using UnityEngine;
using System.Collections;
using System.IO.Ports;
using SerialLib;
public class SerialReceiver : MonoBehaviour
{
public bool isDebug;
private string URL = "/dev/cu.usbmodem1412";
private int PORT = 115200;
[SerializeField]
private UnitySerial _serial;
// Use this for initialization
void OnEnable()
{
_serial = new UnitySerial(URL, PORT, 1000);
_serial.ThreadStart();
}
public string output;
// Update is called once per frame
void Update()
{
var tmp = _serial.GetData();
if (string.IsNullOrEmpty(tmp) == false)
{
Debug.Log(tmp);
output = _serial.GetData();
}
}
void OnGUI()
{
if (GUILayout.Button("Send"))
{
_serial.Write("hoge");
}
}
void OnDisable()
{
if (_serial != null)
{
_serial.ThreadEnd();
}
}
}
using System;
using System.Threading;
using System.IO.Ports;
using System.Runtime.InteropServices;
using UnityEngine;
namespace SerialLib
{
[System.Serializable]
public class UnitySerial
{
SerialPort serial;
byte[] buf;
[TextArea(5, 5), SerializeField]
string message;
Thread SerialThread;
[SerializeField]
bool isThreading = false;
public UnitySerial(string portName, int baudRate, int bufSize)
{
buf = new byte[bufSize];
Init(portName, baudRate);
SerialThread = new Thread(this.UpdateData);
}
public void ThreadStart()
{
SerialThread.Start();
}
public void ThreadEnd()
{
isThreading = false;
SerialThread.Abort();
serial.Close();
}
void Init(string portName, int baudRate)
{
serial = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
try
{
serial.Open();
serial.DtrEnable = true;
serial.RtsEnable = true;
serial.DiscardInBuffer();
serial.ReadTimeout = 5000;
}
catch (Exception e)
{
Debug.LogWarning("Init : " + e.Message);
}
}
public string GetData()
{
return message;
}
public void UpdateData()
{
isThreading = true;
while (isThreading)
{
try
{
message = serial.ReadLine();
}
catch (TimeoutException e)
{
Debug.LogWarning(e.Message);
}
}
}
public void Write(string v)
{
serial.WriteLine(v);
}
}
}