Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

Icould get data from SerialPort but receives as 2 part. Normally data must be 01 02 00 0B 00 01 C8 08 but writes 01 to buffer first and then receives 02 00 0B 00 01 C8 08.

Output is:
Click to See Log Image From MSDN Forum

Thank you for your helps

What I have tried:

My codes are below:
C#
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
       byte[] buff = new byte[port.BytesToRead];
       Console.WriteLine(port.BytesToRead);
       port.Read(buff, 0, buff.Length);
       SetText(buff);
}
Posted
Updated 7-Dec-17 21:44pm

1 solution

You are handling receiving in an asynchronous event. That is triggered when new data are available. In your case port.BytesToRead is one with the first event. Once the event has been handled (one byte is read) it returns. Meanwhile additional bytes has been received and the event has been triggered again.

A possible solution is using a class global buffer and a buffer index variable so that data can be appended. Once the number of expected data bytes is received (a fixed value like it seems in your case, length is part of data, or there is an end indicator like a new line with text data), process the data (set text) and reset the index variable.
 
Share this answer
 
Comments
alidayan 8-Dec-17 3:47am    
When I add port.Write my problem solved. This is about modbus protocol I think device was waiting to get response
OriginalGriff 8-Dec-17 4:24am    
Doesn't matter - What Jochen says is right: that is how serial data works. As soon as data is available, you will get an event - and the port doesn't "know" about the protocol, it just gets bytes are they come in one after the other. If your remote device sends a message longer than a single character, you will almost certainly get multiple events fired, and you will find that you are mysteriously "losing data" because later individual characters are overwriting previous ones. Unless your computer is spectacularly slow or busy, of course - 9600 baud only allows a maximum of about 1000 characters per second to be transfered!
Jochen Arndt 8-Dec-17 4:41am    
In addition to what Griff said:

Inserting a write will not solve the problem. While it might work on your system it might not work on other systems.
OriginalGriff 8-Dec-17 4:24am    
Gets my five.
Jochen Arndt 8-Dec-17 4:37am    
Thank you for the five and especially for your comment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900