Linux下设置驱动实现非标准的波特率(最新版 struct termios2)

其实对于一般的波特率glibc里面已经封装了函数接口,而且非常容易的就可以设置。

但是对于非标准的波特率网上有人提到了ioctl设置,但是最新的内核已经弃用了这种方式,我设置的时候ioctl返回无效

http://blog.chinaunix.net/uid-9543173-id-1988980

我们的方法贴出来:

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

int ioctl(int d, int request, ...);

int main(int argc, char *argv[])
{
  struct termios2 t;
  int fd,baud;

  if (argc != 3)
    {
      fprintf(stderr,"usage: %s <device> <baud>\n", argv[0]);
      return 1;
    }

  fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);

  if (fd == -1)
      {
        fprintf(stderr, "error opening %s: %s", argv[1], strerror(errno));
        return 2;
      }

  baud = atoi(argv[2]);

  if (ioctl(fd, TCGETS2, &t))
    {
      perror("TCGETS2");
      return 3;
    }

  t.c_cflag &= ~CBAUD;
  t.c_cflag |= BOTHER;
  t.c_ispeed = baud;
  t.c_ospeed = baud;

  if (ioctl(fd, TCSETS2, &t))
    {
      perror("TCSETS2");
      return 4;
    }

  if (ioctl(fd, TCGETS2, &t))
    {
      perror("TCGETS2");
      return 5;
    }

  printf("actual speed reported %d\n", t.c_ospeed);
  return 0;
}

其实看到我们用的结构体是 struct termios2 ,特别说明,这个结构体有别于 struct termios,以前内核使用 struct termios,glibc里面也使用该结构体,但是内核更新了 struct termios2,glibc到目前为止没有更新。

当然遗憾的是这个好像只实现了波特率,其他的什么停止位什么的我们依旧用以前的,但是发现编译的时候glibc的头文件和我们引用的内核头文件冲突,https://stackoverflow.com/questions/37710525/including-termios-h-and-asm-termios-h-in-the-same-project 非常easy,解决

 

 

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值