数据发送
串口通信发送数据时需要将数据转换为十六进制内容
using UnityEngine;
using System;
using System.IO.Ports;
public class spSend : MonoBehaviour
{
public SerialPort sp; //串口名字
static public byte[] strSend = new byte[3];
void Start()
{
sp = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One);
//串口初始化
try
{
sp.Open();
Debug.Log("成功打开");
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
//关闭串口
void OnApplicationQuit()
{
sp.Close();
Application.Quit();
}
//发送
public void SendData(byte[] data)
{
if (sp.IsOpen)
{
sp.Write(data, 0, 3);
}
}
}
发送数据使用示例:
spSend.strSend = new byte[3] { 0X43, 0X50, 0X31 };
COM.GetComponent<spSend>().SendData(spSend.strSend);
数据接收
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Threading;
using System.Collections.Generic;
using System.IO.Ports;
public class spReceive : MonoBehaviour
{
public SerialPort sp; //串口名字
private Thread recvThread; //接收线程
//private Thread dealThread; //处理线程
Queue<byte> queueDataPool = new Queue<byte>(); //队列数据池
private byte[] receiveData = new byte[3];
public bool isStartThread; //控制FixedUpd里面的两个线程是否调用(当准备调用串口的Close方法时设置为false)
void Start()
{
isStartThread = true;
sp = new SerialPort("COM9", 38400, Parity.None, 8, StopBits.One);
//串口初始化
try
{
sp.Open();
Debug.Log("成功打开");
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
recvThread = new Thread(new ThreadStart(ReceiveData));
recvThread.Start();
//dealThread = new Thread(new ThreadStart(DealData));
//dealThread.Start();
}
void OnApplicationQuit()
{
isStartThread = false;
sp.Close();
Application.Quit();
}
void Update()
{
DealData();
}
//接收
private void ReceiveData()
{
while (isStartThread)
{
//Debug.Log(sp.PortName);
if (sp != null && sp.IsOpen)
{
try
{
byte[] buf = new byte[1];
sp.Read(buf, 0, 1);
if (buf.Length == 0)
{
return;
}
if (buf != null)
{
queueDataPool.Enqueue(buf[0]);
Debug.Log(buf[0]);
}
}
catch (Exception e)
{
if (e.GetType() != typeof(ThreadAbortException))
{
Debug.Log(e.Message);
}
}
}
}
}
//处理
private void DealData()
{
//使用队列处理接收到的数据
if ( queueDataPool.Count == 3 ) {
receiveData[0] = queueDataPool.Dequeue();
receiveData[1] = queueDataPool.Dequeue();
receiveData[2] = queueDataPool.Dequeue();
Debug.Log(string.Format("{0},{1},{2}", receiveData[0], receiveData[1], receiveData[2]));
}
}
}
为避免接收和发送时数据丢失,使用两个COM端口分别传输,本例中数据发送使用COM8口,数据接收使用COM9口。