C#串口通信学习笔记
因?yàn)閰⒓右粋€(gè)小項(xiàng)目,需要對(duì)繼電器進(jìn)行串口控制,所以這兩天學(xué)習(xí)了基本的串口編程。同事那邊有JAVA的串口通信包,不過是從網(wǎng)上下載的,比較零亂,難以準(zhǔn)確掌握串口通信的流程和內(nèi)含。因此,個(gè)人通過學(xué)習(xí)網(wǎng)上大牛的方法,利用C#實(shí)現(xiàn)了基本的串口通信編程。下面對(duì)學(xué)習(xí)成果進(jìn)行總結(jié)歸納,希望對(duì)大家有所幫助。
一、串口通信簡(jiǎn)介
串行接口(串口)是一種可以將接受來(lái)自CPU的并行數(shù)據(jù)字符轉(zhuǎn)換為連續(xù)的串行數(shù)據(jù)流發(fā)送出去,同時(shí)可將接受的串行數(shù)據(jù)流轉(zhuǎn)換為并行的數(shù)據(jù)字符供給CPU的器件。一般完成這種功能的電路,我們稱為串行接口電路。
串口通信(Serial Communications)的概念非常簡(jiǎn)單,串口按位(bit)發(fā)送和接收字節(jié)。盡管比按字節(jié)(byte)的并行通信慢,但是串口可以在使用一根線發(fā)送數(shù)據(jù)的同時(shí)用另一根線接收數(shù)據(jù)。串口通信最重要的參數(shù)是波特率、數(shù)據(jù)位、停止位和奇偶校驗(yàn)。對(duì)于兩個(gè)進(jìn)行通信的端口,這些參數(shù)必須匹配。
? 1.?波特率:這是一個(gè)衡量符號(hào)傳輸速率的參數(shù)。指的是信號(hào)被調(diào)制以后在單位時(shí)間內(nèi)的變化,即單位時(shí)間內(nèi)載波參數(shù)變化的次數(shù),如每秒鐘傳送960個(gè)字符,而每個(gè)字符格式包含10位(1個(gè)起始位,1個(gè)停止位,8個(gè)數(shù)據(jù)位),這時(shí)的波特率為960Bd,比特率為10位*960個(gè)/秒=9600bps。
? 2.?數(shù)據(jù)位:這是衡量通信中實(shí)際數(shù)據(jù)位的參數(shù)。當(dāng)計(jì)算機(jī)發(fā)送一個(gè)信息包,實(shí)際的數(shù)據(jù)往往不會(huì)是8位的,標(biāo)準(zhǔn)的值是6、7和8位。標(biāo)準(zhǔn)的ASCII碼是0~127(7位),擴(kuò)展的ASCII碼是0~255(8位)。
? 3.?停止位:用于表示單個(gè)包的最后幾位。典型的值為1,1.5和2位。由于數(shù)據(jù)是在傳輸線上定時(shí)的,并且每一個(gè)設(shè)備有其自己的時(shí)鐘,很可能在通信中兩臺(tái)設(shè)備間出現(xiàn)了小小的不同步。因此停止位不僅僅是表示傳輸?shù)慕Y(jié)束,并且提供計(jì)算機(jī)校正時(shí)鐘同步的機(jī)會(huì)。
? 4.?校驗(yàn)位:在串口通信中一種簡(jiǎn)單的檢錯(cuò)方式。有四種檢錯(cuò)方式:偶、奇、高和低。當(dāng)然沒有校驗(yàn)位也是可以的。
二、C#串口編程類
從.NET Framework 2.0開始,C#提供了SerialPort類用于實(shí)現(xiàn)串口控制。命名空間:System.IO.Ports。其中詳細(xì)成員介紹參看MSDN文檔。下面介紹其常用的字段、方法和事件。
? 1. 常用字段:
| 名稱 | 說(shuō)明 |
| PortName | 獲取或設(shè)置通信端口 |
| BaudRate | 獲取或設(shè)置串行波特率 |
| DataBits | 獲取或設(shè)置每個(gè)字節(jié)的標(biāo)準(zhǔn)數(shù)據(jù)位長(zhǎng)度 |
| Parity | 獲取或設(shè)置奇偶校驗(yàn)檢查協(xié)議 |
| StopBits | 獲取或設(shè)置每個(gè)字節(jié)的標(biāo)準(zhǔn)停止位數(shù) |
?
?
?
?
?
?
2. 常用方法:
| 名稱 | 說(shuō)明 |
| 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. 常用事件:
| 名稱 | 說(shuō)明 |
| DataReceived | 表示將處理?SerialPort?對(duì)象的數(shù)據(jù)接收事件的方法 |
?
?
?
三、基本用法
下面結(jié)合已有的一款繼電器給出串口通信的基本用法,以供參考。
1 using System; 2 using System.Windows.Forms; 3 using System.IO.Ports; 4 using System.Text; 5 6 namespace Traveller_SerialPortControl 7 { 8 public partial class Form1 : Form 9 { 10 //定義端口類 11 private SerialPort ComDevice = new SerialPort(); 12 public Form1() 13 { 14 InitializeComponent(); 15 InitralConfig(); 16 } 17 /// <summary> 18 /// 配置初始化 19 /// </summary> 20 private void InitralConfig() 21 { 22 //查詢主機(jī)上存在的串口 23 comboBox_Port.Items.AddRange(SerialPort.GetPortNames()); 24 25 if (comboBox_Port.Items.Count > 0) 26 { 27 comboBox_Port.SelectedIndex = 0; 28 } 29 else 30 { 31 comboBox_Port.Text = "未檢測(cè)到串口"; 32 } 33 comboBox_BaudRate.SelectedIndex = 5; 34 comboBox_DataBits.SelectedIndex = 0; 35 comboBox_StopBits.SelectedIndex = 0; 36 comboBox_CheckBits.SelectedIndex = 0; 37 pictureBox_Status.BackgroundImage = Properties.Resources.red; 38 39 //向ComDevice.DataReceived(是一個(gè)事件)注冊(cè)一個(gè)方法Com_DataReceived,當(dāng)端口類接收到信息時(shí)時(shí)會(huì)自動(dòng)調(diào)用Com_DataReceived方法 40 ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); 41 } 42 43 /// <summary> 44 /// 一旦ComDevice.DataReceived事件發(fā)生,就將從串口接收到的數(shù)據(jù)顯示到接收端對(duì)話框 45 /// </summary> 46 /// <param name="sender"></param> 47 /// <param name="e"></param> 48 private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) 49 { 50 //開辟接收緩沖區(qū) 51 byte[] ReDatas = new byte[ComDevice.BytesToRead]; 52 //從串口讀取數(shù)據(jù) 53 ComDevice.Read(ReDatas, 0, ReDatas.Length); 54 //實(shí)現(xiàn)數(shù)據(jù)的解碼與顯示 55 AddData(ReDatas); 56 } 57 58 /// <summary> 59 /// 解碼過程 60 /// </summary> 61 /// <param name="data">串口通信的數(shù)據(jù)編碼方式因串口而異,需要查詢串口相關(guān)信息以獲取</param> 62 public void AddData(byte[] data) 63 { 64 if (radioButton_Hex.Checked) 65 { 66 StringBuilder sb = new StringBuilder(); 67 for (int i = 0; i < data.Length; i++) 68 { 69 sb.AppendFormat("{0:x2}" + " ", data[i]); 70 } 71 AddContent(sb.ToString().ToUpper()); 72 } 73 else if (radioButton_ASCII.Checked) 74 { 75 AddContent(new ASCIIEncoding().GetString(data)); 76 } 77 else if (radioButton_UTF8.Checked) 78 { 79 AddContent(new UTF8Encoding().GetString(data)); 80 } 81 else if (radioButton_Unicode.Checked) 82 { 83 AddContent(new UnicodeEncoding().GetString(data)); 84 } 85 else 86 { 87 StringBuilder sb = new StringBuilder(); 88 for (int i = 0; i < data.Length; i++) 89 { 90 sb.AppendFormat("{0:x2}" + " ", data[i]); 91 } 92 AddContent(sb.ToString().ToUpper()); 93 } 94 } 95 96 /// <summary> 97 /// 接收端對(duì)話框顯示消息 98 /// </summary> 99 /// <param name="content"></param> 100 private void AddContent(string content) 101 { 102 BeginInvoke(new MethodInvoker(delegate 103 { 104 textBox_Receive.AppendText(content); 105 })); 106 } 107 108 /// <summary> 109 /// 串口開關(guān) 110 /// </summary> 111 /// <param name="sender"></param> 112 /// <param name="e"></param> 113 private void button_Switch_Click(object sender, EventArgs e) 114 { 115 if (comboBox_Port.Items.Count <= 0) 116 { 117 MessageBox.Show("未發(fā)現(xiàn)可用串口,請(qǐng)檢查硬件設(shè)備"); 118 return; 119 } 120 121 if (ComDevice.IsOpen == false) 122 { 123 //設(shè)置串口相關(guān)屬性 124 ComDevice.PortName = comboBox_Port.SelectedItem.ToString(); 125 ComDevice.BaudRate = Convert.ToInt32(comboBox_BaudRate.SelectedItem.ToString()); 126 ComDevice.Parity = (Parity)Convert.ToInt32(comboBox_CheckBits.SelectedIndex.ToString()); 127 ComDevice.DataBits = Convert.ToInt32(comboBox_DataBits.SelectedItem.ToString()); 128 ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox_StopBits.SelectedItem.ToString()); 129 try 130 { 131 //開啟串口 132 ComDevice.Open(); 133 button_Send.Enabled = true; 134 } 135 catch (Exception ex) 136 { 137 MessageBox.Show(ex.Message, "未能成功開啟串口", MessageBoxButtons.OK, MessageBoxIcon.Error); 138 return; 139 } 140 button_Switch.Text = "關(guān)閉"; 141 pictureBox_Status.BackgroundImage = Properties.Resources.green; 142 } 143 else 144 { 145 try 146 { 147 //關(guān)閉串口 148 ComDevice.Close(); 149 button_Send.Enabled = false; 150 } 151 catch (Exception ex) 152 { 153 MessageBox.Show(ex.Message, "串口關(guān)閉錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 154 } 155 button_Switch.Text = "開啟"; 156 pictureBox_Status.BackgroundImage = Properties.Resources.red; 157 } 158 159 comboBox_Port.Enabled = !ComDevice.IsOpen; 160 comboBox_BaudRate.Enabled = !ComDevice.IsOpen; 161 comboBox_DataBits.Enabled = !ComDevice.IsOpen; 162 comboBox_StopBits.Enabled = !ComDevice.IsOpen; 163 comboBox_CheckBits.Enabled = !ComDevice.IsOpen; 164 } 165 166 167 /// <summary> 168 /// 將消息編碼并發(fā)送 169 /// </summary> 170 /// <param name="sender"></param> 171 /// <param name="e"></param> 172 private void button_Send_Click(object sender, EventArgs e) 173 { 174 if (textBox_Receive.Text.Length > 0) 175 { 176 textBox_Receive.AppendText("\n"); 177 } 178 179 byte[] sendData = null; 180 181 if (radioButton_Hex.Checked) 182 { 183 sendData = strToHexByte(textBox_Send.Text.Trim()); 184 } 185 else if (radioButton_ASCII.Checked) 186 { 187 sendData = Encoding.ASCII.GetBytes(textBox_Send.Text.Trim()); 188 } 189 else if (radioButton_UTF8.Checked) 190 { 191 sendData = Encoding.UTF8.GetBytes(textBox_Send.Text.Trim()); 192 } 193 else if (radioButton_Unicode.Checked) 194 { 195 sendData = Encoding.Unicode.GetBytes(textBox_Send.Text.Trim()); 196 } 197 else 198 { 199 sendData = strToHexByte(textBox_Send.Text.Trim()); 200 } 201 202 SendData(sendData); 203 } 204 205 /// <summary> 206 /// 此函數(shù)將編碼后的消息傳遞給串口 207 /// </summary> 208 /// <param name="data"></param> 209 /// <returns></returns> 210 public bool SendData(byte[] data) 211 { 212 if (ComDevice.IsOpen) 213 { 214 try 215 { 216 //將消息傳遞給串口 217 ComDevice.Write(data, 0, data.Length); 218 return true; 219 } 220 catch (Exception ex) 221 { 222 MessageBox.Show(ex.Message, "發(fā)送失敗", MessageBoxButtons.OK, MessageBoxIcon.Error); 223 } 224 } 225 else 226 { 227 MessageBox.Show("串口未開啟", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error); 228 } 229 return false; 230 } 231 232 /// <summary> 233 /// 16進(jìn)制編碼 234 /// </summary> 235 /// <param name="hexString"></param> 236 /// <returns></returns> 237 private byte[] strToHexByte(string hexString) 238 { 239 hexString = hexString.Replace(" ", ""); 240 if ((hexString.Length % 2) != 0) hexString += " "; 241 byte[] returnBytes = new byte[hexString.Length / 2]; 242 for (int i = 0; i < returnBytes.Length; i++) 243 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16); 244 return returnBytes; 245 } 246 247 //以下兩個(gè)指令是結(jié)合一款繼電器而設(shè)計(jì)的 248 private void button_On_Click(object sender, EventArgs e) 249 { 250 textBox_Send.Text = "005A540001010000B0"; 251 } 252 253 private void button_Off_Click(object sender, EventArgs e) 254 { 255 textBox_Send.Text = "005A540002010000B1"; 256 } 257 } 258 }軟件實(shí)現(xiàn)基本界面
?
希望以上內(nèi)容對(duì)入門串口編程有所幫助,在此感謝百度百科的參考和kasama1953文章的幫助。
?
轉(zhuǎn)載于:https://www.cnblogs.com/Traveller-Lee/p/6940221.html
總結(jié)
以上是生活随笔為你收集整理的C#串口通信学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WebStorm V2017.1版用于A
- 下一篇: python爬虫beautifulsou