SerialPort.DataReceived事件执行逻辑 [英] SerialPort.DataReceived Event Execution Logic
问题描述
嘿大家。
我有一个问题要问。
我想知道每当数据来自serialPort时,DataReceived事件会自动引发?我已阅读但无法在此处找到信息:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx [ ^ ]
我写了一个小程序,每3秒从串口读取一次数据,但这样做不太安静。
代码如下:
Hey everyone.
I've a question to ask.
I'm wondering that the DataReceived event is automatically raised whenever
a data comes from serialPort? I've read but couldn't find info here:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx[^]
I've written a little program to read data every 3 seconds from serial port, but that doesn't work quiet well.
The code is below:
string buffer;
SerialPort sp = new SerialPort("COM1");
sp.BaudRate = 9600;
sp.Handshake = Handshake.None;
// Handler
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
buffer= sp.ReadExisting();
}
我不想使用Timer,因为数据并不总是以3秒的间隔到达。所以,我无法获得精确的数据。
我知道这是一个简单的问题,但我被卡住了......
任何想法如何间隔阅读?
我最好的问候...
I don't want to use Timer, because the data doesn't always arrive in 3 second intervals. So, I can't get precise datas.
I know this's a simple question, but I'm stuck...
Any idea how to read with intervals?
My best regards...
推荐答案
如果你想以特定的间隔阅读,那么使用一个计时器。
如果你想要处理数据,请使用DataRecieved。
但请注意,DataReceived每次都会被触发字节到达 - 因此您每次读取的数据可能都是单个字符,如果您在每次处理事件时都覆盖它,缓冲区将永远不会保留整个消息。
If you want to read at specific intervals, then use a Timer.
If you want to process data as it comes in, use DataRecieved.
But be aware that DataReceived is fired every time a byte arrives - so the data you read is likely to be a single character each time, and "buffer" will never hold an entire message if you overwrite it every time you handle the event.
这篇关于SerialPort.DataReceived事件执行逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!