unity3d采用串口通信,怎么接收数据?

2025-04-30 00:23:07
推荐回答(3个)
回答1:

  通过System.IO.Ports来实现

    using UnityEngine;
  using System.Collections;
  using System.IO.Ports;
  using System;
  using System.IO;
  using System.Collections.Generic;
  public class PortControl : MonoBehaviour
  {
      public string portName = "COM3";
      public int baudRate = 57600;
      public Parity parity = Parity.None;
      public int dataBits = 8;
      public StopBits stopBits = StopBits.One;
      SerialPort sp = null;
    
      void Start()
      {
          OpenPort();
          StartCoroutine(DataReceiveFunction());
      }
    
      //打开串口
      public void OpenPort()
      {
          sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
          sp.ReadTimeout = 400;
          try
          {
              sp.Open();
          }
          catch(Exception ex)
          {
              Debug.Log(ex.Message);
          }
      }
    
      //关闭串口
      public void ClosePort()
      {
          try
          {
              sp.Close();
          }
          catch(Exception ex)
          {
              Debug.Log(ex.Message);
          }
      }
    
      /*
      若串口数据速度慢,数量小,可以在Update函数中使用sp.ReadByte等函数,该协程可以不用调用
      若串口数据速度较快,数量较多,就调用该协程(该程序就是这一种,在Start函数中已经被调用)
      若串口数据速度非常快,数量非常多,建议使用Thread
      */
      IEnumerator DataReceiveFunction()
      {
          byte[] dataBytes = new byte[128];//存储数据
          int bytesToRead = 0;//记录获取的数据长度
        
          while(true)
          {
              if(sp != null && sp.IsOpen)
              {
                  try
                  {
                      //通过read函数获取串口数据
                      bytesToRead = sp.Read(dataBytes, 0, dataBytes.Length);
                      //串口数据已经被存入dataBytes中
                      //往下进行自己的数据处理
                      //比如将你的数据显示出来,可以利用guiText.text = ....之类
                  }
                  catch(Exception ex)
                  {
                      Debug.Log(ex.Message);
                  }
                }
                yield return new WaitForSeconds(Time.deltaTime);
          } 
      }
    
      void OnApplicationQuit()
      {
          ClosePort ();
      }
  }

回答2:

http://blog.csdn.net/braveyoung123/article/details/8799987我13年的时候做过了,看我博客

回答3:

有个C#写好的软件直接用就可以