1
votes

I am building a c# application that needs to read some serial data received from an arduino. The arduino sends the following:

Serial.write(0x1);
Serial.write(0x106);
Serial.write(fake_channel.samples, SAMPLE_COUNT); //Sample array

The sample array is nothing else than an array filled with integers.

What is the best way to read this with an c# application? I need to get the integer from the serial data. So when I got 0x1, I want to read the 1. I am able to read data with the following method:

private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    //Code to read the serial data needed here

}

In an older application of mine, I was able to read some serial data in string format with: serialPort.ReadExisting(); The only problem now is that I am not receiving a string, but an integer that looks like a byte. That is the part I am confused about because how is it possible to read an integer out of a thing that looks like a byte.

1

1 Answers

1
votes

The DataReceived event tells you that some bytes were received and you can go and read them.

If you want to read bytes (not strings) you can use serialPort.BytesToRead property to know how many bytes are available to read. You can then use serialPort.Read(byte[], int, int) method to read all bytes at once, or serialPort.ReadByte() method to read one byte at a time.

If you try to read more bytes that the ones available the the method will block until the specified number of bytes are available. To prevent this you can set a read timeout using serialPort.ReadTimeout.