Unity中使用串口的注意事项

来源:互联网 发布:类似算法谜题的书 编辑:程序博客网 时间:2024/05/17 22:23

在unity中使用串口不如WinForm或者MFC中那样有对应的回调函数或者消息来处理,unity中使用的是线程去处理读取数据、处理粘包数据等问题,具体在使用中可能遇到下面问题:

1、程序在打开串口后,关闭不了(只能调出任务管理器,结束任务来处理);

2、读取串口数据时总是丢失第一个字节的数据;

3、串口拒绝访问。

以上可能是你正在苦恼的问题,我也是一样,再次分享自己的解决方法。

第一和第三问题可能是同一问题导致的,那就是串口在打开后使用,在退出程序时,没有调用Close关闭或者说你没有成功关闭导致了程序卡死。

我工程中的一个通信是,当上位机发送数据请求时,下位机上报数据给上位机。

同样采用两个线程分别来读取串口数据和处理串口数据:

float timeInternal = 0.2f;//给下位机发送的时间间隔float timeCount = 0f;byte[] dataCmd = new byte[18];List<byte> liststr;//在ListByte中读取数据,用于数据处理List<byte> listByte;//存放读取的串口数据private Thread tPort;//串口数据读取线程private Thread tPortDeal;//串口数据处理线程bool isStartThread;//控制FixedUpdate里面的两个线程是否调用(当准备调用串口的close方法时设置为false)SerialPort sp;

在Start函数中完成初始化

isStartThread = true;liststr = new List<byte> ();listByte = new List<byte> ();sp = new SerialPort ("COM3", 9600, Parity.None, 8, StopBits.One);try{sp.Open();}catch(Exception e) {Debug.Log (e.ToString ());}tPort = new Thread (ReceiveData);tPort.Start ();tPortDeal = new Thread (DealData);tPortDeal.Start ();
在OnFixedUpdate中检测串口线程是否开启

void FixedUpdate(){if (isStartThread) {if (!tPortDeal.IsAlive) {tPortDeal = new Thread (DealData);tPortDeal.Start ();}if (!tPort.IsAlive) {tPort = new Thread (ReceiveData);tPort.Start ();}} else {if (tPortDeal.IsAlive) {tPortDeal.Abort ();}if (tPort.IsAlive) {tPort.Abort ();}}}
下面是串口数据接收线程的响应函数

void ReceiveData(){try{byte[] buf = new byte[128];int retLen = 0;if(sp.IsOpen){retLen = sp.Read(buf,0,buf.Length);}if(buf.Length==0){return;}if(buf!=null){for(int i=0;i<retLen;i++){listByte.Add(buf[i]);}}}catch(Exception e) {//Debug.Log (e.ToString ());//打开之后有提示报错,不影响}}
在使用过程中,我用sp.Read(buf,0,1);按单个字节读取,出现了丢失第一个字节的问题。我的数据是18个字节为报文发送的,所以经过尝试得出了结论是用一个较大buffer去读取,保证数据的完整。根据Read的返回值,得到读取的字节长度。

在catch中,用debug输出会发现有at System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0 
  at System.IO.Ports.SerialPort.Read (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Read (byte[],int,int)
  at CtrlJoy.ReceiveData () [0x0001d] in C:\Users\chukai\Desktop\JoyStickTest\Assets\CtrlJoy.cs:104 
UnityEngine.Debug:Log(Object)

这样的报错,我没处理它,因为没有影响到程序的执行效果。

最后是数据处理线程函数

void ReceiveData(){try{byte[] buf = new byte[128];int retLen = 0;if(sp.IsOpen){retLen = sp.Read(buf,0,buf.Length);}if(buf.Length==0){return;}if(buf!=null){for(int i=0;i<retLen;i++){listByte.Add(buf[i]);}}}catch(Exception e) {//Debug.Log (e.ToString ());//打开之后有提示报错,不影响}}void DealData(){string strOut = "";for (int i = 0; i < listByte.Count; i++) {liststr.Add (listByte [0]);listByte.Remove (listByte [0]);}//根据自己的通信协议进行处理//这里主要是粘包的处理及格式的正确解析int pos = 0;for (int i = 0; i < liststr.Count; i++){if (liststr [i] == 0x24) {pos = i;} }for(int i=0;i<pos;i++)liststr.Remove (liststr [0]);if (liststr.Count >= 18 && liststr[0]==0x24&&liststr[17]==0x40){liststr.CopyTo (0,dataCmd,0,18);for (int i = 0; i < 18; i++){//strOut += dataCmd [i].ToString ()+" ";liststr.Remove (liststr [0]);}//Debug.Log (strOut);//liststr.Clear ();}}

在退出程序之前,切记要先停止数据接收线程,再关闭串口,退出程序

void OnDestroy()
{
isStartThread = false;


if (tPortDeal.IsAlive) {
tPortDeal.Abort ();
}
if (tPort.IsAlive) {
tPort.Abort ();
}
sp.Close ();
Debug.Log ("close");
Application.Quit ();


}

以上仅供大家参考。

unity中的参考实例点此下载


原创粉丝点击