SerialHandler.cs
1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
// code: https://qiita.com/yjiro0403/items/54e9518b5624c0030531
public class SerialHandler : MonoBehaviour
{
public delegate void SerialDataReceivedEventHandler(string message);
public event SerialDataReceivedEventHandler OnDataReceived;
public string portName = "COM1";
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_);
}
isNewMessageReceived_ = false;
}
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()
{
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);
}
}
}