串口應用 HR receive 初始 ext edev 實現 ear 方式

C#串口介紹以及簡單串口通信程序設計實現

周末,沒事幹,寫個簡單的串口通信工具,也算是本周末曾來過,廢話不多,直接到主題

串口介紹

  串行接口簡稱串口,也稱串行通信接口或串行通訊接口(通常指COM接口),是采用串行通信方式的擴展接口。(至於再詳細,自己百度)

串口應用:

  工業領域使用較多,比如:數據采集,設備控制等等,好多都是用串口通信來實現!你要是細心的話,你會發現,目前家用國網智能電能表就具備RS485通信總線(串行總線的一種)與RS232可以相互轉化(當然一般,非專業的誰也不會閑的蛋疼,趴電表上瞎看,最多也就看看走了多少度電)

RS232 DB9介紹:

1.示意圖

技術分享圖片

2.針腳介紹:

  1. 載波檢測(DCD)
  2. 接受數據(RXD)
  3. 發出數據(TXD)
  4. 數據終端準備好(DTR)
  5. 信號地線(SG)
  6. 數據準備好(DSR)
  7. 請求發送(RTS)
  8. 清除發送(CTS)
  9. 振鈴指示(RI)

3.實物圖:

以下是我購買XX公司的一個usb轉串口線:這個頭就是一個公頭,另一端是一個usb口

技術分享圖片

笨小孩串口工具運行圖:

1.開啟程序

技術分享圖片

2.發送一行字符串HelloBenXH,直接將針腳的發送和接收鏈接起來就可以測試了(針腳2 接受數據(RXD) 和3 發出數據(TXD))直接鏈接,

技術分享圖片

C#代碼實現:采用SerialPort

1.實例化一個SerialPort

1 private SerialPort ComDevice = new SerialPort();

2.初始化參數綁定接收數據事件

技術分享圖片
 1 public void init()
 2         {
 3             btnSend.Enabled = false;
 4             cbbComList.Items.AddRange(SerialPort.GetPortNames());
 5             if (cbbComList.Items.Count > 0)
 6             {
 7                 cbbComList.SelectedIndex = 0;
 8             }
 9             cbbBaudRate.SelectedIndex = 5;
10             cbbDataBits.SelectedIndex = 0;
11             cbbParity.SelectedIndex = 0; 
12             cbbStopBits.SelectedIndex = 0;
13             pictureBox1.BackgroundImage = Properties.Resources.red;
14 
15             ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//綁定事件
16             
17         }
技術分享圖片

3.打開串口button事件

技術分享圖片
 1 /// <summary>
 2         /// 打開串口
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnOpen_Click(object sender, EventArgs e)
 7         {
 8             if (cbbComList.Items.Count <= 0)
 9             {
10                 MessageBox.Show("沒有發現串口,請檢查線路!");
11                 return;
12             }
13 
14             if (ComDevice.IsOpen == false)
15             {
16                 ComDevice.PortName = cbbComList.SelectedItem.ToString();
17                 ComDevice.BaudRate = Convert.ToInt32(cbbBaudRate.SelectedItem.ToString());
18                 ComDevice.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
19                 ComDevice.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
20                 ComDevice.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.SelectedItem.ToString());
21                 try
22                 {
23                     ComDevice.Open();
24                     btnSend.Enabled = true;
25                 }
26                 catch (Exception ex)
27                 {
28                     MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
29                     return;
30                 }
31                 btnOpen.Text = "關閉串口";
32                 pictureBox1.BackgroundImage = Properties.Resources.green;
33             }
34             else
35             {
36                 try
37                 {
38                     ComDevice.Close();
39                     btnSend.Enabled = false;
40                 }
41                 catch (Exception ex)
42                 {
43                     MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
44                 }
45                 btnOpen.Text = "打開串口";
46                 pictureBox1.BackgroundImage = Properties.Resources.red;
47             }
48 
49             cbbComList.Enabled = !ComDevice.IsOpen;
50             cbbBaudRate.Enabled = !ComDevice.IsOpen;
51             cbbParity.Enabled = !ComDevice.IsOpen;
52             cbbDataBits.Enabled = !ComDevice.IsOpen;
53             cbbStopBits.Enabled = !ComDevice.IsOpen;
54         }
技術分享圖片

4.發送數據

