串口 DataReceived 触发太多 [英] Serial port DataReceived firing too much

查看:67
本文介绍了串口 DataReceived 触发太多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个来电显示串行设备并编写以下程序:

I'm handling a caller id serial device and write the following program:

serialPort = new SerialPort("COM7", 19200, Parity.None, 8, StopBits.One);
serialPort.DataReceived += serialPort_DataReceived;
serialPort.RtsEnable = true;
serialPort.Encoding = Encoding.ASCII;
serialPort.Open();

void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    Console.WriteLine(Encoding.ASCII.GetString(data));
}

起初我接到一个电话,事件完美地触发,结果是:"A0101181456926E"

At first that I receive a call, the event fires perfectly and the result is: "A0101181456926E"

问题是后续事件...下次我打电话时,事件 serialPort_DataReceived 会触发很多次,每个事件都有 1 个字符.

The problem is the subsequent events... next time that I make a call, the event serialPort_DataReceived fires a lot of times each one with 1 char.

是否有任何要设置的属性或要调用的方法来解决此行为?

Is there any property to set or method to invoke to solve this behaviour?

ps.如果我注释 serialPort.RtsEnable = true; 行,我不会收到任何后续事件.

ps. If I comment the line serialPort.RtsEnable = true;, I don't receive any subsequent event.

推荐答案

正如 Henk 提到的,您可以使用属性 设置在触发 DataReceived 事件之前要接收的字节数ReceivedBytesThreshold.

As Henk mentioned, you can set the amount of bytes to be received before the DataReceived event is triggered with the property ReceivedBytesThreshold.

但在任何情况下,您都必须处理一次要接收的任意数量的字节.您必须以一种能够识别何时完全接收消息的方式来设计您的协议.

But in any case you have to deal with any number of bytes to be received at a time. You have to design your protocol in a way that you are able to recognize when a message is fully received.

这篇关于串口 DataReceived 触发太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