Created
October 28, 2015 17:43
-
-
Save hecomi/f16a006cc0942a917cb3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.IO.Ports; | |
using System.Threading; | |
public class SerialHandler : MonoBehaviour | |
{ | |
public delegate void SerialDataReceivedEventHandler(string message); | |
public event SerialDataReceivedEventHandler OnDataReceived; | |
public string portName = "/dev/tty.usbmodem1421"; | |
public int baudRate = 9600; | |
private SerialPort serialPort_; | |
private Thread thread_; | |
private bool isRunning_ = false; | |
private string message_; | |
private bool isNewMessageReceived_ = false; | |
void Awake() | |
{ | |
Open(); | |
} | |
void Update() | |
{ | |
if (isNewMessageReceived_) { | |
OnDataReceived(message_); | |
} | |
} | |
void OnDestroy() | |
{ | |
Close(); | |
} | |
private void Open() | |
{ | |
serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One); | |
serialPort_.Open(); | |
isRunning_ = true; | |
thread_ = new Thread(Read); | |
thread_.Start(); | |
} | |
private void Close() | |
{ | |
isRunning_ = false; | |
if (thread_ != null && thread_.IsAlive) { | |
thread_.Join(); | |
} | |
if (serialPort_ != null && serialPort_.IsOpen) { | |
serialPort_.Close(); | |
serialPort_.Dispose(); | |
} | |
} | |
private void Read() | |
{ | |
while (isRunning_ && serialPort_ != null && serialPort_.IsOpen) { | |
try { | |
// if (serialPort_.BytesToRead > 0) { | |
message_ = serialPort_.ReadLine(); | |
isNewMessageReceived_ = true; | |
// } | |
} catch (System.Exception e) { | |
Debug.LogWarning(e.Message); | |
} | |
} | |
} | |
public void Write(string message) | |
{ | |
try { | |
serialPort_.Write(message); | |
} catch (System.Exception e) { | |
Debug.LogWarning(e.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment