c++ - 等待 COM 端口上的数据?

标签 c++ windows serial-port

我正在寻找一种方法让 Windows 串行端口在收到数据之前超时。如果有某种类型的事件触发或有一个函数可以完全按照我想要的方式执行,那就太好了。

这是我当前的实现。

void waitforCom(unsinged char byte)
{
   while (true)
   {
      ClearCommError(serial_handle, &errors, &status);
      if (status.cbInQue>0)
      {
         //check if correct byte
         break;
      }
   }
}

最佳答案

您可以使用的另一个 API 调用是 WaitCommEvent()

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363479(v=vs.85).aspx

此调用可以异步工作,因为它采用 OVERLAPPED 对象作为参数。在您的情况下,您只需等待 EV_RXCHAR 事件即可让您知道数据已到达:

OVERLAPPED o = {0};
o.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

SetCommMask(comPortHandle, EV_RXCHAR);

if (!WaitCommEvent(comPortHandle, &commEvent, &o))
{
    // Check GetLastError for ERROR_IO_PENDING, if I/O is pending then
    // use WaitForSingleObject() to determine when `o` is signaled, then check
    // the result. If a character arrived then perform your ReadFile.
}

或者,您也可以通过使用一个具有未完成的 ReadFile 调用的线程来执行相同的操作,但使用 OVERLAPPED 对象,而不是像 MSalters 建议的那样阻塞。

关于c++ - 等待 COM 端口上的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20183510/

相关文章:

c++ - 使用 task_group(新用户)的 Intel Threading Building Blocks 性能不佳

c++ - 英特尔 tbb 中的奇怪错误

c# - Python 中 C# 的 GetEncoding ("28591") 相当于什么?

c++ - 从格式化文件创建 std::vector

c++ - 如何检测我是否正在使用特定的 Visual Studio 版本编译代码?

php - 将 php 脚本结果写入文本文件

python - 在 Windows 上将原始数据写入物理磁盘(闪存驱动器)失败并显示 "Bad file descriptor"- Python

c# - 如何将MySQL查询结果存储在一个字符串中

python - 阅读Python串行

c++ - float 类型的默认参数 = 乱码