網站首頁 編程語言 正文
串口通信(Serial Communications)是指外設和計算機間通過數據信號線、地線等按位(bit)進行傳輸數據的一種通信方式,屬于串行通信方式,能夠實現遠距離通信,長度可達1200米。盡管比按字節(byte)的并行通信慢,但是串口可以在使用一根線發送數據的同時用另一根線接收數據。串口通信最重要的參數是波特率、數據位、停止位和奇偶校驗。對于兩個進行通信的端口,這些參數必須匹配。
串口通信的接口標準有很多,有 RS-232C、RS-232、RS-422A、RS-485 等。常用的就是 RS-232 和 RS-485。串口通信使用的大多都是 DB9 接口,如下圖。
1 載波檢測(DCD) 2 接受數據(RXD) 3 發出數據(TXD) 4 數據終端準備好(DTR) 5 信號地線(SG) 6 數據準備好(DSR) 7 請求發送(RTS) 8 清除發送(CTS) 9 振鈴指示(RI)
這里我們以 RS-232 接口進行演示。
1、數據包格式定為(10bytes):
幀頭(0xAA,0x55),命令字(1byte),地址位(2bytes),數據位(2bytes),校驗位(1byte,和校驗),幀尾(0xFE,0xFE)
地址位和數據位都是高位在前。
數據封裝方法:
//數據打包 private byte[] DataPackage(byte cmd, int addr, int data) ? ? ? ? { ? ? ? ? ? ? byte[] package = new byte[10]; ? ? ? ? ? ? package[0] = 0xAA;//幀頭 ? ? ? ? ? ? package[1] = 0x55; ? ? ? ? ? ? package[2] = cmd;//命令字 ? ? ? ? ? ? ? ? byte[] dataaddr = IntToByteArray(addr); ? ? ? ? ? ? package[3] = dataaddr[0];//地址高字節 ? ? ? ? ? ? package[4] = dataaddr[1];//地址低字節 ? ? ? ? ? ? byte[] value = IntToByteArray(data); ? ? ? ? ? ? package[5] = value[0];//數據高字節 ? ? ? ? ? ? package[6] = value[1];//數據低字節 ? ? ? ? ? ? package[7] = CheckSum(package);//校驗位 ? ? ? ? ? ? package[8] = 0xFE;//幀尾 ? ? ? ? ? ? package[9] = 0xFE; ? ? ? ? ? ? return package; ? ? ? ? } ? ? ? ? ? //將int轉換成2位數組 ? ? ? ? private static byte[] IntToByteArray(int value) ? ? ? ? { ? ? ? ? ? ? int hvalue = (value >> 8) & 0xFF; ? ? ? ? ? ? int lValue = value & 0xFF; ? ? ? ? ? ? byte[] arr = new byte[] { (byte)hvalue, (byte)lValue }; ? ? ? ? ? ? return arr; ? ? ? ? } ? ? ? ? ? //得到和校驗碼 ? ? ? ? private byte CheckSum(byte[] package) ? ? ? ? { ? ? ? ? ? ? byte checksum = 0; ? ? ? ? ? ? for (int i = 0; i < package.Length; i++) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? checksum += package[i]; ? ? ? ? ? ? } ? ? ? ? ? ? return checksum; ? ? ? ? }
2、串口調用封裝類CommHelper.cs
internal class CommHelper ? ? { ? ? ? ? //委托 ? ? ? ? public delegate void EventHandle(byte[] readBuffer); ? ? ? ? public event EventHandle DataReceived; ? ? ? ? ? public SerialPort serialPort; ? ? ? ? private Thread thread; ? ? ? ? volatile bool _keepReading; ? ? ? ? ? public CommHelper() ? ? ? ? { ? ? ? ? ? ? serialPort = new SerialPort(); ? ? ? ? ? ?? ? ? ? ? ? ? thread = null; ? ? ? ? ? ? _keepReading = false; ? ? ? ? ? ? ? serialPort.ReadTimeout = -1; ? ? ? ? ? ? serialPort.WriteTimeout = 1000; ? ? ? ? } ? ? ? ? ? //獲取串口打開狀態 ? ? ? ? public bool IsOpen ? ? ? ? { ? ? ? ? ? ? get ? ? ? ? ? ? { ? ? ? ? ? ? ? ? return serialPort.IsOpen; ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //開始讀取 ? ? ? ? private void StartReading() ? ? ? ? { ? ? ? ? ? ? if (!_keepReading) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? _keepReading = true; ? ? ? ? ? ? ? ? thread = new Thread(new ThreadStart(ReadPort)); ? ? ? ? ? ? ? ? thread.Start(); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //停止讀取 ? ? ? ? private void StopReading() ? ? ? ? { ? ? ? ? ? ? if (_keepReading) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? _keepReading = false; ? ? ? ? ? ? ? ? thread.Join(); ? ? ? ? ? ? ? ? thread = null; ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //讀數據 ? ? ? ? private void ReadPort() ? ? ? ? { ? ? ? ? ? ? while (_keepReading) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? if (serialPort.IsOpen) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? int count = serialPort.BytesToRead; ? ? ? ? ? ? ? ? ? ? if (count > 0) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? byte[] readBuffer = new byte[count]; ? ? ? ? ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? Application.DoEvents(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? serialPort.Read(readBuffer, 0, count); ? ? ? ? ? ? ? ? ? ? ? ? ? ? DataReceived?.Invoke(readBuffer); ? ? ? ? ? ? ? ? ? ? ? ? ? ? Thread.Sleep(100); ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? catch (TimeoutException) ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //寫數據 ? ? ? ? public void WritePort(byte[] send, int offSet, int count) ? ? ? ? { ? ? ? ? ? ? if (IsOpen) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? serialPort.Write(send, offSet, count); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //打開 ? ? ? ? public void Open() ? ? ? ? { ? ? ? ? ? ? Close(); ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? serialPort.Open(); ? ? ? ? ? ? ? ? serialPort.RtsEnable = true; ? ? ? ? ? ? ? ? if (serialPort.IsOpen) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? StartReading(); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? else ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? MessageBox.Show("串口打開失??!"); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? catch ? ? ? ? ? ? { ? ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //關閉 ? ? ? ? public void Close() ? ? ? ? { ? ? ? ? ? ? StopReading(); ? ? ? ? ? ? serialPort.Close(); ? ? ? ? ? ? ? ? ? ? } ? ? }
3、調用(模擬測試讀寫硬件版本號)
//地址存儲信息定義 private static int HARD_VERSION = 0;?? ??? ? ? ?//硬件版本號 ? ? ? ? //命令定義 private static byte RD_HV = 0;?? ??? ??? ? ? ?//讀硬件版本 private static byte WR_HV = 1;?? ??? ??? ? ? ?//寫硬件版本 ? private CommHelper comm = new CommHelper(); private bool GetCorrect = false; //用來標識是否已經接收到返回值 ? private Listbuffer = new List (1024);//默認分配1M內存,限制不能超過 private byte[] binary_data = new byte[10];//指定格式的某個完整數據 ? //串口初始化 private void InitComm() ? ? ? ? { ? ? ? ? ? ? comm.serialPort.PortName = "COM1"; ? ? ? ? ? ? comm.serialPort.BaudRate = 19200; ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? comm.Open(); ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception ex) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message); ? ? ? ? ? ? } ? ? ? ? ? ? if (comm.IsOpen) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? comm.DataReceived += new CommHelper.EventHandle(comm_DataReceived); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //數據接收后處理 ? ? ? ? private void comm_DataReceived(byte[] readBuffer) ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? buffer.AddRange(readBuffer);//將數據放到緩存中 ? ? ? ? ? ? ? ? //完整性判斷 ? ? ? ? ? ? ? ? while (buffer.Count >= 10) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? //查找數據頭 ? ? ? ? ? ? ? ? ? ? if (buffer[0] == 0xAA && buffer[1] == 0x55) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? //和校驗 ? ? ? ? ? ? ? ? ? ? ? ? byte checksum = 0; ? ? ? ? ? ? ? ? ? ? ? ? for (int i = 0; i < 7; i++) ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? checksum += buffer[i]; ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? if (checksum != buffer[7]) ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? buffer.RemoveRange(0, 10);//如果校驗失敗,從緩存中刪除這一包數據 ? ? ? ? ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? buffer.CopyTo(0, binary_data, 0, 10);//復制一條完整的數據到具體的數據緩存 ? ? ? ? ? ? ? ? ? ? ? ? ? //讀取硬件版本號 ? ? ? ? ? ? ? ? ? ? ? ? if (binary_data[2] == RD_HV && ByteArrayToInt(binary_data[3], binary_data[4]) == HARD_VERSION)//命令字為讀RD_HV,地址HARD_VERSION ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? GetCorrect = true; ? ? ? ? ? ? ? ? ? ? ? ? ? ? string data = ByteArrayToString(binary_data[5], binary_data[6]); ? ? ? ? ? ? ? ? ? ? ? ? ? ? //這里可以處理數據更新界面展示 ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? ? buffer.RemoveRange(0, 10); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? else ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? GetCorrect = false; ? ? ? ? ? ? ? ? ? ? ? ? buffer.RemoveAt(0);//如果數據開始不是頭,則刪除數據 ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? catch ? ? ? ? ? ? { ? ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //將2位數組轉換成字符串 ? ? ? ? private static string ByteArrayToString(byte arr1, byte arr2) ? ? ? ? { ? ? ? ? ? ? int value = ByteArrayToInt(arr1, arr2); ? ? ? ? ? ? string str = Convert.ToString(value, 10); ? ? ? ? ? ? return str; ? ? ? ? } ? ? ? ? ? //將2位數組轉換成10進制數 ? ? ? ? private static int ByteArrayToInt(byte arr1, byte arr2) ? ? ? ? { ? ? ? ? ? ? byte[] arr = new byte[] { arr1, arr2 }; ? ? ? ? ? ? int value = (int)((arr[0] & 0xFF) << 8) ? ? ? ? ? ? ? ? ? ? ? | (arr[1] & 0xFF); ? ? ? ? ? ? return value; ? ? ? ? } ? ? ? ? ? //讀取硬件版本號 ? ? ? ? private void ReadHV() ? ? ? ? { ? ? ? ? ? ? GetCorrect = false; ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? comm.WritePort(DataPackage(RD_HV, HARD_VERSION, 0), 0, 10);//發送RD_E2P命令,地址HARD_VERSION ? ? ? ? ? ? ? ? Delay(100); ? ? ? ? ? ? ? ? if (GetCorrect == true) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? MessageBox.Show("硬件版本號讀取成功!"); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? else ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? MessageBox.Show("硬件版本號讀取失敗!"); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? catch (Exception ex) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //寫入硬件版本號 ? ? ? ? private void WriteHV() ? ? ? ? { ? ? ? ? ? ? if (tbVersion.Text.Length == 4 && isLegal(tbVersion.Text))//限定只能寫入4個字符且輸入合法 ? ? ? ? ? ? { ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? int buf = Convert.ToInt32(tbVersion.Text); ? ? ? ? ? ? ? ? ? ? GetCorrect = false; ? ? ? ? ? ? ? ? ? ? comm.WritePort(DataPackage(WR_HV, HARD_VERSION, buf), 0, 10);//發送WR_HV命令,地址HARD_VERSION ? ? ? ? ? ? ? ? ? ? Delay(100); ? ? ? ? ? ? ? ? ? ? if (GetCorrect == true) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? MessageBox.Show("硬件版本號寫入成功!"); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? else ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? MessageBox.Show("硬件版本號寫入失敗!"); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? catch (Exception ex) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? else ? ? ? ? ? ? { ? ? ? ? ? ? ? ? MessageBox.Show("硬件版本號數據格式錯誤!請重新寫入!"); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? //判斷輸入是否合法,必須是數字 ? ? ? ? private const string PATTERN = @"^[0-9]*$"; ? ? ? ? private bool isLegal(string hex) ? ? ? ? { ? ? ? ? ? ? return System.Text.RegularExpressions.Regex.IsMatch(hex, PATTERN); ? ? ? ? } ? ? ? ? ? //延時函數 ? ? ? ? [DllImport("kernel32.dll")] ? ? ? ? static extern uint GetTickCount(); ? ? ? ? static void Delay(uint ms) ? ? ? ? { ? ? ? ? ? ? uint start = GetTickCount(); ? ? ? ? ? ? while (GetTickCount() - start < ms) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Application.DoEvents(); ? ? ? ? ? ? } ? ? ? ? }
原文鏈接:https://blog.csdn.net/dnazhd/article/details/88327160
相關推薦
- 2023-03-28 Python中用append()連接后多出一列Unnamed的解決_python
- 2022-06-07 redis復制有可能碰到的問題匯總_Redis
- 2022-09-22 lex yacc與C++編寫代碼解析字符串代碼示例
- 2022-04-04 react解包并配置Less解包config文件目錄
- 2022-07-30 python?replace?空格數據處理的實現_python
- 2022-09-22 git只提交部分修改的文件(提交指定文件)
- 2022-11-16 Python?讀取?.gz?文件全過程_python
- 2022-06-02 Tomcat用戶管理的優化配置詳解_Tomcat
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支