1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Only one question still left, what if the serialPort buffer reads its max?
If you let the buffer fill, you will lose all subsequent bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.