I made SerialHandler.cs
for connecting Arduino via serial connection.
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using UnityEngine;
public class SerialHandler : MonoBehaviour {
public delegate void SerialDataReceivedEventHandler (string message);
public event SerialDataReceivedEventHandler OnDataReceived = delegate { };
//Port name
public string portName = "/dev/tty.usbmodem1412101";
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_);
}
Debug.Log (message_);
isNewMessageReceived_ = false;
}
void OnDestroy () {
Close ();
}
private void Open () {
serialPort_ = new SerialPort (portName, baudRate, Parity.None, 8, StopBits.One);
// Or
//serialPort_ = new SerialPort(portName, baudRate);
serialPort_.Open ();
serialPort_.NewLine = "\\n";
isRunning_ = true;
thread_ = new Thread (Read);
thread_.Start ();
}
private void Close () {
isNewMessageReceived_ = false;
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 {
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);
}
}
}
And also I wrote an another code for the object inside Unity.
It's called DoSomething.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoSomething : MonoBehaviour {
//先ほど作成したクラス
public SerialHandler serialHandler;
void Start () {
//信号を受信したときに、そのメッセージの処理を行う
// serialHandler.OnDataReceived += OnDataReceived;
}
void Update () {
//文字列を送信
// serialHandler.Write ("hogehoge");
}
//受信した信号(message)に対する処理
void OnDataReceived (string message) {
var data = message.Split (
new string[] { "\\t" }, System.StringSplitOptions.None);
if (data.Length < 2) return;
try {
// try here
Debug.Log (data);
} catch (System.Exception e) {
Debug.LogWarning (e.Message);
}
}
}