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#中使用DataContractSerializer類實現(xiàn)深拷貝操作示例
這篇文章主要介紹了C#中使用DataContractSerializer類實現(xiàn)深拷貝操作示例,本文給出了實現(xiàn)深拷貝方法、測試深拷貝方法例子、DataContractSerializer類實現(xiàn)深拷貝的原理等內(nèi)容,需要的朋友可以參考下2015-06-06C# ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的完美解決方法
這篇文章主要介紹了C# ComboBox控件“設(shè)置 DataSource 屬性后無法修改項集合”的解決方法,非常不錯具有一定的參考借鑒價值,需要的朋友可以參考下2016-11-11詳解C#中的System.Timers.Timer定時器的使用和定時自動清理內(nèi)存應用
這篇文章主要介紹了詳解C#中的System.Timers.Timer定時器的使用和定時自動清理內(nèi)存應用,需要的朋友可以參考下2017-06-06C#利用OpenCvSharp實現(xiàn)玉米粒計數(shù)
這篇文章主要為大家詳細介紹了C#如何結(jié)合OpenCVSharp4實現(xiàn)玉米粒計數(shù),文中的示例代碼簡潔易懂,具有一定的學習價值,需要的小伙伴可以參考下2023-11-11