我正在尝试从 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/