Linux非阻塞读取串口数据

#include <stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <stdlib.h>
char *dev="/dev/ttyUSB0";

int OpenDev(char *Dev)
{
    int fd = open( Dev, O_RDWR | O_NOCTTY | O_NDELAY);         
    if (-1 == fd) { 
        perror("Can't Open Serial Port");
        return -1;
    } else
        return fd;
}

int read_fun(int fd,char *buf ,int len){
    int tem = read(fd,buf,len);
    printf("read:%s\n",buf);
    return tem;
}


int write_fun(int fd,char *buf ,int len){

    return write(fd,buf,len);
}


int main(){

    char *write_buf = "hello";
    char *read_buf = (char *)malloc(20);
    int fd;
    fd_set set;
    pid_t pid;
    fd = OpenDev(dev);
    printf("fd is %d\n",fd);



while(1){
    FD_ZERO(&set);        

        FD_SET(fd, &set);//此处将读取的串口fd加入队列     

    pid = fork();
    if(pid == 0){
    while(1){
        select(fd+1,&set,NULL,NULL,NULL);//此次判断读取的队列
            if(FD_ISSET(fd, &set)){  /*测试读取fd是否在set集合中*/        
            read_fun(fd,read_buf,20);
        }
      }
    }else{
    while(1){
        int write_tem = write_fun(fd,write_buf,sizeof(write_buf));
        printf("write %d bytes\n",write_tem);
        sleep(5);
        }
       }       
    }   
}

需要在串口处将收发短接,才能收到数据

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux C 中打开并读取串口数据,可以使用以下步骤: 1. 打开串口设备文件,使用 open() 函数,例如: ``` int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { perror("open error"); exit(1); } ``` 其中,/dev/ttyS0 表示串口设备文件路径,O_RDWR 表示读写方式打开,O_NOCTTY 表示不将串口设备作为控制终端,O_NDELAY 表示非阻塞方式打开。 2. 配置串口参数,使用 termios 结构体和 tcsetattr() 函数,例如: ``` 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_oflag &= ~OPOST; options.c_cc[VMIN] = 1; options.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &options); ``` 其中,B9600 表示波特率,CLOCAL 和 CREAD 表示忽略 modem 状态和启用接收器,PARENB 表示启用奇偶校验,CSTOPB 表示使用两个停止位,CSIZE 表示数据位数,CRTSCTS 表示启用 RTS/CTS 硬件流控,ICANON、ECHO、ECHOE、ISIG、OPOST 分别表示输入模式、回显、回显擦除、信号处理、输出模式,VMIN 和 VTIME 分别表示最小读取字符数和超时时间。 3. 读取串口数据,使用 read() 函数,例如: ``` char buf[1024]; int n = read(fd, buf, sizeof(buf)); if (n < 0) { perror("read error"); exit(1); } else if (n == 0) { printf("no data\n"); } else { printf("read %d bytes: %s\n", n, buf); } ``` 其中,buf 表示读取数据缓冲区,sizeof(buf) 表示缓冲区大小,n 表示实际读取的字节数。 4. 关闭串口设备文件,使用 close() 函数,例如: ``` close(fd); ``` 注意,在使用串口之前,可能需要使用 root 权限或者将用户添加到 dialout 用户组中,以获得串口读写权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值