Unity串口通讯

通过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中
                  //往下进行自己的<a href="https://www.baidu.com/s?wd=%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YLmWnLP1-huHTvrjPbmhcL0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1DLPHT1rjT3PjTknHRznWmsP0" target="_blank" class="baidu-highlight">数据处理</a>
                  //比如将你的数据显示出来,可以利用guiText.text = ....之类
              }
              catch(Exception ex)
              {
                  Debug.Log(ex.Message);
              }
            }
            yield return new WaitForSeconds(Time.deltaTime);
      } 
  }

  void OnApplicationQuit()
  {
      ClosePort ();
  }

  }

猜你喜欢

转载自blog.csdn.net/qq_25325511/article/details/50418385
今日推荐