Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send and recieve over rs-485 serial port?

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)

like image 378
M.Movaffagh Avatar asked Oct 08 '22 18:10

M.Movaffagh


1 Answers

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);
}
like image 114
M.Movaffagh Avatar answered Oct 13 '22 11:10

M.Movaffagh