我正在尝试读取一米的数据。设备实际支持的圣杯是1000 samples per second
。如果重要,波特率为38400, Parity.None
和Stopbits.One
。我正在使用binary mode
来保持尽可能快的东西。我计划使用DataReceived事件,如下所示。
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytesToRead = _serialPort.BytesToRead;
byte[] data = new byte[bytesToRead];
int actualBytesRead = 0;
do
{
actualBytesRead = serialPort.Read(data, 0, bytesToRead);
} while (actualBytesRead != bytesToRead);
//At this point assume that the data byte array has all the data
}
BytesToRead
似乎会返回可以为该事件读取的所有字节。但是link表示
The SerialPort class buffers data, but the stream object contained in the
SerialPort.BaseStream property does not. Therefore, the SerialPort object
and the stream object might differ on the number of bytes that are
available to read. When bytes are buffered to the SerialPort object, the
BytesToRead property includes these bytes in its value;
however, these bytes might not be accessible to the stream contained in
the BaseStream property.
Read
仅返回已读取的字节数。
因此,作为对此的预防措施,我计划不断阅读,直到我得到的字节数与BytesToRead为引发的事件所指示的相同。但是,我不清楚几点。
答案 0 :(得分:3)
以下是错误的:
int actualBytesRead = 0;
do
{
actualBytesRead = serialPort.Read(data, 0, bytesToRead);
} while (actualBytesRead != bytesToRead);
在循环的每次迭代中,您总是为offset
传递0,因此每次读取字节时都会覆盖先前读取的字节。
我会按如下方式重写:
for( int offset = 0; offset < data.Length; )
{
int n = serialPort.Read( data, offset, data.Length - offset );
offset += n;
}