C#實現(xiàn)簡單串口通信的示例詳解
串口通信
C# 串口通信主要操作:
命名空間:using System.IO.Ports;
獲取端口:string[] ports = System.IO.Ports.SerialPort.GetPortNames();
設(shè)置端口名:serialPort1.PortName = “COM1”; // 字符串
設(shè)置波特率:serialPort1.BaudRate = 115200;// int.Parse(“115200”);
設(shè)置數(shù)據(jù)位:serialPort1.DataBits = 1; // int.Parse(“1”);
設(shè)置停止位:serialPort1.StopBits = StopBits.One;
- StopBits.One:停止位1
- StopBits.OnePointFive:停止位1.5
- StopBits.Two:停止位2
設(shè)置校驗位:serialPort1.Parity = Parity.None;
- Parity.None:無
- Parity.Even:奇校驗
- Parity.Odd:偶校驗
打開串口:serialPort1.Open();
關(guān)閉串口:serialPort1.Close();
可讀字節(jié):serialPort1.BytesToRead;
讀取數(shù)據(jù):serialPort1.Read(buffer, 0, len);
寫入數(shù)據(jù):serialPort1.Write(buffer);
接收事件: XXX_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);
示例代碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Ports; namespace serial_tools { public partial class Form1 : Form { String serialPortName; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] ports = System.IO.Ports.SerialPort.GetPortNames(); // 獲取本機可用串口端口 comboBoxPort.Items.AddRange(ports); comboBoxPort.SelectedIndex = comboBoxPort.Items.Count > 0 ? 0 : -1; // 有可用端口顯示第一個 comboBoxBaudrate.Text = "115200"; // 默認波特率 comboBoxDataBits.Text = "8"; // 默認數(shù)據(jù)位:8 comboBoxStopbit.Text = "1"; // 默認停止位:1 comboBoxCheck.Text = "無"; // 默認無校驗 } /// <summary> /// 重寫 系統(tǒng)消息函數(shù) /// </summary> /// <param name="m"></param> protected override void WndProc(ref Message m) { base.WndProc(ref m); } /// <summary> /// 串口數(shù)據(jù)接收 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int len = serialPort1.BytesToRead; // 獲取可讀字節(jié)數(shù) byte[] buff = new byte[len]; // 創(chuàng)建緩存數(shù)據(jù)數(shù)組 serialPort1.Read(buff, 0, len); // 把數(shù)據(jù)讀取到buff數(shù)組 string str = Encoding.Default.GetString(buff); // Byte值轉(zhuǎn)ASCII字符串 Invoke((new Action(() => { if (checkBoxHexShow.Checked) { textBoxRecv.AppendText(byteToHexStr(buff)); } else { textBoxRecv.AppendText(str); } }))); // 對話框追加顯示數(shù)據(jù) } public static string byteToHexStr(byte[] bytes) { string hexStr = ""; try { if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { hexStr += bytes[i].ToString("X2"); hexStr += " "; // 兩個Hex數(shù)值以空格隔開 } } return hexStr; } catch (Exception) { return hexStr; } } /// <summary> /// 打開關(guān)閉串口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonPortOnOff_Click(object sender, EventArgs e) { if (buttonPortOnOff.Text == "打開串口") { try { serialPort1.PortName = comboBoxPort.Text; // 獲取選擇的串口端口 serialPortName = comboBoxPort.Text; serialPort1.BaudRate = int.Parse(comboBoxBaudrate.Text); // 獲取選擇的波特率 serialPort1.DataBits = int.Parse(comboBoxDataBits.Text); // 獲取選擇的數(shù)據(jù)位 // 設(shè)置停止位 if (comboBoxStopbit.Text == "1") { serialPort1.StopBits = StopBits.One; } else if (comboBoxStopbit.Text == "1.5") { serialPort1.StopBits = StopBits.OnePointFive; } else if (comboBoxStopbit.Text == "2") { serialPort1.StopBits = StopBits.Two; } // 設(shè)置奇偶校驗 if (comboBoxCheck.Text == "無") { serialPort1.Parity = Parity.None; } else if (comboBoxCheck.Text == "奇校驗") { serialPort1.Parity = Parity.Even; } else if (comboBoxCheck.Text == "偶校驗") { serialPort1.Parity = Parity.Odd; } // 打開串口 serialPort1.Open(); buttonPortOnOff.Text = "關(guān)閉串口"; } catch (Exception ex) { MessageBox.Show("串口打開失敗"+ ex.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { serialPort1.Close(); } catch (Exception ex) { } buttonPortOnOff.Text = "打開串口"; } } /// <summary> /// 清空接收數(shù)據(jù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonClearRecv_Click(object sender, EventArgs e) { textBoxRecv.Clear(); } /// <summary> /// 發(fā)送數(shù)據(jù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonSendData_Click(object sender, EventArgs e) { String Str = textBoxSend.Text.ToString(); // 獲取發(fā)送文本框里的數(shù)據(jù) try { if (Str.Length > 0) { serialPort1.Write(Str); // 串口發(fā)送數(shù)據(jù) } } catch (Exception) { } } /// <summary> /// 清除發(fā)送數(shù)據(jù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonClearSend_Click(object sender, EventArgs e) { textBoxSend.Clear(); } private void comboBoxPort_SelectedIndexChanged(object sender, EventArgs e) { } private void comboBoxPort_MouseClick(object sender, MouseEventArgs e) { } } }
窗體界面設(shè)計
運行效果
到此這篇關(guān)于C#實現(xiàn)簡單串口通信的示例詳解的文章就介紹到這了,更多相關(guān)C#串口通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# Dynamic關(guān)鍵字之:解析dynamic就是Object
本篇文章是對C#中dynamic關(guān)鍵字就是Object進行了詳細的分析介紹,需要的朋友參考下2013-05-05c#中SqlHelper封裝SqlDataReader的方法
這篇文章主要介紹了c#中SqlHelper封裝SqlDataReader的方法,涉及C#針對數(shù)據(jù)庫相關(guān)操作封裝與使用的技巧,需要的朋友可以參考下2015-05-05C#實現(xiàn)將javascript文件編譯成dll文件的方法
這篇文章主要介紹了C#實現(xiàn)將javascript文件編譯成dll文件的方法,涉及C#編譯生成dll動態(tài)鏈接庫文件的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11C#實現(xiàn)延時并自動關(guān)閉MessageBox的方法
這篇文章主要介紹了C#實現(xiàn)延時并自動關(guān)閉MessageBox的方法,非常實用的功能,需要的朋友可以參考下2014-08-08詳解C# Socket簡單例子(服務(wù)器與客戶端通信)
這篇文章主要介紹了詳解C# Socket簡單例子(服務(wù)器與客戶端通信) ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-12-12