1、串口簡介
串行接口(串口)通常指COM接口,是采用串行通信方式的擴(kuò)展接口。串口按位(bit)發(fā)送和接收字節(jié)。盡管比按字節(jié)(byte)的并行通信慢,但是串口可以在使用一根線發(fā)送數(shù)據(jù)的同時(shí)用另一根線接收數(shù)據(jù)。特別適用于遠(yuǎn)距離通信。
查看串口:右鍵 我的電腦-管理-設(shè)備管理器-端口
選擇一個(gè)端口,雙擊查看屬性。
這里通過串口屬性,可以知道以下數(shù)據(jù):
波特率:這是一個(gè)衡量符號(hào)傳輸速率的參數(shù)。
數(shù)據(jù)位:這是衡量通信中實(shí)際數(shù)據(jù)位的參數(shù)。
停止位:用于表示單個(gè)包的最后一位。
奇偶校驗(yàn):在串口通信中一種簡單的檢錯(cuò)方式。
對(duì)于兩個(gè)進(jìn)行通信的端口,這些參數(shù)必須匹配。
3、串口通信原理:
串行接口在嵌入式系統(tǒng)中是一種重要的數(shù)據(jù)通信接口,其本質(zhì)功能是作為CPU和串行設(shè)備間的編碼轉(zhuǎn)換器。在發(fā)送數(shù)據(jù)時(shí),數(shù)據(jù)從CPU經(jīng)串行端口,字節(jié)數(shù)據(jù)轉(zhuǎn)換為串行的位;在接收數(shù)據(jù)時(shí),串行的位轉(zhuǎn)換為字節(jié)數(shù)據(jù)。
4、常用的協(xié)議:
RS-232: 標(biāo)準(zhǔn)串口,最常用的一種串行通訊接口采取不平衡傳輸方式,即所謂單端通訊, 是為點(diǎn)對(duì)點(diǎn)通訊而設(shè)計(jì)的。
RS-422: 支持點(diǎn)對(duì)多的雙向通信。采用單獨(dú)的發(fā)送和接收通道,因此不必控制數(shù)據(jù)方向,各裝置之間任何必須的信號(hào)交換均可以按軟件方式(XON/XOFF握手)或硬件方式(一對(duì)單獨(dú)的雙絞線)實(shí)現(xiàn)。
RS-485: 從RS-422基礎(chǔ)上發(fā)展而來的, RS-485可以采用二線與四線方式,二線制可實(shí)現(xiàn)真正的多點(diǎn)雙向通信,而采用四線連接時(shí),與RS-422一樣只能實(shí)現(xiàn)點(diǎn)對(duì)多的通信,但它比RS-422有改進(jìn),無論四線還是二線連接方式總線上可多接到32個(gè)設(shè)備。
串口的接口標(biāo)準(zhǔn)規(guī)范9針串口:
針腳功能:
1、數(shù)據(jù)載波檢測(cè)(DCD)
2、串口接收數(shù)據(jù)(RXD)
3、串口發(fā)出數(shù)據(jù)(TXD)
4、數(shù)據(jù)終端就緒(DTR)
5、信號(hào)地線(GND)
6、數(shù)據(jù)發(fā)送就緒(DSR)
7、發(fā)送數(shù)據(jù)請(qǐng)求(RTS)
8、清除發(fā)送(CTS)
9、鈴聲指示(RI)
我在現(xiàn)在用的是CH340芯片進(jìn)行傳輸
二、使用C#和Unity進(jìn)行串口編程
在對(duì)串口進(jìn)行編程時(shí)候,我們要向串口發(fā)送指令,然后我們解析串口返回的指令。從.NET Framework 2.0開始,C#提供了SerialPort類用于實(shí)現(xiàn)串口控制。命名空間:System.IO.Ports。詳細(xì)信息可以參看(MSDN技術(shù)文檔)
1、 常用的字段:
PortName:獲取或設(shè)置通信端口
BaudRate:獲取或設(shè)置串行波特率
DataBits:獲取或設(shè)置每個(gè)字節(jié)的標(biāo)準(zhǔn)數(shù)據(jù)位長度
Parity:獲取或設(shè)置奇偶效驗(yàn)檢查協(xié)議
StopBits:獲取或設(shè)置每個(gè)字節(jié)的標(biāo)準(zhǔn)停止位數(shù)
2、 常用方法:
Close:關(guān)閉端口連接,將IsOpen屬性設(shè)置false,并釋放內(nèi)部Stream對(duì)象
GetPortNames:獲取當(dāng)前計(jì)算機(jī)的串行端口名稱數(shù)組
Open:打開一個(gè)新的串行端口連接
Read:從SerialPort輸入緩沖區(qū)中讀取
Write:將數(shù)據(jù)寫入串行端口輸出緩沖區(qū)
3、常用事件:
DataReceived:表示將處理SerialPort對(duì)象的數(shù)據(jù)接收事件的方法
DisPosed:通過調(diào)用釋放組件時(shí)發(fā)生Dispose方法(繼承自Component)
4、SerialPort 控件使用流程
流程是設(shè)置通信端口號(hào)及波特率、數(shù)據(jù)位、停止位和校驗(yàn)位,再打開端口連接、發(fā)送數(shù)據(jù)、接收數(shù)據(jù),最后關(guān)閉端口連接步驟。
?
首先Unity是支持串口通信的,只不過Unity采用的是Mono .NET 2.0。之前版本對(duì)COM支持不是很好,所以導(dǎo)致Unity在串口通信方面有些問題。
小編用的版本是2018.4.0
首先想使用Unity開發(fā)串口通信,必須要做的 一點(diǎn)就是 要使用Mono.NET 2.0/4.0/其他
如下圖:
或?.net framework
不修改的話是不能進(jìn)行串口開發(fā)的 。
例子一:
修改完之后下面是代碼環(huán)節(jié),簡單通俗易懂
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System;
using System.Text;
/// <summary>
/// 串口通信
/// </summary>
public class SerialPortControl
{
public static string portName;//串口號(hào)
public static int baudRate;//波特率
public static Parity parity;//校驗(yàn)位
public static int dataBit;//數(shù)據(jù)位
public static StopBits stopBit;//停止位
static SerialPort sp = new SerialPort();
/// <summary>
/// 串口號(hào)
/// </summary>
/// <param name="portname"></param>
/// <returns></returns>
public static string PortName(string portname)
{
portName = portname;
return portName;
}
/// <summary>
/// 波特率
/// </summary>
/// <param name="baud"></param>
/// <returns></returns>
public static int BauRate(int baud)
{
baudRate = baud;
return baudRate;
}
/// <summary>
/// 校驗(yàn)位
/// </summary>
/// <param name="paritys"></param>
/// <returns></returns>
public static Parity Paritys(Parity paritys)
{
parity = paritys;
return parity;
}
/// <summary>
/// 數(shù)據(jù)位
/// </summary>
/// <param name="dataBits"></param>
/// <returns></returns>
public static int DataBits(int dataBits)
{
dataBit = dataBits;
return dataBit;
}
/// <summary>
/// 停止位
/// </summary>
/// <param name="stopBits"></param>
/// <returns></returns>
public static StopBits StopBitss(StopBits stopBits)
{
stopBit = stopBits;
return stopBit;
}
/// <summary>
/// 字節(jié)流轉(zhuǎn)字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesTohexString(byte[] bytes)
{
if (bytes == null || bytes.Length < 1)
{
return string.Empty;
}
var count = bytes.Length;
var cache = new StringBuilder();
cache.Append("0x");
for (int ii = 0; ii < count; ++ii)
{
var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
}
return cache.ToString();
}
/// <summary>
/// 字符串轉(zhuǎn)字節(jié)流
/// </summary>
/// <param name="hexStr"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexStr)
{
if (string.IsNullOrEmpty(hexStr))
{
return new byte[0];
}
if (hexStr.StartsWith("0x"))
{
hexStr = hexStr.Remove(0, 2);
}
var count = hexStr.Length;
var byteCount = count / 2;
var result = new byte[byteCount];
for (int ii = 0; ii < byteCount; ++ii)
{
var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
result[ii] = tempBytes;
}
return result;
}
//字符串轉(zhuǎn)字節(jié)流 推薦======
public static byte[] Convert16(string strText)
{
strText = strText.Replace(" ", "");
byte[] bText = new byte[strText.Length / 2];
for (int i = 0; i < strText.Length / 2; i++)
{
bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
}
return bText;
}
/// <summary>
/// 打開端口,連接串口
/// </summary>
public static void OpenPort()
{
sp = new SerialPort(portName, baudRate, parity, dataBit, stopBit);
sp.ReadTimeout = 1000;
try
{
sp.Open();
Debug.Log("打開端口成功");
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
/// <summary>
/// 關(guān)閉端口
/// </summary>
public static void ClosePort()
{
try
{
sp.Close();
sp.Dispose();
Debug.Log("關(guān)閉端口");
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
byte[] buffer = new byte[5];
int bytes = 0;
/// <summary>
/// 交互:接收端口數(shù)據(jù)
/// </summary>
public void DataReceiveFun()
{
while (true)
{
if (sp != null && sp.IsOpen)
{
try
{
bytes = sp.Read(buffer, 0, buffer.Length);
sp.DiscardOutBuffer();
if (bytes == 0)
{
continue;
}
else
{
for (int i = 0; i < buffer.Length; i++)
{
Debug.Log(buffer[i].ToString("x8"));
}
}
}
catch (Exception e)
{
Debug.Log(e);
}
}
Thread.Sleep(500);
}
}
/// <summary>
/// 交互:發(fā)送數(shù)據(jù)
/// </summary>
/// <param name="dataStr"></param>
public static void SendData(byte[] dataStr)
{
sp.Write(dataStr, 0, dataStr.Length);
Debug.LogWarning("發(fā)送成功");
}
}
?一些其他便捷功能:
//十進(jìn)制轉(zhuǎn)二進(jìn)制
Console.WriteLine(Convert.ToString(69, 2));
//十進(jìn)制轉(zhuǎn)八進(jìn)制
Console.WriteLine(Convert.ToString(69, 8));
//十進(jìn)制轉(zhuǎn)十六進(jìn)制
Console.WriteLine(Convert.ToString(69, 16));
//二進(jìn)制轉(zhuǎn)十進(jìn)制
Console.WriteLine(Convert.ToInt32("100111101", 2));
//八進(jìn)制轉(zhuǎn)十進(jìn)制
Console.WriteLine(Convert.ToInt32("76", 8));
//16進(jìn)制轉(zhuǎn)換10進(jìn)制
Console.WriteLine(Convert.ToInt32("FF", 16));
/// <summary>
/// 字符串轉(zhuǎn)字節(jié)流
/// </summary>
/// <param name="hexStr"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexStr)
{
if (string.IsNullOrEmpty(hexStr))
{
return new byte[0];
}
if (hexStr.StartsWith("0x"))
{
hexStr = hexStr.Remove(0, 2);
}
var count = hexStr.Length;
var byteCount = count / 2;
var result = new byte[byteCount];
for (int ii = 0; ii < byteCount; ++ii)
{
var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
result[ii] = tempBytes;
}
return result;
}
//第二種 常用轉(zhuǎn)換方式 推薦
public static byte[] Convert16(string strText)
{
strText = strText.Replace(" ", "");
byte[] bText = new byte[strText.Length / 2];
for (int i = 0; i < strText.Length / 2; i++)
{
bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
}
return bText;
}
例子二:Mono版本
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
public class PortControl : MonoBehaviour
{
#region 定義串口屬性
public GUIText gui;
//public GUIText Test;
//定義基本信息
public string portName = "COM3";//串口名
public int baudRate = 9600;//波特率
public Parity parity = Parity.None;//效驗(yàn)位
public int dataBits = 8;//數(shù)據(jù)位
public StopBits stopBits = StopBits.One;//停止位
SerialPort sp = null;
Thread dataReceiveThread;
//發(fā)送的消息
string message = "";
public List<byte> listReceive = new List<byte>();
char[] strchar = new char[100];//接收的字符信息轉(zhuǎn)換為字符數(shù)組信息
string str;
#endregion
void Start()
{
OpenPort();
dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));
dataReceiveThread.Start();
}
void Update()
{
}
#region 創(chuàng)建串口,并打開串口
public void OpenPort()
{
//創(chuàng)建串口
sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
sp.ReadTimeout = 400;
try
{
sp.Open();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
#endregion
#region 程序退出時(shí)關(guān)閉串口
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 接收數(shù)據(jù)
void DataReceiveFunction()
{
#region 按單個(gè)字節(jié)發(fā)送處理信息,不能接收中文
//while (sp != null && sp.IsOpen)
//{
// Thread.Sleep(1);
// try
// {
// byte addr = Convert.ToByte(sp.ReadByte());
// sp.DiscardInBuffer();
// listReceive.Add(addr);
// PrintData();
// }
// catch
// {
// //listReceive.Clear();
// }
//}
#endregion
#region 按字節(jié)數(shù)組發(fā)送處理信息,信息缺失
byte[] buffer = new byte[1024];
int bytes = 0;
while (true)
{
if (sp != null && sp.IsOpen)
{
try
{
bytes = sp.Read(buffer, 0, buffer.Length);//接收字節(jié)
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 發(fā)送數(shù)據(jù)
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 發(fā)送";//測(cè)試字符串
if (GUILayout.Button("Send Test"))
{
WriteData(test);
}
}
#endregion
}
一些問題:?
1、沒有將Unity3D的API平臺(tái)切換成.NET2.0,這時(shí)Unity編寫SerialPort類會(huì)報(bào)錯(cuò)。
解決方法:將Unity3D的API平臺(tái)切換成.NET2.0,切換方法: “Edit–>project Setting–>Player–>Other Setting –>Api Compatibility level”。在這里將“.NET2.0 Subset”切換為“.NET2.0”
2、Unity的目標(biāo)平臺(tái)沒有切換為Windows平臺(tái),會(huì)提示該命名空間不支持SystemIO,提示你切換工具。
解決方法:把目標(biāo)平臺(tái)切換為Windows平臺(tái),否則是其他平臺(tái)會(huì)報(bào)錯(cuò)誤。
3、串口發(fā)送的信息不能正常解析
解決方法:把串口發(fā)送的消息使用字節(jié)流進(jìn)行轉(zhuǎn)換。(字符流轉(zhuǎn)換)
4、串口接收信息的缺失問題
(1)接收字符串(string):port.ReadLine()
數(shù)據(jù)接收可能錯(cuò)誤,數(shù)據(jù)丟失,數(shù)據(jù)接收不到
(2)接收字節(jié)數(shù)組(byte[]):port.Read()
接收數(shù)據(jù)斷層,會(huì)分兩次接收完整數(shù)據(jù)
(3)接收單個(gè)字節(jié)(byte):port.ReadByte()
將接收到的數(shù)據(jù)進(jìn)行組合
5.第一次發(fā)送數(shù)據(jù)的時(shí)候,往往會(huì)丟失數(shù)據(jù)尾(和知名大佬總結(jié)得出,最后會(huì)在文章底部@大佬)
比如發(fā)送:64 64 80 89 第一次接收的可能是64 80 89 0
解決方法:
?
//40405059 暫停
if (paramByte[0] == (byte)64 && paramByte[1] == (byte)64 && paramByte[2] == (byte)80 && paramByte[3] == (byte)89)
{
Debug.Log("AA");
}
else if (paramByte[0] == (byte)64 && paramByte[1] == (byte)80 && paramByte[2] == (byte)89)
{
Debug.Log("AA");
}
通過以上代碼,可以完美避開這個(gè)坑,第二次就會(huì)正常。
每臺(tái)電腦的串口都是不一樣的,比如你從A電腦,插上去設(shè)備管理器顯示的是COM 2,你程序中定義的是COM2,這樣可以實(shí)現(xiàn)通訊。
如果你換了臺(tái)電腦B,但是現(xiàn)在B電腦串口是COM10,你代碼中還是COM2,就沒辦法完成通訊了。
解決方案一:通過讀取TXT文檔,來設(shè)置COM口。
public static string portName = "";//串口名稱
void Start()
{
string path = Application.streamingAssetsPath + "/config.txt";
string[] strs = File.ReadAllLines(path);
if (strs.Length > 0) portName = strs[0];
Debug.Log(strs.Length);
}
解決方案二:通過讀取電腦注冊(cè)表,來動(dòng)態(tài)設(shè)置COM口。
public string getPortName = "";//串口名稱
void Start()
{
List<string> protReg = GetPortFromReg();
if (protReg.Count > 0)
{
getPortName = protReg[2];//0是默認(rèn)第一接口.
}
else
{
Debug.Log("獲取不到端口");
}
Debug.Log("當(dāng)前COM口配置為:"+getPortName);
}
這樣就可以動(dòng)態(tài)獲取COM口,但是此方法多少還是有局限性,想要準(zhǔn)確無誤,還是要用解決一方法(通過TXT文本配置)
三步教會(huì)你 Unity串口通訊_unity串口通信_(tái)_橙子先生的博客-CSDN博客文章來源:http://www.zghlxwxcb.cn/news/detail-411905.html
Unity串口通信、接受和發(fā)送數(shù)據(jù)、C#_unity 串口接收_與火星的孩子對(duì)話的博客-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-411905.html
到了這里,關(guān)于Unity串口通信、接受和發(fā)送數(shù)據(jù)、C#的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!