I’m trying to handle my incoming buffer and ensure that I got all the 125 bytes of the data at each transmission. I’ve created a byte array. How can I know 125 bytes of data is being received. I tried displaying the number of bytes but it displayed different number and I’m unsure if it’s the right coding to get the number of bytes received.
Here’s my code:
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: ");
}
}
At the moment you are reading until the local receive buffer (
BytesToRead) is empty, however, a better approach is to keep a buffer and offset, and loop until you have what you need, even if that means waiting – i.e.