简体   繁体   中英

Reading bytes from the serial port

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM