linux C 串口编程

2 篇文章 0 订阅
1 篇文章 0 订阅

        最近在做串口编程,在linux下串口编程设置繁多,一个参数设置不对,收到的数据就会出错或者漏掉数据,现发一个多方测试正确的config。

int uart_config(int fd,int baude ,int databits,int stopbits,int parity)
{
    struct termios opt;

    if( tcgetattr(fd ,&opt) != 0)
    {
        perror("get attr failed!\n");
        return -1;
    }

    switch(baude)
    {
        case 4800:
            cfsetispeed(&opt,B4800);
            cfsetospeed(&opt,B4800);
            break;
        case 9600:
            cfsetispeed(&opt,B9600);
            cfsetospeed(&opt,B9600);
            break;
        case 19200:
            cfsetispeed(&opt,B19200);
            cfsetospeed(&opt,B19200);
            break;
        case 38400:
            cfsetispeed(&opt,B38400);
            cfsetospeed(&opt,B38400);
            break;
        default:
            fprintf(stderr,"Unknown baude!");
            return -1;
    }

    opt.c_cflag &= ~CSIZE;
    switch (databits)
     {
        case 5:
          opt.c_cflag |= CS5;
          break;
        case 6:
          opt.c_cflag |= CS6;
          break;
        case 7:
          opt.c_cflag |= CS7;
          break;
        case 8:
          opt.c_cflag |= CS8;
          break;
        default:
          printf("Unsupported data size\n");
          return -1;
     }

    switch(parity)
     {
        case 'n':
        case 'N':
           opt.c_cflag &= ~PARENB;
           opt.c_iflag &= ~INPCK;
           break;
        case 'o':
        case 'O':
           opt.c_cflag |= (PARODD|PARENB);
           opt.c_iflag |= INPCK;
           break;
        case 'e':
        case 'E':
           opt.c_cflag |= PARENB;
           opt.c_cflag &= ~PARODD;
           opt.c_iflag |= INPCK;
           break;
        default:
           printf("Unsupported parity\n");
           return -1;
     }

    switch(stopbits)
     {
        case 1:
           opt.c_cflag &= ~CSTOPB;
           break;
        case 2:
           opt.c_cflag |= CSTOPB;
           break;
        default:
           printf("Unsupported stop bits\n");
           return -1;
     }

     opt.c_iflag &= ~(IXON | IXOFF | IXANY | BRKINT | ICRNL | INPCK | ISTRIP);
     opt.c_lflag &=  ~(ICANON | ECHO | ECHOE | IEXTEN | ISIG);
     opt.c_oflag &= ~OPOST;
     opt.c_cc[VTIME] = 5;
     opt.c_cc[VMIN] = 0;

     tcflush(fd, TCIOFLUSH);
     if (tcsetattr(fd, TCSANOW, &opt) != 0)
     {
        perror("set attr failed!\n");
        return -1;
     }
     return 0;
}

大家有啥问题可以留言啊,一起探讨。

原文参考:

https://www.linuxidc.com/Linux/2014-11/109307.htm  //这个config设置的很对。

https://blog.csdn.net/continue_862/article/details/79919028//这位仁兄的程序也做了参考,但是在我这测试没法正确接收数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值