技術分享圖片
 1 /// <summary>
 2         /// 發送數據
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="data"></param>
 6         public bool SendData(byte[] data)
 7         {
 8             if (ComDevice.IsOpen)
 9             {
10                 try
11                 {
12                     ComDevice.Write(data, 0, data.Length);//發送數據
13                     return true;
14                 }
15                 catch (Exception ex)
16                 {
17                     MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
18                 }
19             }
20             else
21             {
22                 MessageBox.Show("串口未打開", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
23             }
24             return false;
25         }
26 
27         /// <summary>
28         /// 發送數據button事件
29         /// </summary>
30         /// <param name="sender"></param>
31         /// <param name="e"></param>
32         private void btnSend_Click(object sender, EventArgs e)
33         {
34             byte[] sendData = null;
35 
36             if (rbtnSendHex.Checked)
37             {
38                 sendData = strToHexByte(txtSendData.Text.Trim());
39             }
40             else if (rbtnSendASCII.Checked)
41             {
42                 sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
43             }
44             else if (rbtnSendUTF8.Checked)
45             {
46                 sendData = Encoding.UTF8.GetBytes(txtSendData.Text.Trim());
47             }
48             else if (rbtnSendUnicode.Checked)
49             {
50                 sendData = Encoding.Unicode.GetBytes(txtSendData.Text.Trim());
51             }
52             else
53             {
54                 sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
55             }
56 
57             if (this.SendData(sendData))//發送數據成功計數
58             {
59                 lblSendCount.Invoke(new MethodInvoker(delegate
60                 {
61                     lblSendCount.Text = (int.Parse(lblSendCount.Text) + txtSendData.Text.Length).ToString();
62                 }));
63             }
64             else
65             {
66 
67             }
68 
69         }
70 
71         /// <summary>
72         /// 字符串轉換16進制字節數組
73         /// </summary>
74         /// <param name="hexString"></param>
75         /// <returns></returns>
76         private byte[] strToHexByte(string hexString)
77         {
78             hexString = hexString.Replace(" ", "");
79             if ((hexString.Length % 2) != 0)
80                 hexString += " ";
81             byte[] returnBytes = new byte[hexString.Length / 2];
82             for (int i = 0; i < returnBytes.Length; i++)
83                 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ",""), 16);
84             return returnBytes;
85         }
技術分享圖片

5.接收和數據輸出

技術分享圖片
 1 /// <summary>
 2         /// 接收數據
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
 7         {
 8             byte[] ReDatas = new byte[ComDevice.BytesToRead];
 9             ComDevice.Read(ReDatas, 0, ReDatas.Length);//讀取數據
10             this.AddData(ReDatas);//輸出數據
11         }
12        
13         /// <summary>
14         /// 添加數據
15         /// </summary>
16         /// <param name="data">字節數組</param>
17         public void AddData(byte[] data)
18         {
19             if (rbtnHex.Checked)
20             {
21                 StringBuilder sb = new StringBuilder();
22                 for (int i = 0; i < data.Length; i++)
23                 {
24                     sb.AppendFormat("{0:x2}" + " ", data[i]);
25                 }
26                 AddContent(sb.ToString().ToUpper());
27             }
28             else if (rbtnASCII.Checked)
29             {
30                 AddContent(new ASCIIEncoding().GetString(data));
31             }
32             else if (rbtnUTF8.Checked)
33             {
34                 AddContent(new UTF8Encoding().GetString(data));
35             }
36             else if (rbtnUnicode.Checked)
37             {
38                 AddContent(new UnicodeEncoding().GetString(data));
39             }
40             else
41             {}
42           
43             lblRevCount.Invoke(new MethodInvoker(delegate
44             {
45                 lblRevCount.Text = (int.Parse(lblRevCount.Text) + data.Length).ToString();
46             }));
47         }
48 
49 
50         /// <summary>
51         /// 輸入到顯示區域
52         /// </summary>
53         /// <param name="content"></param>
54         private void AddContent(string content)
55         {
56             this.BeginInvoke(new MethodInvoker(delegate
57             {
58                 if(chkAutoLine.Checked && txtShowData.Text.Length>0)
59                 {
60                     txtShowData.AppendText("\r\n");
61                 }
62                 txtShowData.AppendText(content);
63             }));
64         }
技術分享圖片

6.清空數據區域事件

技術分享圖片
 1 /// <summary>
 2         /// 清空接收區
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnClearRev_Click(object sender, EventArgs e)
 7         {
 8             txtShowData.Clear();
 9         }
10 
11         /// <summary>
12         /// 清空發送區
13         /// </summary>
14         /// <param name="sender"></param>
15         /// <param name="e"></param>
16         private void btnClearSend_Click(object sender, EventArgs e)
17         {
18             txtSendData.Clear();
19         }
技術分享圖片

運行程序下載地址 BXHSerialPort.exe

源代碼工程文件下載

C#串口介紹以及簡單串口通信程序設計實現