这篇文章随手记录之用
前面的博客很多写需要调整Unity的API到.net 2.0,我这个项目使用的Unity2020.1和VS2019,目前调整PlayerSettings中的API版本到.net 4.x时,编译等都正常,不知道具体原因。
代码(已删除无关部分)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System;
public class SerialPortCommunication : MonoBehaviour
{
System.IO.Ports.SerialPort sp = new SerialPort();//创建一个端口
private byte[] openBytes = new byte[4] { 0x0a,0x01,0x01,0xa2};
// Start is called before the first frame update
void Start()
{
//需要依照电脑情况,我这里电脑只有一个占用的COM1,插入之后就是其他的串口号(虽然不同USB接口也不同),但排除一个COM1就行。实际上可以通过串口助手或者设备管理器等确认具体的串口号。
string[] names = SerialPort.GetPortNames();
for (int i = 0; i < names.Length; i++)
if (names[i].ToUpper() != "COM1")
sp.PortName = names[i];
//设置串口的属性
sp.BaudRate = 9600;
sp.WriteTimeout = 5;
sp.ReadTimeout = 5;
try
{
sp.DataReceived += Sp_DataReceived;
sp.Open();//打开串口开始通信
}
catch (Exception e)
{
Debug.Log($"serial error:{e.ToString()}");
}
}
public void Send(string command)
{
try
{
//写入数据并清空缓存,不过后面一句不确定是否需要
sp.Write(command);
sp.BaseStream.Flush();
}
catch (Exception e)
{
Debug.Log($"serial write error:{e.ToString()}");
}
}
public void Send(byte[] command)
{
try
{
//写入数据并清空缓存,不过后面一句不确定是否需要
sp.Write(command, 0, command.Length);
sp.BaseStream.Flush();
}
catch (Exception e)
{
Debug.Log($"serial write error:{e.ToString()}");
}
}
//保留了一个输入接收事件,但因为没有数据所以也没有调试。根据其他博客内容,似乎事件优先级比较低,如此的话似乎可以考虑开子线程随时监听和处理
private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string result=sp.ReadExisting();
PocessRecievedData(result);
}
private void PocessRecievedData(string data)
{
//do something...
}
//退出时关闭串口
private void OnApplicationQuit()
{
if (sp.IsOpen)
sp.Close();
}
}



