C#中怎么实现监听串口

发布时间:2021-07-08 14:34:29 作者:Leah
来源:亿速云 阅读:265

C#中怎么实现监听串口,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

C#串口监听的实现在 Visual Stdio 2005中,对于串口操作Framework提供了一个很好的类接口-SerialPort,在这当中,串口数据的读取与写入有较大的不同。C#串口监听的实现由于串口不知道数据何时到达,因此有两种方法可以实现C#串口监听之串口数据的读取。1.用线程实时读串口2.用事件触发方式实现。但由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1。

此外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。

C#串口监听实现一、创建WIndow项目,设计界面

C#中怎么实现监听串口

C#串口监听实现二、编写实现代码

using System;  using System.Collections.Generic;  using System.ComponentModel;  using System.Data;  using System.Drawing;  using System.Text;  using System.Windows.Forms;  using System.IO.Ports;  //using Microsoft.VisualBasic.Devices;   //C#串口监听  namespace Demo  ...{  public partial class Form1 : Form  ...{  public Form1()  ...{  InitializeComponent();  }   private SerialPort Sp = new SerialPort();  public delegate void HandleInterfaceUpdataDelegate(string text);  private HandleInterfaceUpdataDelegate interfaceUpdataHandle;   private void Form1_Load(object sender, EventArgs e)  ...{  tbID.Focus();  BtPause.Enabled = false;  }   private void UpdateTextBox(string text)  ...{  tbData.Text = text;  }   public void Sp_DataReceived(object sender,  System.IO.Ports.SerialDataReceivedEventArgs e)  ...{  byte[] readBuffer = new byte[Sp.ReadBufferSize];  Sp.Read(readBuffer, 0, readBuffer.Length);  this.Invoke(interfaceUpdataHandle,   new string[] ...{ Encoding.UTF8.GetString(readBuffer) });  }   private void Form1_FormClosing(  object sender, FormClosingEventArgs e)  ...{  Sp.Close();  }   private void btENT_Click(object sender, EventArgs e)  ...{  if ((tbID.Text.Trim() != "") &&   (cmRate.Text != ""))  ...{  interfaceUpdataHandle =   new HandleInterfaceUpdataDelegate(UpdateTextBox);  //C#串口监听之实例化委托对象  Sp.PortName = tbID.Text.Trim();  serialPort1.BaudRate =   Convert.ToInt32(cmRate.Text.Trim());  Sp.Parity = Parity.None;  Sp.StopBits = StopBits.One;  Sp.DataReceived +=   new SerialDataReceivedEventHandler(Sp_DataReceived);  Sp.ReceivedBytesThreshold = 1;  try ...{  Sp.Open();  tbID.ReadOnly = true;  BtPause.Enabled = true;  btENT.Enabled = false;  }  catch ...{  MessageBox.Show(  "端口" + tbID.Text.Trim() + "打开失败!");  }  }//C#串口监听  else ...{  MessageBox.Show("请输入正确的端口号和波特率!");  tbID.Focus();  }  }   private void BtPause_Click(  object sender, EventArgs e)  ...{  Sp.Close();  tbID.ReadOnly = false;  btENT.Enabled = true;  BtPause.Enabled = false;  }  }//C#串口监听  }

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 怎么实现C#串口通信
  2. C#串口通讯概念是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:C#中怎么创建一个串口通信程序

下一篇:iOS中在APP内加入AppStore评分功能的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》