前几天群里有朋友有做串口通信的需求,开始以为可以直接用串口的接收事件,结果发现U3D默认不支持,如果要通过转换来实现的话很麻烦,没有调试成功,到网上搜索一番,发现有位网友之前做过,使用的是开线程接收,这样原理上和事件应该差的不错。于是通过对他代码的修改,终于测试出了一版暂时没什么问题的,跟大家分享一下,代码如下:
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Text;
public class SerialPortReciever : MonoBehaviour
{
private SerialPort sp;
private Queue<string> queueDataPool;
private Thread tPort;
private Thread tPortDeal;
private string strOutPool = string.Empty;
string finalstring = string.Empty;
string tempstring = string.Empty;
// Use this for initialization
void Start()
{
queueDataPool = new Queue<string>();
sp = new SerialPort(“COM1”, 9600, Parity.None, 8, StopBits.One);
if (!sp.IsOpen)
{
sp.Open();
}
tPort = new Thread(DealData);
tPort.Start();
tPortDeal = new Thread(ReceiveData);
tPortDeal.Start();
}
// Update is called once per frame
void Update()
{
if (!tPortDeal.IsAlive)
{
tPortDeal = new Thread(ReceiveData);
tPortDeal.Start();
}
if (!tPort.IsAlive)
{
tPort = new Thread(DealData);
tPort.Start();
}
}
private void ReceiveData()
{
try
{
Byte[] buf = new Byte[1];
string sbReadline2str = string.Empty;
if (sp.IsOpen) sp.Read(buf, 0, 1);
if (buf.Length == 0)
{
return;
}
if (buf != null)
{
for (int i = 0; i < buf.Length; i++)
{
sbReadline2str += buf.ToString(“X2”);
queueDataPool.Enqueue(sbReadline2str);
}
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
private void DealData()
{
while (queueDataPool.Count != 0)
{
for (int i = 0; i < queueDataPool.Count; i++)
{
strOutPool+= queueDataPool.Dequeue();
if(strOutPool.Length==16)
{
Debug.Log(strOutPool);
strOutPool=string.Empty;
}
}
}
}
private void SendSerialPortData(string data)
{
if(sp.IsOpen)
{
sp.WriteLine(data);
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
其中代码里有一句是if(strOutPool.Length==16),这里可以把16改成任何你需要的数字,这个数字的依据是串口发送过来数据每组的长度,比如串口调试助手接收到的数据是如下:
图片:未命名.jpg