题
我想在我的电脑和一些控制板之间进行沟通。
期望是PC将在RS-485上发送电路板的标识符,然后它应该从板上接收答案。
当我尝试收到响应时,我收到了错误的数据。
这是我的代码:
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();
}
.
如果我使用RS-232,则可以使用,但是当我使用RS-485时没有。
更新:
它是RS-485 2线。( http://en.wikipedia.org/wiki/ RS-485 )
解决方案
我发现了这个问题。
sp.Read(rec,0,rec.Length);
.
Read
是一种非阻塞方法,所以它读取缓冲区,但不等待所有字节。因此,您需要使用此函数的返回值,该函数返回包含它可以读取的多个字节的整数。
我正在使用这个:
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);
}
. 不隶属于 StackOverflow