You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
119 lines
2.9 KiB
119 lines
2.9 KiB
using System; |
|
using System.Collections; |
|
using System.Collections.Generic; |
|
using System.IO.Ports; |
|
using System.Threading; |
|
using UnityEngine; |
|
|
|
public class UnitySerialPort : MonoBehaviour |
|
{ |
|
private SerialPort serialPort; |
|
private Thread readPortData; |
|
|
|
public int[] SpeedValueArr; |
|
int ClientCount = 2; |
|
|
|
public List<byte> listReceive = new List<byte>(); |
|
|
|
private void Start() |
|
{ |
|
SpeedValueArr = new int[ClientCount]; |
|
try |
|
{ |
|
serialPort = new SerialPort("COM4", 115200); |
|
serialPort.ReadTimeout = 500; |
|
if (!serialPort.IsOpen) |
|
{ |
|
serialPort.Open(); |
|
} |
|
|
|
readPortData = new Thread(new ThreadStart(readData)); |
|
readPortData.IsBackground = true; |
|
readPortData.Start(); |
|
} |
|
catch (Exception) |
|
{ |
|
throw; |
|
} |
|
} |
|
|
|
private void OnDestroy() |
|
{ |
|
if (serialPort.IsOpen) |
|
serialPort.Close(); |
|
readPortData.Abort(); |
|
} |
|
|
|
|
|
/// <summary> |
|
/// 读取数据 |
|
/// </summary> |
|
private void readData() |
|
{ |
|
try |
|
{ |
|
while (serialPort != null && serialPort.IsOpen) |
|
{ |
|
byte addr = Convert.ToByte(serialPort.ReadByte()); |
|
serialPort.DiscardInBuffer(); |
|
listReceive.Add(addr); |
|
ParseReceive(); |
|
PrintData(); |
|
print(serialPort.ReadLine()); |
|
} |
|
} |
|
catch (Exception) |
|
{ |
|
throw; |
|
} |
|
} |
|
|
|
/// <summary> |
|
/// 打印数据 |
|
/// </summary> |
|
void PrintData() |
|
{ |
|
string str = string.Empty; |
|
for (int i = 0; i < listReceive.Count; i++) |
|
{ |
|
str += listReceive[i].ToString("X2"); //这里只会得到数据 FC |
|
} |
|
|
|
string Data = System.Text.Encoding.Default.GetString(listReceive.ToArray()); |
|
//print(Data); |
|
} |
|
|
|
private void ParseReceive() |
|
{ |
|
if (listReceive.Count < ClientCount + 2) |
|
{ |
|
return; |
|
} |
|
for (int i = 0; i < ClientCount; i++) |
|
{ |
|
SpeedValueArr[i] = listReceive[listReceive.Count - 1 - i]; //这里只会得到数据 252 |
|
} |
|
listReceive.RemoveRange(0, ClientCount + 2); |
|
} |
|
|
|
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) |
|
{ |
|
Debug.Log("???"); |
|
try |
|
{ |
|
System.Threading.Thread.Sleep(20); |
|
byte[] _data = new byte[serialPort.BytesToRead]; |
|
serialPort.Read(_data, 0, _data.Length); |
|
if (_data.Length == 0) { return; } |
|
if (serialPort != null) |
|
{ |
|
print(_data); |
|
} |
|
//_serialPort.DiscardInBuffer(); //清空接收缓冲区 |
|
} |
|
catch (Exception ex) |
|
{ |
|
throw ex; |
|
} |
|
} |
|
} |