Linux C串口编程非阻塞读写数据
Linux C串口编程中,非阻塞读写数据可以通过设置串口的属性来实现。具体步骤如下:
- 打开串口设备文件,获取文件描述符。
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
- 设置串口属性。
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= CLOCAL | CREAD;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
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] = 0;
options.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &options);
其中,设置了波特率为9600,数据位为8位,无校验位,停止位为1位,禁用硬件流控,禁用软件流控,禁用回显等。
- 非阻塞读写数据。
char buf[256];
int nread = read(fd, buf, sizeof(buf));
if (nread > 0) {
// 读取到数据
}
int nwrite = write(fd, "hello", 5);
if (nwrite < 0) {
// 写入数据失败
}
在非阻塞模式下,读取数据时如果没有数据可读,则read函数会立即返回0,不会阻塞等待数据。写入数据时如果串口发送缓冲区已满,则write函数会立即返回-1,不会阻塞等待缓冲区有空间。因此,需要在代码中处理好读写函数返回值,确保数据的正确读写
原文地址: http://www.cveoy.top/t/topic/eph0 著作权归作者所有。请勿转载和采集!