【unity笔记】九、Unity添加串口通信

unity仿真使用虚拟串口调试。下面为简单流程。
常用串口调试软件在这里下载。

1.虚拟串口

添加虚拟串口,这里使用com1 com2
在这里插入图片描述

2. 串口调试

在这里为虚拟串口发送消息。
在这里插入图片描述

3. unity配置

3.1 设置

文件->生成设置->玩家设置->玩家->其他设置 中找到 API兼容级别 选项,将其修改为.NET Framework
在这里插入图片描述

3.2 完整脚本代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;

public class abc : MonoBehaviour
{
    public SerialPort uart;
    void Awake()
    {
        uart = new SerialPort
        {
            PortName = "COM2",//串口号
            BaudRate = 115200,//波特率
            DataBits = 8,//数据位
            StopBits = StopBits.One,//停止位
            Parity = Parity.None,//验证位
            DtrEnable = true,
            RtsEnable = true,
            ReadTimeout = 1000
        };

        uart.Open();//启动串口

        Thread recT = new Thread(SerialPort_DataReceived);
        recT.IsBackground = true;
        recT.Start();
    }


    public void SerialPort_DataReceived()
    {
        while (true)
        {
            if (uart.IsOpen)
            {
                var length = uart.BytesToRead;
                if (length > 0)
                {
                    Debug.Log(uart.ReadTo("E"));//指示读取操作停止的位置
                    uart.DiscardInBuffer();
                }
            }
        }
    }
}

4. 通信效果

在这里插入图片描述

5.问题及解决

  1. 串口读取数据错误 IOException: 拒绝访问。
  • 原因
    串口重复打开
  • 解决方法
    检查占用COM2(这里以COM2为例)的程序,或者脚本,同一个脚本中的一个串口不可以同时多次调用。

相关推荐

  1. Unity串口通信教程:基础知识和实践指南

    2024-07-10 15:54:03       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 15:54:03       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 15:54:03       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 15:54:03       4 阅读
  4. Python语言-面向对象

    2024-07-10 15:54:03       5 阅读

热门阅读

  1. C++继承

    C++继承

    2024-07-10 15:54:03      8 阅读
  2. ArcGIS Pro SDK (八)地理数据库 2 定义

    2024-07-10 15:54:03       10 阅读
  3. 面试题 12. 矩阵中的路径

    2024-07-10 15:54:03       13 阅读
  4. 算法整理——【贪心算法练习(2)】

    2024-07-10 15:54:03       13 阅读
  5. RK3588开发笔记-ES8311音频芯片调试记录

    2024-07-10 15:54:03       9 阅读
  6. Selenium 等待

    2024-07-10 15:54:03       9 阅读
  7. MySQL中的JOIN、LEFT JOIN、RIGHT JOIN讲解

    2024-07-10 15:54:03       7 阅读