可以通過計算機管理->設備管理器,查看端口
串口通訊,通常是指的通過計算機或其他設備上的串行端口實現數據傳輸的過程。
定義與特點:串口通訊是按位(bit)發送和接收字節的通信方式,它將數據一位一位地順序傳輸。其特點是使用的數據線少,通常只需兩根線就可以實現雙向通信,并且能夠實現遠距離通信,比如串口通信的長度可達 1200 米,而并行通信設備線總長不得超過 20 米。
工作原理:串口通信采用 UART(通用異步收發傳輸器)協議進行數據傳輸。發送端的 UART 將并行數據轉換為串行數據,在數據字節前發送起始位,然后依次發送數據字節的每個 Bit,最后發送停止位。接收端的 UART 檢測到起始位后開始接收數據位和停止位,并將串行數據轉換為并行數據。
關鍵參數
每秒位數(波特率):表示每秒鐘傳輸的位數,常見的波特率有 4800bps、9600bps、19200bps 等。波特率越高,數據傳輸速度越快,但也可能帶來更高的誤碼率。
數據位:指實際傳輸的數據位數,可能為 5、6、7、8 位等,標準的 ASCII 碼是 7 位,擴展的 ASCII 碼是 8 位。
奇偶校驗位:用于接收方對接收到的數據進行校驗,校驗方式有奇校驗、偶校驗等,以判斷數據在傳輸過程中是否出現錯誤。
停止位:用于表示單個包的最后一位,典型的值為 1、1.5 和 2 位。停止位的位數越多,不同時鐘同步的容忍程度越大,但數據傳輸率也越慢。
使用C# System.IO.Ports
下進行串口通訊,這邊有個注意的地方就是從,net 2開始才有,如果沒有命名空間,可以更改一下ProjectSetting->Player->Configuration-> API Compatibility Level
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;public class SerialPortBridge : MonoBehaviour
{#region 定義串口屬性//定義基本信息public string portName = "COM7";//串口名public int baudRate = 115200;//波特率public Parity parity = Parity.None;//校驗位public int dataBits = 8;//數據位public StopBits stopBits = StopBits.One;//停止位SerialPort sp = null;Thread dataReceiveThread;//發送的消息string message = "";public List<byte> listReceive = new List<byte>();char[] strchar = new char[100];//接收的字符信息轉換為字符數組信息string str;#endregionvoid Start(){OpenPort();dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));dataReceiveThread.Start();}void Update(){}#region 創建串口,并打開串口public void OpenPort(){//創建串口sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);sp.ReadTimeout = 400;try{sp.Open();}catch (Exception ex){Debug.Log(ex.Message);}}#endregion#region 程序退出時關閉串口void OnApplicationQuit(){ClosePort();}public void ClosePort(){try{sp.Close();dataReceiveThread.Abort();}catch (Exception ex){Debug.Log(ex.Message);}}#endregion/// <summary>/// 打印接收的信息/// </summary>void PrintData(){for (int i = 0; i < listReceive.Count; i++){strchar[i] = (char)(listReceive[i]);str = new string(strchar);}Debug.Log(str);}#region 接收數據void DataReceiveFunction(){byte[] buffer = new byte[1024];int bytes = 0;while (true){if (sp != null && sp.IsOpen){try{bytes = sp.Read(buffer, 0, buffer.Length);//接收字節if (bytes == 0){continue;}else{string strbytes = Encoding.Default.GetString(buffer);Debug.Log(strbytes);}}catch (Exception ex){if (ex.GetType() != typeof(ThreadAbortException)){}}}Thread.Sleep(10);}#endregion}#endregion#region 發送數據public void WriteData(string dataStr){if (sp.IsOpen){sp.Write(dataStr);}}void OnGUI(){message = GUILayout.TextField(message);if (GUILayout.Button("Send Input")){WriteData(message);}string test = "AA BB 01 12345 01AB 0@ab 發送";//測試字符串if (GUILayout.Button("Send Test")){WriteData(test);}}#endregion
}
其實這邊更推薦插件SerialPortUtilityPro,C#原生的限制很大,串口相關的功能這個插件都封裝好了,傻瓜式使用。
直接掛一下核心組件 SerialPortUtilityPro,直接在面板上設置好需要的參數,設備號,廠商號,端口可以不填,會自動掃描,填了會主動連接設置的端口,然后ReadCompleteEventObject中去添加UnityEvent事件,去響應收到的消息。