Unity中使用串口的注意事项

在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 ();


}

以上仅供大家参考。

.net2.0 直接使用2.0 不要使用subset

使用scripting Runtime Version 为3.5 否则容易接收数据不正常

 

unity中的参考实例点此下载
--------------------- 
作者:夫人的泡泡鱼 
来源:CSDN 
原文:https://blog.csdn.net/zqckzqck/article/details/77540506 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值