欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于C#實現(xiàn)串口通信

 更新時間:2022年02月17日 12:50:35   作者:Zed_H  
這篇文章主要為大家詳細介紹了基于C#實現(xiàn)串口通信,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了C#實現(xiàn)串口通信的具體代碼,供大家參考,具體內(nèi)容如下

1.基本概念

2.前端winForm布局如下(僅僅為了實現(xiàn)功能,布局略丑)

3.代碼實現(xiàn)如下

namespace SerialPortTest
? {
? ? ? public partial class Form1 : Form
? ? ? {
? ? ? ? ? SerialPort sp1 = new SerialPort();
? ? ? ? ? public Form1()
? ? ? ? ? {
? ? ? ? ? ? ? InitializeComponent();
? ? ? ? ? }
??
? ? ? ? ? private void Form1_Load(object sender, EventArgs e)
? ? ? ? ? {
       ?//分別對應(yīng)前端的波特率、數(shù)字位、校驗位、停止位
? ? ? ? ? ? ? cbBaudRate.SelectedIndex = 0;
? ? ? ? ? ? ? cbDataBits.SelectedIndex = 0;
? ? ? ? ? ? ? cbCheck.SelectedIndex = 0;
? ? ? ? ? ? ? cbStop.SelectedIndex = 0;
??
? ? ? ? ? ? ? string[] strCom = SerialPort.GetPortNames();
? ? ? ? ? ? ? if (strCom == null)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("本機沒有串口!", "Error");
? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? }
? ? ? ? ? ? ? //GetPortNames()方法:獲取當前計算機的串行端口名的數(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è)置一個值,該值在串行通信過程中啟用數(shù)據(jù)終端就緒 (DTR) 信號。
? ? ? ? ? ? ? sp1.RtsEnable = true;//獲取或設(shè)置一個值,該值指示在串行通信中是否啟用請求發(fā)送 (RTS) 信號
? ? ? ? ? ? ? //設(shè)置數(shù)據(jù)讀取超時為1秒
? ? ? ? ? ? ? sp1.ReadTimeout = 1000;
??
? ? ? ? ? ? ? sp1.Close();
? ? ? ? ? }
??
? ? ? ? ? private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
? ? ? ? ? {
? ? ? ? ? ? ? if (sp1.IsOpen) ? ? //判斷是否打開串口
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? //輸出當前時間
? ? ? ? ? ? ? ? ? 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));//用萬能的UTF8可以傳輸中文不會亂碼
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ?catch (System.Exception ex)
? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message, "出錯提示!!!!!");
? ? ? ? ? ? ? ? ? ? ? txtSendStr.Text = "";
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? }
? ? ? ? ? ? ? else
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("請打開某個串口", "錯誤提示");
? ? ? ? ? ? ? }
? ? ? ? ? }
??
? ? ? ? ? //將接受到的內(nèi)容顯示出來
? ? ? ? ? private void AddContent(string content)
? ? ? ? ? {
? ? ? ? ? ? ? this.BeginInvoke(new MethodInvoker(delegate
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? txtReceived.AppendText(content);
? ? ? ? ? ? ? ? ? txtReceived.AppendText("\r\n");
? ? ? ? ? ? ? ? ? //記錄收到的字符個數(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è)置串口號
? ? ? ? ? ? ? ? ? ? ? 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) ? ? ? ? ? ? //校驗位
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ?case "無":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.None;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "奇校驗":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Odd;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "偶校驗":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Even;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?default:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:參數(shù)不正確!", "Error");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? ? ? ? ?if (sp1.IsOpen == true)//如果打開狀態(tài),則先關(guān)閉一下
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Close();
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? ? ? ? ?//設(shè)置必要控件不可用
? ? ? ? ? ? ? ? ? ? ?cbCom.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbDataBits.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbStop.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbCheck.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?sp1.Open(); ? ? //打開串口
? ? ? ? ? ? ? ? ? ? ?btnOpen.Text = "關(guān)閉串口";
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?catch (System.Exception ex)
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:" + ex.Message, "Error");
? ? ? ? ? ? ? ? ? ? ?return;
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? ?else
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?//恢復控件功能
? ? ? ? ? ? ? ? ?//設(shè)置必要控件不可用
? ? ? ? ? ? ? ? ?cbCom.Enabled = true;
? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = true;
? ? ? ? ? ? ? ? ?cbDataBits.Enabled = true;
? ? ? ? ? ? ? ? ?cbStop.Enabled = true;
? ? ? ? ? ? ? ? ?cbCheck.Enabled = true;
? ? ? ? ? ? ? ? ?sp1.Close(); ? ? ? ? ? ? ? ? ? ?//關(guān)閉串口
? ? ? ? ? ? ? ? ?btnOpen.Text = "打開串口";
? ? ? ? ? ? ?}
? ? ? ? ?}
?
? ? ? ? ?private void btnSend_Click(object sender, EventArgs e)
? ? ? ? ?{
? ? ? ? ? ? ?byte[] sendData = null;
? ? ? ? ? ? ?if (!sp1.IsOpen) //如果沒打開
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?MessageBox.Show("請先打開串口!", "Error");
? ? ? ? ? ? ? ? ?return;
? ? ? ? ? ? ?}
? ? ? ? ? ? ?String strSend = txtSendStr.Text;
? ? ? ? ? ? ?try
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?sendData = Encoding.UTF8.GetBytes(txtSendStr.Text.Trim());
? ? ? ? ? ? ? ? //sp1.WriteLine(txtSendStr.Text); ? ?//寫入數(shù)據(jù)
? ? ? ? ? ? ? ? ?sp1.Write(sendData, 0, sendData.Length);
? ? ? ? ? ? ? }
? ? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("Error:" + ex.Message, "Error");
}
?
}
?
}
}

