串口通信抛出 TimeoutException [英] Serial port communication throwing TimeoutException

查看:79
本文介绍了串口通信抛出 TimeoutException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟进串行端口通信解决方案 我实现了以下设计.我的代码使用 com8 与正在侦听的 串行端口实用程序应用程序 通信com9 在同一台机器内,然后发回(我手动输入消息并按下按钮)

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)

我主要是这样做的:

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
    }
}

然而,它在第 7 步抛出一个错误说:

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

{操作已超时."}

内部异常:空

你能告诉我我哪里出错了吗?请和谢谢.

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

推荐答案

ReadLine 一直等到它看到 SerialPort.NewLine 字符串.如果这未在 SerialPort.ReadTimeout 内到达,则抛出 TimeoutException.所以不要错过发送NewLine!

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!

这是一个没有 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);

这篇关于串口通信抛出 TimeoutException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