c - 从 COM 端口读取会破坏线路

标签 c windows serial-port

我正在尝试从 Windows 中的 COM 端口逐行读取数据。在 PuTTY 中,COM 连接看起来很好——我的串行设备(一个 MSP430 Launchpad)每秒输出一次字符串“Data”。但是,当我使用一个简单的 C 程序读取 COM 端口并打印出读取的字节数,然后是数据本身时,它会完全损坏:

0
6 Data

2 Data

4 ta


6 Data

3 Data

3 a
a

6 Data

6 Data

2 Data

6 Data 的行是正确的(四个字符,然后是 \r\n),但是那些不包含完整消息的行发生了什么?根据the documentation , ReadFile 应该默认读取整行。这是不正确的吗?我需要自己缓冲它并等待换行符吗?

请注意,并非所有这些错误都会在每次运行代码时发生;为了您的观赏乐趣,我进行了几次运行并整理了各种错误。这是我正在使用的代码:

#include <windows.h>
#include <stdio.h>

static DCB settings;
static HANDLE serial;
static char line[200];
static unsigned long read;
static unsigned int lineLength = sizeof(line) / sizeof(char);

int main(void) {
   int i = 10;

   serial = CreateFile("COM4",
      GENERIC_READ | GENERIC_WRITE,
      0, NULL,
      OPEN_EXISTING,
      0, NULL);

   GetCommState(serial, &settings);
   settings.BaudRate = CBR_9600;
   settings.ByteSize = 8;
   settings.Parity = NOPARITY;
   settings.StopBits = ONESTOPBIT;
   SetCommState(serial, &settings);

   while(i) {
      ReadFile(serial, &line, lineLength, &read, 0);
      printf("%lu %s\n", read, line);
      i--;
   }
   scanf("%c", &read);

   return 0;
}

使用 Visual Studio Express 2012 在 Windows 7 64 位中编译。

最佳答案

发生的事情是 ReadFile 在获取任何数据后返回。由于数据可能会在将来的某个时候从串口接收到,ReadFile 将在从串口接收到一定量的数据时返回。如果您尝试从串行端口读取,Linux 中也会发生同样的事情。您取回的数据可能是也可能不是整行,具体取决于您的进程再次分派(dispatch)时缓冲区中有多少信息。

如果您再看一下文档,请注意它只会在 HANDLE 处于控制台模式时返回一行:

Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of the ReadFile function. By default, the console mode is ENABLE_LINE_INPUT, which indicates that ReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, but GetLastError returns ERROR_OPERATION_ABORTED. For more information, see CreateFile.

关于c - 从 COM 端口读取会破坏线路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601944/

相关文章:

python - 禁用 python 记录器输出

java - 来自外部 JAR 的 Minecraft 插件 ClassNotFound 错误

c# - 从 56k 调制解调器创建拨号音

子进程可以 <defunct> 而父进程不死吗?

python - ClearCase 符号链接(symbolic link)未映射到 Windows 7 本身?

c++ - 如何在c/c++控制台程序中正常输出utf8编码的字符?

c# - 如何通过串行端口RS-232或USB转换器将体重秤的重量显示到文本框?

c - 遇到奇怪的情况-变量值

c++ - 我可以在 C 中存储指向 C++ 类的指针吗?

c - 打印值,C