4.測試運行結(jié)果如下

在自己同一臺電腦上測試,需要先用Configure Virtual Serial Port Driver建立兩個虛擬串口,如下

串口運行結(jié)果如下:

上述兩窗體通信時要選擇同一波特率,不然收發(fā)數(shù)據(jù)會失敗

關(guān)于C# serialport的一些說明:

SerialPort() :如果未指定,則此構(gòu)造函數(shù)使用默認屬性值。 例如, DataBits 屬性默認值為 8, Parity 屬性默認為 None 枚舉值,
StopBits 屬性默認值為 1,默認端口名為 COM1。

public static string[] GetPortNames() :獲取當前計算機的串行端口名的數(shù)組

SerialPort.Read 方法 (Byte[], Int32, Int32) :從 SerialPort 輸入緩沖區(qū)讀取一些字節(jié)并將那些字節(jié)寫入字節(jié)數(shù)組中指定的偏移量處

SerialPort.ReadLine 方法 () :一直讀取到輸入緩沖區(qū)中的 NewLine 值

SerialPort.Write 方法 (Byte[], Int32, Int32) : 使用緩沖區(qū)中的數(shù)據(jù)將指定數(shù)量的字節(jié)寫入串行端口

SerialPort.WriteLine 方法 (String) : 將指定的字符串和 NewLine 值寫入輸出緩沖區(qū)。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • ftp服務(wù)器搭建部署與C#實現(xiàn)ftp文件的上傳的示例

    ftp服務(wù)器搭建部署與C#實現(xiàn)ftp文件的上傳的示例

    本文主要介紹了ftp服務(wù)器搭建部署與C#實現(xiàn)ftp文件的上傳的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • C#實現(xiàn)一鍵換IP、重置DNS、網(wǎng)關(guān)及掩碼的方法

    C#實現(xiàn)一鍵換IP、重置DNS、網(wǎng)關(guān)及掩碼的方法

    這篇文章主要介紹了C#實現(xiàn)一鍵換IP、重置DNS、網(wǎng)關(guān)及掩碼的方法,很實用的功能,需要的朋友可以參考下
    2014-07-07
  • C#基礎(chǔ)知識之this關(guān)鍵字介紹

    C#基礎(chǔ)知識之this關(guān)鍵字介紹

    本文主要介紹this關(guān)鍵字的幾種使用方法,this可以代表當前實例,可以調(diào)用其他構(gòu)造函數(shù),還可以用來構(gòu)建索引器,這里都有一一舉例說明。
    2016-04-04
  • WPF微信聊天和通訊錄按鈕樣式代碼分享

    WPF微信聊天和通訊錄按鈕樣式代碼分享

    這篇文章主要為大家分享了WPF微信聊天和通訊錄按鈕樣式代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • C# Winform 子窗體訪問父級窗體的控件和屬性

    C# Winform 子窗體訪問父級窗體的控件和屬性

    本文主要介紹兩種子窗體訪問父窗體控件和屬性的方法,大家可以參考一下,本人比較偏向第二種,把父窗體作為屬性傳遞,一勞永逸,想訪問父窗體的什么控件屬性都可以。
    2016-05-05
  • C# 中用 Sqlparameter 的兩種用法

    C# 中用 Sqlparameter 的兩種用法

    這篇文章主要介紹了C# 中用 Sqlparameter 的幾種用法,文中給大家列舉了兩種用法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-09-09
  • C#中的集合用法分析

    C#中的集合用法分析

    這篇文章主要介紹了C#中的集合用法,實例形式分析了集合元素的定義、賦值、插入、移除等操作,需要的朋友可以參考下
    2014-10-10
  • 關(guān)于C#中yield?return用法的思考

    關(guān)于C#中yield?return用法的思考

    在這篇文章中,我們將深入討論?C#?中yield?return的機制和用法,幫助您更好地理解這個強大的功能,并在實際開發(fā)中靈活使用它,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-05-05
  • C#10的13個特性

    C#10的13個特性

    本文詳細講解了C#10的13個特性,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-12-12
  • Unity 從UI中拖拽對象放置并拖動效果 附demo

    Unity 從UI中拖拽對象放置并拖動效果 附demo

    最近新接了個需求,要求模擬場景并生成3D對象,對象可以跟隨鼠標移動效果,今天小編把我實現(xiàn)的demo分享到腳本之家平臺,對Unity UI拖拽相關(guān)知識感興趣的朋友跟隨小編一起學習吧
    2021-05-05

最新評論