Unity串列埠通訊
阿新 • • 發佈:2018-11-19
通過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 (); }
}