生成c语言读取串口数据的代码
时间: 2023-03-08 19:58:22 浏览: 87
可以参考下面的代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>int main(int argc, char *argv[])
{
int fd;
struct termios opt;
char buf[255]; fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if (fd < 0) {
perror("open");
return -1;
}
tcgetattr(fd, &opt);
cfsetispeed(&opt, B9600);
cfsetospeed(&opt, B9600);
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_cflag &= ~PARENB;
opt.c_cflag &= ~CSTOPB;
opt.c_cflag &= ~CSIZE;
opt.c_cflag |= CS8;
opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
opt.c_oflag &= ~OPOST;
opt.c_cc[VMIN] = 1;
opt.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &opt); while (1) {
memset(buf, 0, sizeof(buf));
int n = read(fd, buf, sizeof(buf));
if (n > 0) {
printf("Received: %s\n", buf);
}
} return 0;
}