以下是用C语言实现阻塞式读取串口数据直至读取到len长度数据的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    int fd, len;
    char buf[100];

    if (argc != 3) {
        printf("Usage: %s <port> <len>\n", argv[0]);
        return -1;
    }

    len = atoi(argv[2]);

    fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0) {
        perror("open");
        return -1;
    }

    struct termios opt;
    tcgetattr(fd, &opt);
    opt.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
    opt.c_iflag = IGNPAR;
    opt.c_oflag = 0;
    opt.c_lflag = 0;
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &opt);

    int n = 0;
    while (n < len) {
        int ret = read(fd, buf + n, len - n);
        if (ret < 0) {
            if (errno == EAGAIN || errno == EINTR) {
                continue;
            } else {
                perror("read");
                break;
            }
        } else if (ret == 0) {
            usleep(1000);
            continue;
        } else {
            n += ret;
        }
    }

    printf("Read %d bytes: %s\n", n, buf);

    close(fd);

    return 0;
}

注意事项:

  1. 必须以root权限运行程序才能访问串口设备文件;
  2. 串口设备文件的名称应该为类似于"/dev/ttyUSB0"的形式;
  3. 在Linux下,在打开设备文件之前需要将O_NOCTTY标志设置为1,以避免程序成为控制终端;
  4. 在读取串口数据时,需要设置O_NDELAY标志以保证读操作是非阻塞的,不然会一直阻塞等待数据到来
用C写一个阻塞式读取串口数据直至读取到len长度数据

原文地址: https://www.cveoy.top/t/topic/hlw9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录