Question

I want to communicate between my PC and some controller boards.

The expectation is that the PC will send an identifier of the board on RS-485 and then it should receive the answer from the board.

When I try to receive the response, I receive the wrong data.

Here is my code:

public void set()
    {

        SerialPort sp = new SerialPort("COM1");
        sp.Open();
        if (sp.IsOpen)
        {
            byte[] id = new byte[]{0,0,0,0,0,0,0,0,0,0};
            byte[] rec = new byte[540];
            while (!end)
            {
                sp.Write(id,0,id.Length);

                sp.Read(rec,0,rec.Length);

                //do some with rec
                //WORKING
                //do soem with rec

            }
        }
        sp.Close();
    }

It works if I am using RS-232, but not when I am using RS-485.

UPDATE :

It is RS-485 2 wire.(http://en.wikipedia.org/wiki/RS-485)

Was it helpful?

Solution

I found the problem.

 sp.Read(rec,0,rec.Length);

Read is a non-blocking method so it reads the buffer but does not wait for all of the bytes. So you need to use the return value of this function which returns an integer with a number of bytes that it could read.

I am using this:

int read = 0;
int shouldRead = readData1.Length;
int len;
while (read < shouldRead )
{
    len = serialport.Read(buffer, 0, readData1.Length);
    if (len == 0)
         continue;
    Array.Copy(buffer, 0, readData1, read, len);
    read += len;
    Thread.Sleep(20);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top