ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Unity 串口通信消息不完整

Unity 串口通信消息不完整 public string portName COM1;//串口名 public int baudRate 9600;//波特率 public Parity parity Parity.None;//效验位 public int dataBits 8;//数据位 public StopBits stopBits StopBits.One;//停止位 SerialPort sp null; Thread dataReceiveThread; // 串口接收相关 private readonly ConcurrentQueuebyte[] receivedFrames new ConcurrentQueuebyte[](); private byte[] frameBuffer new byte[4096]; private int frameLen 0; private DateTime lastByteTime DateTime.MinValue; private const int FRAME_GAP_MS 60; // 60ms 内无新字节 认为一帧结束 private volatile bool serialRunning false; void Start() { OpenPort(); serialRunning true; dataReceiveThread new Thread(new ThreadStart(DataReceived)); dataReceiveThread.IsBackground true; dataReceiveThread.Start(); } void Update() { // 处理串口帧 while (receivedFrames.TryDequeue(out byte[] frame)) { string hex BytesToHex(frame); Debug.Log($RX ({frame.Length}B): {hex}); if (frame.Length 10 || frame.Length 12) { string lower hex; // BytesToHex 已经返回小写 //处理消息 } } } private void OnDisable() { try { serialRunning false; // 让子线程自己退出 if (dataReceiveThread ! null dataReceiveThread.IsAlive) dataReceiveThread.Join(500); } catch { } } void OnApplicationQuit() { serialRunning false; ClosePort(); } public void OpenPort() { //创建串口 sp new SerialPort(portName, baudRate, parity, dataBits, stopBits); sp.ReadTimeout 400; try { sp.Open(); } catch (Exception ex) { Debug.Log(ex.Message); } } public void ClosePort() { try { if (sp ! null sp.IsOpen) sp.Close(); } catch (Exception ex) { Debug.Log(ex.Message); } } public void DataReceived() { byte[] temp new byte[256]; while (serialRunning) { try { if (sp null || !sp.IsOpen) { Thread.Sleep(50); continue; } int count sp.BytesToRead; if (count 0) { if (count temp.Length) count temp.Length; int n sp.Read(temp, 0, count); for (int i 0; i n; i) { if (frameLen frameBuffer.Length) { Debug.LogWarning(帧缓冲溢出重置缓冲区); frameLen 0; } frameBuffer[frameLen] temp[i]; } lastByteTime DateTime.Now; } else { // 静默超过阈值 一帧结束整帧入队 if (frameLen 0 (DateTime.Now - lastByteTime).TotalMilliseconds FRAME_GAP_MS) { byte[] frame new byte[frameLen]; Buffer.BlockCopy(frameBuffer, 0, frame, 0, frameLen); frameLen 0; receivedFrames.Enqueue(frame); } Thread.Sleep(5); } } catch (ThreadAbortException) { break; } catch (Exception ex) { Debug.LogWarning(串口读取异常: ex.Message); Thread.Sleep(50); } } } private static string BytesToHex(byte[] data) { var sb new StringBuilder(data.Length * 2); for (int i 0; i data.Length; i) sb.Append(data[i].ToString(x2)); return sb.ToString(); }
返回列表