基于C#實(shí)現(xiàn)串口通信
本文實(shí)例為大家分享了C#實(shí)現(xiàn)串口通信的具體代碼,供大家參考,具體內(nèi)容如下
1.基本概念
2.前端winForm布局如下(僅僅為了實(shí)現(xiàn)功能,布局略丑)
3.代碼實(shí)現(xiàn)如下
namespace SerialPortTest ? { ? ? ? public partial class Form1 : Form ? ? ? { ? ? ? ? ? SerialPort sp1 = new SerialPort(); ? ? ? ? ? public Form1() ? ? ? ? ? { ? ? ? ? ? ? ? InitializeComponent(); ? ? ? ? ? } ?? ? ? ? ? ? private void Form1_Load(object sender, EventArgs e) ? ? ? ? ? { ?//分別對(duì)應(yīng)前端的波特率、數(shù)字位、校驗(yàn)位、停止位 ? ? ? ? ? ? ? cbBaudRate.SelectedIndex = 0; ? ? ? ? ? ? ? cbDataBits.SelectedIndex = 0; ? ? ? ? ? ? ? cbCheck.SelectedIndex = 0; ? ? ? ? ? ? ? cbStop.SelectedIndex = 0; ?? ? ? ? ? ? ? ? string[] strCom = SerialPort.GetPortNames(); ? ? ? ? ? ? ? if (strCom == null) ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? MessageBox.Show("本機(jī)沒(méi)有串口!", "Error"); ? ? ? ? ? ? ? ? ? return; ? ? ? ? ? ? ? } ? ? ? ? ? ? ? //GetPortNames()方法:獲取當(dāng)前計(jì)算機(jī)的串行端口名的數(shù)組 ? ? ? ? ? ? ? foreach (string com in System.IO.Ports.SerialPort.GetPortNames()) ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? cbCom.Items.Add(com); ? ? ? ? ? ? ? } ?? ? ? ? ? ? ? ? cbCom.SelectedIndex = 0; ? ? ? ? ? ? ? sp1.BaudRate = 9600; ? ? ? ? ? ? ? Control.CheckForIllegalCrossThreadCalls = false; ? ? ? ? ? ? ? sp1.DataReceived += Sp1_DataReceived; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sp1.DtrEnable = true;//獲取或設(shè)置一個(gè)值,該值在串行通信過(guò)程中啟用數(shù)據(jù)終端就緒 (DTR) 信號(hào)。 ? ? ? ? ? ? ? sp1.RtsEnable = true;//獲取或設(shè)置一個(gè)值,該值指示在串行通信中是否啟用請(qǐng)求發(fā)送 (RTS) 信號(hào) ? ? ? ? ? ? ? //設(shè)置數(shù)據(jù)讀取超時(shí)為1秒 ? ? ? ? ? ? ? sp1.ReadTimeout = 1000; ?? ? ? ? ? ? ? ? sp1.Close(); ? ? ? ? ? } ?? ? ? ? ? ? private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e) ? ? ? ? ? { ? ? ? ? ? ? ? if (sp1.IsOpen) ? ? //判斷是否打開(kāi)串口 ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? //輸出當(dāng)前時(shí)間 ? ? ? ? ? ? ? ? ? DateTime dt = DateTime.Now; ? ? ? ? ? ? ? ? ? txtReceived.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n"; ? ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? Byte[] receivedData = new Byte[sp1.BytesToRead]; ? ? ? ?//創(chuàng)建接收字節(jié)數(shù)組 ? ? ? ? ? ? ? ? ? ? ? sp1.Read(receivedData, 0, receivedData.Length); ? ? ? ? //讀取數(shù)據(jù) ? ? ? ? ? ? ? ? ? ? ? AddContent(new UTF8Encoding().GetString(receivedData));//用萬(wàn)能的UTF8可以傳輸中文不會(huì)亂碼 ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ?catch (System.Exception ex) ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message, "出錯(cuò)提示!!!!!"); ? ? ? ? ? ? ? ? ? ? ? txtSendStr.Text = ""; ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? } ? ? ? ? ? ? ? else ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? MessageBox.Show("請(qǐng)打開(kāi)某個(gè)串口", "錯(cuò)誤提示"); ? ? ? ? ? ? ? } ? ? ? ? ? } ?? ? ? ? ? ? //將接受到的內(nèi)容顯示出來(lái) ? ? ? ? ? private void AddContent(string content) ? ? ? ? ? { ? ? ? ? ? ? ? this.BeginInvoke(new MethodInvoker(delegate ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? txtReceived.AppendText(content); ? ? ? ? ? ? ? ? ? txtReceived.AppendText("\r\n"); ? ? ? ? ? ? ? ? ? //記錄收到的字符個(gè)數(shù) ? ? ? ? ? ? ? ? ? lblRevCount.Text = (int.Parse(lblRevCount.Text) + content.Length).ToString(); ? ? ? ? ? ? ? })); ? ? ? ? ? } ?? ? ? ? ? ? private void btnOpen_Click(object sender, EventArgs e) ? ? ? ? ? { ? ? ? ? ? ? ? //serialPort1.IsOpen ? ? ? ? ? ? ? if (!sp1.IsOpen) ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? //設(shè)置串口號(hào) ? ? ? ? ? ? ? ? ? ? ? string serialName = cbCom.SelectedItem.ToString(); ? ? ? ? ? ? ? ? ? ? ? sp1.PortName = serialName; ?? ? ? ? ? ? ? ? ? ? ? ? //設(shè)置各“串口設(shè)置” ? ? ? ? ? ? ? ? ? ? ? string strBaudRate = cbBaudRate.Text; ? ? ? ? ? ? ? ? ? ? ? string strDateBits = cbDataBits.Text; ? ? ? ? ? ? ? ? ? ? ? string strStopBits = cbStop.Text; ? ? ? ? ? ? ? ? ? ? ? Int32 iBaudRate = Convert.ToInt32(strBaudRate); ? ? ? ? ? ? ? ? ? ? ? Int32 iDateBits = Convert.ToInt32(strDateBits); ? ? ? ? ? ? ? ? ? ? ? ?sp1.BaudRate = iBaudRate; ? ? ? //波特率 ? ? ? ? ? ? ? ? ? ? ?sp1.DataBits = iDateBits; ? ? ? //數(shù)據(jù)位 ? ? ? ? ? ? ? ? ? ? ?switch (cbStop.Text) ? ? ? ? ? ?//停止位 ? ? ? ? ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ? ? ? ?case "1": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.One; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?case "1.5": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.OnePointFive; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?case "2": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.Two; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?default: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:參數(shù)不正確!", "Error"); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ?switch (cbCheck.Text) ? ? ? ? ? ? //校驗(yàn)位 ? ? ? ? ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ? ? ? ?case "無(wú)": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.None; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?case "奇校驗(yàn)": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Odd; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?case "偶校驗(yàn)": ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Even; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ? ? ?default: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:參數(shù)不正確!", "Error"); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break; ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ? ?if (sp1.IsOpen == true)//如果打開(kāi)狀態(tài),則先關(guān)閉一下 ? ? ? ? ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Close(); ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ? ?//設(shè)置必要控件不可用 ? ? ? ? ? ? ? ? ? ? ?cbCom.Enabled = false; ? ? ? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = false; ? ? ? ? ? ? ? ? ? ? ?cbDataBits.Enabled = false; ? ? ? ? ? ? ? ? ? ? ?cbStop.Enabled = false; ? ? ? ? ? ? ? ? ? ? ?cbCheck.Enabled = false; ? ? ? ? ? ? ? ? ? ? ?sp1.Open(); ? ? //打開(kāi)串口 ? ? ? ? ? ? ? ? ? ? ?btnOpen.Text = "關(guān)閉串口"; ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ?catch (System.Exception ex) ? ? ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:" + ex.Message, "Error"); ? ? ? ? ? ? ? ? ? ? ?return; ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ?} ? ? ? ? ? ? ?else ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ?//恢復(fù)控件功能 ? ? ? ? ? ? ? ? ?//設(shè)置必要控件不可用 ? ? ? ? ? ? ? ? ?cbCom.Enabled = true; ? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = true; ? ? ? ? ? ? ? ? ?cbDataBits.Enabled = true; ? ? ? ? ? ? ? ? ?cbStop.Enabled = true; ? ? ? ? ? ? ? ? ?cbCheck.Enabled = true; ? ? ? ? ? ? ? ? ?sp1.Close(); ? ? ? ? ? ? ? ? ? ?//關(guān)閉串口 ? ? ? ? ? ? ? ? ?btnOpen.Text = "打開(kāi)串口"; ? ? ? ? ? ? ?} ? ? ? ? ?} ? ? ? ? ? ?private void btnSend_Click(object sender, EventArgs e) ? ? ? ? ?{ ? ? ? ? ? ? ?byte[] sendData = null; ? ? ? ? ? ? ?if (!sp1.IsOpen) //如果沒(méi)打開(kāi) ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ?MessageBox.Show("請(qǐng)先打開(kāi)串口!", "Error"); ? ? ? ? ? ? ? ? ?return; ? ? ? ? ? ? ?} ? ? ? ? ? ? ?String strSend = txtSendStr.Text; ? ? ? ? ? ? ?try ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ?sendData = Encoding.UTF8.GetBytes(txtSendStr.Text.Trim()); ? ? ? ? ? ? ? ? //sp1.WriteLine(txtSendStr.Text); ? ?//寫(xiě)入數(shù)據(jù) ? ? ? ? ? ? ? ? ?sp1.Write(sendData, 0, sendData.Length); ? ? ? ? ? ? ? } ? ? ? ? ? ? ? catch (Exception ex) ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? MessageBox.Show("Error:" + ex.Message, "Error"); } ? } ? } }
4.測(cè)試運(yùn)行結(jié)果如下
在自己同一臺(tái)電腦上測(cè)試,需要先用Configure Virtual Serial Port Driver建立兩個(gè)虛擬串口,如下
串口運(yùn)行結(jié)果如下:
上述兩窗體通信時(shí)要選擇同一波特率,不然收發(fā)數(shù)據(jù)會(huì)失敗
關(guān)于C# serialport的一些說(shuō)明:
SerialPort() :如果未指定,則此構(gòu)造函數(shù)使用默認(rèn)屬性值。 例如, DataBits 屬性默認(rèn)值為 8, Parity 屬性默認(rèn)為 None 枚舉值,
StopBits 屬性默認(rèn)值為 1,默認(rèn)端口名為 COM1。
public static string[] GetPortNames() :獲取當(dāng)前計(jì)算機(jī)的串行端口名的數(shù)組
SerialPort.Read 方法 (Byte[], Int32, Int32) :從 SerialPort 輸入緩沖區(qū)讀取一些字節(jié)并將那些字節(jié)寫(xiě)入字節(jié)數(shù)組中指定的偏移量處
SerialPort.ReadLine 方法 () :一直讀取到輸入緩沖區(qū)中的 NewLine 值
SerialPort.Write 方法 (Byte[], Int32, Int32) : 使用緩沖區(qū)中的數(shù)據(jù)將指定數(shù)量的字節(jié)寫(xiě)入串行端口
SerialPort.WriteLine 方法 (String) : 將指定的字符串和 NewLine 值寫(xiě)入輸出緩沖區(qū)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ftp服務(wù)器搭建部署與C#實(shí)現(xiàn)ftp文件的上傳的示例
本文主要介紹了ftp服務(wù)器搭建部署與C#實(shí)現(xiàn)ftp文件的上傳的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07C#實(shí)現(xiàn)一鍵換IP、重置DNS、網(wǎng)關(guān)及掩碼的方法
這篇文章主要介紹了C#實(shí)現(xiàn)一鍵換IP、重置DNS、網(wǎng)關(guān)及掩碼的方法,很實(shí)用的功能,需要的朋友可以參考下2014-07-07C#基礎(chǔ)知識(shí)之this關(guān)鍵字介紹
本文主要介紹this關(guān)鍵字的幾種使用方法,this可以代表當(dāng)前實(shí)例,可以調(diào)用其他構(gòu)造函數(shù),還可以用來(lái)構(gòu)建索引器,這里都有一一舉例說(shuō)明。2016-04-04C# Winform 子窗體訪問(wèn)父級(jí)窗體的控件和屬性
本文主要介紹兩種子窗體訪問(wèn)父窗體控件和屬性的方法,大家可以參考一下,本人比較偏向第二種,把父窗體作為屬性傳遞,一勞永逸,想訪問(wèn)父窗體的什么控件屬性都可以。2016-05-05Unity 從UI中拖拽對(duì)象放置并拖動(dòng)效果 附demo
最近新接了個(gè)需求,要求模擬場(chǎng)景并生成3D對(duì)象,對(duì)象可以跟隨鼠標(biāo)移動(dòng)效果,今天小編把我實(shí)現(xiàn)的demo分享到腳本之家平臺(tái),對(duì)Unity UI拖拽相關(guān)知識(shí)感興趣的朋友跟隨小編一起學(xué)習(xí)吧2021-05-05