【问题标题】:Serial port communication throwing TimeoutException串口通信抛出TimeoutException
【发布时间】:2016-09-06 12:48:09
【问题描述】:

跟进Serial Port Communication solution 我实现了以下设计。我的代码使用com8 与在同一台机器上监听com9Serial Port Utility Application 通信,然后发回(我手动输入消息并按下按钮)

我主要是这样做的:

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

然后在我的课堂上我有这个:

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 步抛出错误:

{"操作已超时。"}

InnerException: null

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

【问题讨论】:

  • 我们不是已经经历过了吗?您必须设置 Handshake 属性,它不是可选的。如果您使用 Handshake.None,那么您必须将 DtrEnable 和 RtsEnable 属性设置为 true。您使用的实用程序仅用于与设备对话,而不是与您的程序对话。将 PC 发送回 PC 的数据的本地环回需要一根将 com8 连接到 com9 的空调制解调器电缆。你的线程坏了,它只能读一次。不要使用线程。
  • 嘿,汉斯先生 \o/ 再一次:)。我还在苦苦挣扎 :( 我有一条从 com8 到 com9 的硬件电缆!而且我无法重现上次的问题,所以我使用了这个多线程。我现在正在尝试 MyPort.Handshake = SetPortHandshake(MyPort.Handshake);MSDN

标签: c# multithreading serial-port


【解决方案1】:

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

这是一个没有 NewLine 的替代版本。

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

【讨论】:

  • 嗨,杰夫。我有 5 秒钟的时间输入 back 并按下按钮。我很确定没有错过发送 NewLine。
  • 尝试使用 Read 而不是 ReadLine。
  • 读取不需要 0 个参数
  • 果然必须使用正确的方法参数。这是一个测试数据是否到达的测试。您也可以尝试 ReadExisting,但在您能够输入答案之前它不会阻塞。并且 - 再次 - 将您发送的内容与 NewLine 的实际值进行比较。通常 CR 和 LF 可能会混淆。
  • 成功了。现在,带有字符串 back 的 Read() 和带有字符串 back\n 的 ReadLine() 都可以正常工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 2022-01-16
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
相关资源
最近更新 更多