我正在尝试处理我的传入缓冲区,并确保在每次传输时获得所有125字节的数据。我创建了一个字节数组。我怎么知道正在接收125字节的数据。我尝试显示字节数,但它显示不同的数字,我不确定它是否是正确的编码,以获得接收的字节数。
这是我的代码:
void datareceived(object sender, SerialDataReceivedEventArgs e)
{
myDelegate d = new myDelegate(update);
listBox1.Invoke(d, new object[] { });
}
public void update()
{
Console.WriteLine("Number of bytes:" + serialPort.BytesToRead); // it shows 155
while (serialPort.BytesToRead > 0)
bBuffer.Add((byte)serialPort.ReadByte());
ProcessBuffer(bBuffer);
}
private void ProcessBuffer(List<byte> bBuffer)
{
// Create a byte array buffer to hold the incoming data
byte[] buffer = bBuffer.ToArray();
// Show the user the incoming data // Display mode
for (int i = 0; i < buffer.Length; i++)
{
listBox1.Items.Add("SP: " + (bBuffer[43].ToString()) + " " + " HR: " + (bBuffer[103].ToString()) + " Time: ");
}
}
答案 0 :(得分:7)
当你正在阅读,直到本地接收缓冲区(BytesToRead
)为空时,更好的方法是保持缓冲区和偏移量,并循环直到你有<强>你需要什么,即使这意味着等待 - 即
byte[] buffer = new byte[125]
int offset = 0, toRead = 125;
...
int read;
while(toRead > 0 && (read = serialPort.Read(buffer, offset, toRead)) > 0) {
offset += read;
toRead -= read;
}
if(toRead > 0) throw new EndOfStreamException();
// you now have all the data you requested