Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to use SerialPort object to listen for incoming data and send outgoing data.

Doing each other separately, it is working well - I can send or receive with no issues. The problem happens when I want to make this port available for both operations.

What I do is this (In a dedicated thread):

private void SerialCommunicationsListen(SerialPort serialPort)
{
while (true)
{
string val = serialPort.ReadLine();
// do some code with val
}
}

This is the listener. 2nd thing I'm doing is this for sending data out:

public void SendMessage(SerialPort port, string message)
{
port.Write(message);
}

Both are using the same SerialPort object. The thing is that if I call "SendMessage" when the listener is up, the listener receives the data instead of the device, and if it is down, the device is the one receiving it.

What am I doing wrong here? I want to do both transmit and receive from the device on the same port.
Posted

1 solution

Don't.
The problem is probably that ReadLine is a blocking operation - it doesn't return until a complete line together with line end character(s) has been received by the serial port - so your code can't do anything else until that happens.

Instead, use the SerialPort.DataReceived event[^] and buffer up the data yourself in a stringbuilder yuntiul you have a complete line. You can then process the line.
That way, your code isn't sitting waiting for data all the time and doing nothing else!
 
Share this answer
 
Comments
impeham 18-Apr-15 6:12am    
won't this solution create the same problem? when i write to the port, my listener is the one receiving the data (and i assume will be the one that will get the raised event) instead of the device...
OriginalGriff 18-Apr-15 6:33am    
Check your port with Hyperterminal or similar - it sounds like you have an echo coming back from the device (some do that if they receive text so the user can read it as he types)
impeham 18-Apr-15 7:18am    
Thanks - i found it :)
working well now.

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