How to read bytes in C #

I am trying to process my incoming buffer and make sure that I receive all 125 bytes of data with each transfer. I created an array of bytes. How can I find out that 125 bytes of data are being accepted. I tried to display the number of bytes, but displayed a different number, and I'm not sure if it encodes the number of bytes received correctly.

Here is 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: "); } } 
+4
source share
1 answer

At the moment, you are reading while the local receive buffer ( BytesToRead ), however, the best approach is to keep the buffer and offset, and loop until you have what you need , even if it means waiting - i.e. .

 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 
+7
source

Source: https://habr.com/ru/post/1386996/


All Articles