Serial port communication throwing TimeoutException

有些话、适合烂在心里 提交于 2020-06-29 12:37:31

问题


Following up with Serial Port Communication solution I implemented the below design. My code uses com8 to communicate with a Serial Port Utility Application that is listening on com9 within the same machine, then sending back (manually I type a message and press a button)

In my main I do this:

MyClass MyObj = new MyClass();
var message = MyObj.SendThenRecieveDataViaSerialPort("Test");

And then in my class I have this:

private static SerialPort MainSerialPort { get; set; } = new SerialPort();
private static string _ReceivedMessage;
private Thread readThread = new Thread(() => ReadSerialPort(ref _ReceivedMessage));

public string SendThenRecieveDataViaSerialPort(string _Message)
{
    MainSerialPort = new SerialPort("com8", 9600);
    MainSerialPort.ReadTimeout = 5000;
    MainSerialPort.WriteTimeout = 5000;
    MainSerialPort.Open();
    readThread.Start(); // 1

    try
    { // 2
        MainSerialPort.WriteLine(_Message); // 3
        readThread.Join(); // 6 - Console pops and waits
    }
    catch (TimeoutException ex)
    {
        Console.WriteLine("Exception in SendThenreceive");
    }

    return _ReceivedMessage;
}

private static void ReadSerialPort(ref string _message)
{
    try
    { // 4
        _message= MainSerialPort.ReadLine(); // 5 
    }
    catch (TimeoutException ex)
    {
        // 7 - when time outs
    }
}

However, it is throwing an error at step 7 saying:

{"The operation has timed out."}

InnerException: null

Could you tell me where I am going wrong? Please and thanks.


回答1:


ReadLine waits until it sees the SerialPort.NewLine string. If this doesn't arrive within SerialPort.ReadTimeout the TimeoutException is thrown. So don't miss to send the NewLine!

Here is an alternative version without NewLine.

byte[] data = new byte[1024];
int bytesRead = MainSerialPort.Read(data, 0, data.Length);
_message = Encoding.ASCII.GetString(data, 0, bytesRead);


来源:https://stackoverflow.com/questions/39349409/serial-port-communication-throwing-timeoutexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!