Unity串口通信

Unity技术QQ群:484275915,有需要可以加群相互探讨
用Unity串口编程很长时间了,一直轻信网上的观点,以为Unity不支持COM10以上的串口,根本跟Unity没有关系好嘛?!所以千万别轻信网上人说的什么不支持这不支持那,多研究,多研究,多研究。重要的事情说三遍。
吐槽完我们来好好聊一下Unity串口通信的方法。一共分为以下几个步骤

  1. 将Unity的.NET库从.NET 2.0 Subset改为.NET 2.0,原因是子集库太小了,不包含串口的类库。
    选择Edit->Project Settings -> Player->Api Compatibility Level
    如果不设置会报下面这个错误:
The type or namespace name `Ports' does not exist in the namespace `System.IO'. Are you missing an assembly reference?

以下是修改图解:
Unity串口通信_第1张图片
Unity串口通信_第2张图片
2. 第二步新建一个脚本,引入类库:

using System.IO.Ports;

3.串口的使用,请注意看注释说明

	private string[] allPorts;
    private byte[] contentData;
    private byte[] writeData;
    void Start()
    {
        allPorts = SerialPort.GetPortNames();//这一步是动态获取目前计算机检测到的所有串口
        
        //中间可以增加一些对allPorts的处理算法,可以用来过滤掉自己不需要的串口拿到自己的目标串口
        
        SerialPort sp = new SerialPort(allPorts[0], 115200, Parity.None, 8, StopBits.One);//此处以allPorts第0个串口名称为例打开串口,我们称"sp"为次串口操作的句柄
        sp.Read(contentData, 0, 68);//读取数据
        sp.Write(writeData, 0, 7);//写入数据
        sp.Close();//关闭串口
        sp.Dispose();//将串口从内存中释放掉,注意如果这里不释放则在同一次运行状态下打不开此关闭的串口
    }

    void Update()
    {
        GarbageCollection();//在不断接收数据的过程中可能清理垃圾
    }
    private void GarbageCollection()
    {
        if (Time.frameCount % 120 == 0) System.GC.Collect();
    }

你可能感兴趣的:(unity)