Question

I'm trying to run a serial communication using the [SerialPort] class. I made a simple console application project where I test this class using HyperTerminal.

This is my program:

class Program
{
    private static bool _continue = true;
    private static SerialPort port;

    static void Main(string[] args)
    {
        try
        {
            port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
            port.ReadTimeout = port.WriteTimeout = 5000;
            port.Open();

            Thread thread = new Thread(Read);
            thread.Start();

            while (_continue)
            {
                string message = Console.ReadLine();

                if (message.Equals("quit"))
                    _continue = false;
                else
                    port.Write(message);
            }

            thread.Join();
            port.Close();
        }
        catch (Exception ex)
        { }
    }

    private static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = port.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }
}

The problem is the following: when I write a line (in the console) a can see in the HyperTerminal GUI what i wrote, but when I write a line using HyperTerminal no message is read by my program that thorws always a TimeoutException.

Why?
How can I solve this problem?
Thanks.

Was it helpful?

Solution

Try Port.Read in case Port.ReadLine is waiting for new line !

OTHER TIPS

How about making use of SerialPort.DataRecieved event?

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top