Receiving serial data is an asynchronous operation and you usually get not all data from a packet with a single event.
So you have to create at least the receive buffer and an index as (private) class members to store the received data by appending until you know that a complete package has been received. The buffer must be large enough to store the largest possible package size.
A very simple example from scratch:
bool newData = false;
int rxOffset = 0;
byte[] rxBuffer = new byte[MAX_PACKAGE_LENGTH];
byte[] rxPackage = new byte[MAX_PACKAGE_LENGTH];
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
int bytes = port.BytesToRead;
port.Read(rxBuffer, rxOffset, bytes);
rxOffset += bytes;
if (HasCompletePackage())
{
rxBuffer.CopyTo(rxPackage, 0);
rxOffset = 0;
newData = true;
}
}
Note that the above does not include additional checks like overflow of the receive buffer, detection of incomplete packages (e.g. at startup) and locking access to shared variables (here:
newData
and
rxPackage
).