c#中seralport的一些用法
来源:互联网 发布:apache 图片压缩 编辑:程序博客网 时间:2024/06/04 00:54
很经典!!! SerialPort中串口数据的读取与写入有较大的不同。由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取。一、线程实时读串口;二、事件触发方式实现。
由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1。
另外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。如下:
SerialPortspSend; //spSend,spReceive用虚拟串口连接,它们之间可以相互传输数据。spSend发送数据
SerialPortspReceive; //spReceive接受数据
TextBoxtxtSend; //发送区
TextBoxtxtReceive; //接受区
ButtonbtnSend; //数据发送按钮
delegatevoid HandleInterfaceUpdateDelegate(string text); //委托,此为重点
HandleInterfaceUpdateDelegate interfaceUpdateHandle;
publicvoid InitClient() //窗体控件已在初始化
{
interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox); //实例化委托对象
spSend.Open(); //SerialPort对象在程序结束前必须关闭,在此说明
spReceive.DataReceived += Ports.SerialDataReceivedEventHandler(spReceive_DataReceived);
spReceive.ReceivedBytesThreshold = 1;
spReceive.Open();
}
publicvoid btnSend_Click(object sender,EventArgs e)
{
spSend.WriteLine(txtSend.Text);
}
publicvoid spReceive_DataReceived(object sender,Ports.SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[spReceive.ReadBufferSize];
spReceive.Read(readBuffer, 0, readBuffer.Length);
this.Invoke(interfaceUpdateHandle, new string[] { Encoding.Unicode.GetString(readBuffer) });
}
privatevoid UpdateTextBox(string text)
{
txtReceive.Text = text;
}
原文地址:c#中seralport的一些用法作者:静水流深
由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1。
另外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。如下:
SerialPort
SerialPort
TextBox
TextBox
Button
delegate
HandleInterfaceUpdateDel
public
{
}
public
{
}
public
{
}
private
{
}
- c#中seralport的一些用法
- c#中ToString()的一些常用用法
- C#中ToString()的一些常用用法
- c#中string类的一些用法
- C#中ToString() 的一些常用用法
- c#中string的一些基本用法
- C#的一些用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- C#中一些字符串操作的常用用法
- c#.net2010总结
- MFC中控件的用法【转】
- Windows程序设计基础总结
- 关于对象的总结
- vs常用类
- c#中seralport的一些用法
- 串行通信程序(C#)
- 51单片机的data,bdata,idata…
- Android中JNI和NDK的使用
- C# winform退出方法
- c# winform委托实例
- 转:.CRC的校验原理
- CRC16校验C语言程序源码(转载)
- 51单片机的MODBUS C语言程序…