C语言串口读取完整的报文
时间: 2023-04-10 16:05:19 浏览: 138
可以使用以下代码来读取完整的串口报文:
```c
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main() {
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open");
return -1;
}
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &options);
char buffer[255];
int n = 0;
while (1) {
int len = read(fd, buffer + n, 255 - n);
if (len > 0) {
n += len;
if (buffer[n - 1] == '\n') {
buffer[n - 1] = '\0';
printf("Received message: %s\n", buffer);
n = 0;
}
}
}
close(fd);
return 0;
}
```
这段代码使用了 Linux 下的串口通信 API,可以读取串口发送过来的完整报文。
阅读全文