Silny ToJa
Silny ToJa

Reputation: 2261

How to receive more messages from Serial Port c#

I am using System.IO.Ports. I send messages to device and want to wait for all messages from it.

I am trying do it like this:

message = Console.ReadLine();
_serialPort.Write(message);
Console.WriteLine(_serialPort.ReadExisting());

But it returns only the first line. I have tried using port.BytesToRead, but I get the same results. When I use ReadLine() it doesn't return anything.

Edit:

To see all line use Event handler.

Solution for my problem is use \r (enter) on the end line.

Upvotes: 1

Views: 1299

Answers (2)

Erwin Draconis
Erwin Draconis

Reputation: 784

ReadExisting return the available bytes available at the exacte time, put a delay befor you read the buffer, a work around would be

message = Console.ReadLine();
_serialPort.Write(message);
Thread.Sleep(200);
Console.WriteLine(_serialPort.ReadExisting());

Edit 2 : here is how i do it on my projects

private SerialPort port;
string DataReceived  = string.Empty;

public string OpenPort(string PortName, int BaudRate)
    {
        // if the port is already used by other window then return the same instance
        if (port != null)
            if(port.IsOpen)
                return "True";


        port = new SerialPort(PortName, BaudRate, Parity.None, 8, StopBits.One);

        // Attach a method to be called when there
        // is data waiting in the port's buffer
        port.DataReceived += new
            SerialDataReceivedEventHandler(port_DataReceived);

        // Begin communications
        try
        {
            port.Open();
        }
        catch(Exception ex)
        {
            return ex.Message;
        }
        return "True";
    }


private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
Thread.sleep(200);
            DataReceived =  port.ReadExisting();
        }

in your main

message = Console.ReadLine();
_serialPort.Write(message);
//use Stopwatch to calculate time befor you can exit from the loop
while(true)
{
if(!string.IsNullOrWhiteSpace(DataReceived))
break;
// Todo : Check stopwatch for timeout
}

Upvotes: 2

Müller
Müller

Reputation: 335

Maybe you have a new line issue expected from your serial device try:

message = Console.ReadLine();
_serialPort.WriteLine(message);
Console.WriteLine(_serialPort.ReadExisting()); # try debug here replace with string test = _serialPort.ReadLine();

Upvotes: 0

Related Questions