Unity接硬件串口

本文介绍了如何在Unity中进行硬件串口通信,包括PortControl脚本用于控制硬件串口数据,以及PortDispose脚本用于处理串口数据的读取。通过这两个脚本,可以实现Unity与外部设备的数据交互。
摘要由CSDN通过智能技术生成

一、PortControl脚本(硬件串口数据)

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

public class PortControl : MonoBehaviour
{
   
    public static PortControl Instance;
 
    #region 定义串口属性
    //定义基本信息
    public string portName = "COM5";//串口名
    public int baudRate = 115200;//波特率
    public Parity parity = Parity.None;//效验位
    public int dataBits = 8;//数据位
    public StopBits stopBits = StopBits.One;//停止位
    public SerialPort sp = null;  
    public Thread dataReceiveThread;
    public Thread dataSendThread;
    //发送数据
    public List<byte> listReceive = new List<byte>();
    public Queue<byte[]> recBuffer = new Queue<byte[]>();//接受所有的buffer  队列 先进先出
    public Queue<byte[]> sendBuffer = new Queue<byte[]>();//发包  队列
    char[] strchar = new char[100];//接收的字符信息转换为字符数组信息
    string str;
    byte[] buffer = new byte[1024];
    byte[] receiveBuffer = new byte[1024];
    int receivePosition;
    #endregion
    void Start()
    {
   
        Instance = this;
        dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));
        dataReceiveThread.Start();
        dataSendThread = new Thread(new ThreadStart(WriteData));
        dataSendThread.Start();
        //ThreadPool.QueueUserWorkItem(new WaitCallback(WriteData));
    }
 
    #region 创建串口,并打开串口
    public void OpenPort()
    {
   
        //创建串口
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        sp.ReadTimeout =800;//操作超出时间 这个时间越长报错越少,但不能太长
        try
        {
   
            sp.Open
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值