user2628363
user2628363

Reputation: 143

Putting delay in read and write from serial port

Hi I'm writing an application to work with a device by using serial port. I've written the code and it works fine when I put breaking points but when I debug it with out breaking points the expected data is part by part. For example when I put break points and read from port the correct data is "ali" but when I remove breaking points the data will be "a" ,"li" . here's my snippet code for writing and reading from port :

 fname1 = Encoding.Default.GetBytes("write1"  + dataRow[0].ToString());
 comport.Write(fname1,0,fname1.Length);
 lname1 = Encoding.Default.GetBytes("write4" + dataRow[1].ToString());
 comport.Write(lname1, 0, lname1.Length); 

c3 = Encoding.Default.GetBytes("read" +0x1);
comport.Write(c3,0,c3.Length);
comport.Read(fname1, 0, fname1.Length);
string s = Encoding.Default.GetString(fname1);
MessageBox.Show(s);

I assume cause I have encoding there is some time wasting and this explains the effect of breaking point which I described.

My solution is to put delay in two consecutive read or write . Am I correct ? If yes how can I implement that? Is there a better way?

Upvotes: 0

Views: 3028

Answers (1)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

The problem is, when you call comport.Read, that reads whatever data is available to be read. It is quite possible that the whole message has not arrived at the serial port yet.

If you're expecting a certain number of bytes, then you could use a loop like:

var bytesReceived= 0;
while(bytesReceived < fname1.Length)
{
    bytesReceived += 
        comport.Read(fname1, bytesReceived, fname1.Length - bytesReceived);
}

It is also possible to read a single line using SerialPort.ReadLine, or read upto a certain string using SerialPort.ReadTo.

For more info on those methods, see MSDN.

Upvotes: 1

Related Questions