I made an application in C# which sends 11 byte of data to a serial port using:
port = new SerialPort("COM1");
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.ReadTimeout = 1000;
port.WriteTimeout = 1000;
port.Open();
byte[] buffer = new byte[11];
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 3;
buffer[4] = 2;
buffer[5] = 4;
buffer[6] = 1;
buffer[7] = 20;
buffer[8] = 50;
buffer[9] = 0;
buffer[10] = 120;
port.Write(buffer, 0, 11);
Then I wrote another application to test the previous one. I would like to check if the 11 bytes were correctly sent. In this application I use:
using (SerialPort port = new SerialPort("COM1"))
{
// configure serial port
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Open();
for (; ; )
{
byte[] b = new byte[11];
port.Read(b, 0, 11);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 11; ++i)
{
sb.Append(b[i]);
sb.Append(" ");
}
Console.WriteLine(sb.ToString());
}
}
to receive bytes. The problem is that, after sending something like this:
0 0 0 3 2 4 1 20 50 0 120
I receive:
0 0 0 0 0 0 0 0 0 0 0
0 0 3 2 1 4 20 50 0 120 0
Why does it happen? What kind of error is there in my code?
Thank you
You’re not checking the result from
port.Read(). It returns the number of bytes read, not the number of bytes requested. The output loop then needs to use this result as the upper limit.Although you’ve setup timeouts on the sending side, you’ll also need them on the reader too.