0
votes

Im building an application where i need to reed 15 byes from a serial device. (ScaleXtric c7042 powerbase) The bytes need to come in the right order, and the last one is a crc.

Using this code in an backgroundworker, I get the bytes:

byte[] data = new byte[_APB.ReadBufferSize];
_APB.Read(data, 0, data.Length);

The problem is that I don't get the first bytes first, Its like it stores some of the bytes in the buffer, so next time the DataRecieved event fires, I get the last x bytes from the previous message, and only the 15-x byte from the new. I write the bytes to a text box, and its all over the place, so some bytes are missing somewhere.

I have tried to clear the buffer after each read, but no luck.

_APB = new SerialPort(comboBoxCommAPB.SelectedItem.ToString());
_APB.BaudRate = 19200;
_APB.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandlerDataFromAPB);
_APB.Open();
_APB.DiscardInBuffer();

Hope any one can help me here

1
You only get the bytes currently available in the receive buffer, usually only 1 or 2. Counting them off so you get them all is up to you. Like this.Hans Passant

1 Answers

1
votes

Use this Method to read fixed amout of bytes from serial port, for your case toread = 15;

 public byte[] ReadFromSerialPort(SerialPort serialPort, int toRead)
 {
     byte[] buffer = new byte[toRead];
     int offset = 0;
     int read;

    while (toRead > 0 && (read = serialPort.Read(buffer, offset, toRead)) > 0)
    {
        offset += read;
        toRead -= read;
    }
    if (toRead > 0) throw new EndOfStreamException();

    return buffer;
}