UNITY3D串口通信
2021/3/16??????點擊:
UNITY3D串口通信例子
using UnityEngine; using System.Collections; using System.IO; using System.IO.Ports; using System; using System.Collections.Generic; using System.Threading; using System.Text;//16進制轉換 public class U3DSerial : MonoBehaviour { public string portName = "COM1"; public int baudRate = 115200; public Parity parity = Parity.None; public int dataBits = 8; public StopBits stopBits = StopBits.One; SerialPort sp = null; //串口的通信類 byte[] data = new byte[128]; //用戶存儲6位數據 Thread dataReceiveThread; string message = "$";//發送 string msg; //接收到的數據顯示在Label string tip;//提示串口是否打開 string str1 = ""; string str2 = ""; ListliData = new List(); string str = ""; private bool shuJuZJ = false; void Start() { OpenPort(); dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));//開啟線程接收數據 dataReceiveThread.Start(); } void Update() { if (shuJuZJ) { CancelInvoke("XieCheng");//如果str還未接收完整DataReceiveFunction()扔在執行,則快速終止調用 shuJuZJ = false; Invoke("XieCheng", 0.1f);//可根據數據大小來定接收完整數據的時間 } } public void OpenPort() //打開串口 { sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits); sp.ReadTimeout = 400; try { sp.Open(); Debug.Log("串口已經打開"); tip= "串口已經打開"; } catch (Exception ex) { Debug.Log(ex.Message); } } public void ClosePort() //關閉串口 { try { sp.Close(); Debug.Log("關閉串口"); tip= "關閉串口"; } catch (Exception ex) { Debug.Log(ex.Message); } } public void WriteData(string dataStr)//寫入數據 { if (sp.IsOpen) { sp.Write(dataStr); } } void OnApplicationQuit() { ClosePort(); } void DataReceiveFunction() { byte[] buffer = new byte[128]; //string str = string.Empty; //此處只執行一次 //int index = 0; int bytes; while (true) { if (sp != null && sp.IsOpen) // sp != null && { try { //這里面會執行多次,以接收byte[]數據 bytes = sp.Read(buffer, 0, buffer.Length); for (int i = 0; i < bytes; i++) { data[i] = buffer[i]; //將數據存入data //str += data[i].ToString("X2") + "/"; //X表示16進制,2表示兩位數 //index++; } //Debug.Log("長度:" + bytes); if (bytes == 1) { liData.Clear();//添加數據前,先清空泛型數組 str1 = System.Text.Encoding.ASCII.GetString(data, 0, bytes); liData.Add(str1); } else { str2 = System.Text.Encoding.ASCII.GetString(data, 0, bytes); liData.Add(str2); str = ""; foreach (var i in liData) { str += i; } shuJuZJ = true; } } catch (Exception e) { if (e.GetType() != typeof(ThreadAbortException)) { //Debug.Log(e.Message); } } } Thread.Sleep(1); } } void XieCheng() { Debug.Log("*終數據:" + str); //這里接收到的數據str,進行處理 } void OnGUI() //按鈕發送數據 { message = GUILayout.TextField(message); if (GUI.Button(new Rect(100, 100, 100, 30), "Send Message")) { WriteData(message); } string by = "AA"; if (GUI.Button(new Rect(100, 150, 100, 30), "Send")) { WriteData(by); } GUILayout.Label(msg); if (GUI.Button(new Rect(100, 200, 100, 30), "Quit")) { Application.Quit(); } GUILayout.Label(tip); } }
- 上一篇:UNITY3D C#開發ANDROID APP調用串口 2021/3/18
- 下一篇:LINUX串口通信 2021/3/16