Linux C非阻塞读串口数据
在Linux下,可以使用以下步骤实现C语言非阻塞读串口数据:
- 打开串口
使用open()函数打开串口设备文件,并设置非阻塞标志:
int fd;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
- 配置串口参数
使用tcgetattr()函数获取当前串口参数,然后修改需要的参数,最后使用tcsetattr()函数设置新的串口参数:
struct termios oldtio, newtio;
tcgetattr(fd, &oldtio);
memset(&newtio, 0, sizeof(newtio));
newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
其中,B9600表示波特率为9600,CS8表示数据位为8,CLOCAL表示忽略调制解调器状态线,CREAD表示启用接收器。
- 读取串口数据
使用read()函数读取串口数据,如果没有数据可读,则返回-1并设置errno为EAGAIN:
char buf[255];
int n;
n = read(fd, buf, sizeof(buf));
if (n == -1 && errno == EAGAIN) {
printf("no data available\n");
} else if (n > 0) {
buf[n] = '\0';
printf("read: %s\n", buf);
}
如果读取到数据,则将其打印出来。
- 关闭串口
使用close()函数关闭串口:
close(fd);
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
int main()
{
int fd;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
struct termios oldtio, newtio;
tcgetattr(fd, &oldtio);
memset(&newtio, 0, sizeof(newtio));
newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
char buf[255];
int n;
n = read(fd, buf, sizeof(buf));
if (n == -1 && errno == EAGAIN) {
printf("no data available\n");
} else if (n > 0) {
buf[n] = '\0';
printf("read: %s\n", buf);
}
close(fd);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/eCqj 著作权归作者所有。请勿转载和采集!