Created
August 20, 2014 15:26
-
-
Save hecomi/2d3f9db01319cf1d29a4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 = 57600; | |
private SerialPort serialPort_; | |
private Thread thread_; | |
private bool isRunning_ = false; | |
private string message_; | |
private bool isNewMessageReceived_ = false; | |
void Awake() | |
{ | |
if (!Application.isEditor) { | |
LoadPortFromFile(); | |
} | |
Open(); | |
} | |
void Update() | |
{ | |
if (isNewMessageReceived_) { | |
if (OnDataReceived != null && OnDataReceived.GetInvocationList().Length > 0) { | |
OnDataReceived(message_); | |
} | |
} | |
} | |
void OnDestroy() | |
{ | |
Close(); | |
} | |
[ContextMenu("Load port from file")] | |
private void LoadPortFromFile() | |
{ | |
var path = System.IO.Path.Combine(Application.streamingAssetsPath, "Serial.txt"); | |
using (var sr = System.IO.File.OpenText( path )) { | |
portName = sr.ReadLine(); | |
} | |
} | |
private void Open() | |
{ | |
try { | |
serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One); | |
serialPort_.Open(); | |
isRunning_ = true; | |
thread_ = new Thread(Read); | |
thread_.Start(); | |
Debug.Log("Connected!"); | |
} catch (System.Exception e) { | |
Debug.LogError(e.Message); | |
} | |
} | |
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