转:Linux C下非特定波特率的配置和使用

【转】Linux C下非特定波特率的配置和使用

https://blog.csdn.net/jinhongdu/article/details/43413071


 对于非标准的任意波特率需要用ioctl(fd, TIOCGSERIAL,  p)和ioctl(fd, TIOCSSERIAL, p)的配合,ioctl的最后一个参数是struct serial_struct  *类型,在linux/serial.h中定义。
 
 其中baud_base是基准晶振频率/16,通常是115200,你需要设的是custom_divisor这个值,最终的波特率为baud_base/custom_divisor,比如你需要28800,因为115200/4=28800,所以要设置custom_divisor=4,。
 具体过程为,先设置波特率设为38400(tcsetattr),然后用TIOCGSERIAL得到当前的设置,将flags设置ASYNC_SPD_CUST位,设置custom_divisor,最后用TIOCSSERIAL设置。
 
 使用setserial其实就是利用上述方法,来设置baud_base, custom_divisor等, 其内部实现就是使用ioctl来进行设置。
 
 网上的东西真的是参差不齐,希望能呈现完善的正确的Blog给大家。
 由于是测试代码,只是保证可以运行。另外推荐一个串口调试助手AccessPort,可以提供28800的串口比特率作为测试。

#include <termios.h>
#include <sys/ioctl.h>
#include <stdio.h>      /*标准输入输出定义*/
#include <stdlib.h>     /*标准函数库定义*/
#include <unistd.h>     /*Unix标准函数定义*/
#include <sys/types.h>  /**/
#include <sys/stat.h>   /**/
#include <fcntl.h>      /*文件控制定义*/
#include <termios.h>    /*PPSIX终端控制定义*/
#include <errno.h>      /*错误号定义*/
#include <linux/serial.h>
#define TRUE 1
#define FALSE 0
/*
*功能:用于测试非标准波特率串口。
*此代码仅限于运行在X86架构的环境下,其他架构并未测试。在arm下未测试
*请在root下编译此代码
*如有问题,联系我:靳小都 hellojinhongdu#126.com
*/
struct serial_t {
    int     fd;
    char    *device;/*/dev/ttyS0,...*/
    int     baud;
    int     databit;/*5,6,7,8*/
    char    parity;/*O,E,N*/
    int    stopbit;/*1,2*/
    int    startbit;/*1*/
    struct termios    options;
};
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
        B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400,  19200,  9600,  4800,  2400,  1200,  300,
        38400,  19200,  9600, 4800, 2400, 1200,  300, };
void set_speed(int fd, int speed)
{
  int   i;
  int   status;
  struct termios   Opt;
  tcgetattr(fd, &Opt);
  for ( i= 0;  i < sizeof(speed_arr) / sizeof(int);  i++)
   {
    if  (speed == name_arr[i])
    {
        tcflush(fd, TCIOFLUSH);
        cfsetispeed(&Opt, speed_arr[i]);
        cfsetospeed(&Opt, speed_arr[i]);
        status = tcsetattr(fd, TCSANOW, &Opt);
        if  (status != 0)
            perror("tcsetattr fd1");
        return;
        }
   tcflush(fd,TCIOFLUSH);
   }
}
//设置为特诉波特率,比如28800
int serial_set_speci_baud(struct serial_t *tty,int baud)
{
    struct serial_struct ss,ss_set;
    tcgetattr(tty->fd,&tty->options);
    cfsetispeed(&tty->options,B38400);
    cfsetospeed(&tty->options,B38400);
    tcflush(tty->fd,TCIFLUSH);/*handle unrecevie char*/
    tcsetattr(tty->fd,TCSANOW,&tty->options);
    if((ioctl(tty->fd,TIOCGSERIAL,&ss))<0){
        printf("BAUD: error to get the serial_struct info:%s\n",strerror(errno));
        return -1;
    }
    ss.flags = ASYNC_SPD_CUST;
    ss.custom_divisor = ss.baud_base / baud;
    printf("ss.custom_divisor = %d \r\n",ss.custom_divisor);
    if((ioctl(tty->fd,TIOCSSERIAL,&ss))<0){
        printf("BAUD: error to set serial_struct:%s\n",strerror(errno));
        //return -2;
    }
    ioctl(tty->fd,TIOCGSERIAL,&ss_set);
    printf("BAUD: success set baud to %d,custom_divisor=%d,baud_base=%d\n",
            baud,ss_set.custom_divisor,ss_set.baud_base);
    return 0;
}
/*get serial's current attribute*/
static int serial_get_attr(struct serial_t *tty)
{
    if(tcgetattr(tty->fd,&tty->options) != 0){
        printf("SERIAL: can't get serial's attribute\n");
        return -1;
}
    return 0;
}
/*update serial's attrbute*/
static int serial_attr_update(struct serial_t *tty)
{
    tcflush(tty->fd,TCIFLUSH);/*handle unrecevie char*/
    if((tcsetattr(tty->fd,TCSANOW,&tty->options)) < 0){
        return -1;
}
    return 0;
}
static int serial_init_databit(struct serial_t *tty)
{
    if(serial_get_attr(tty)<0)
        return -1;
    tty->options.c_cflag &= ~CSIZE;
    switch(tty->databit){
        case 5: tty->options.c_cflag |= CS5;break;
        case 6: tty->options.c_cflag |= CS6;break;
        case 7: tty->options.c_cflag |= CS7;break;
        case 8: tty->options.c_cflag |= CS8;break;
        default:
            printf("SERIAL: unsupported databit %d\n",tty->databit);
            return -2;    
}
    if(serial_attr_update(tty) < 0)
        return -3;
    printf("SERIAL: set databit to %d\n",tty->databit);
    return 0;
}
static int serial_init_parity(struct serial_t *tty)
{
    if(serial_get_attr(tty)<0)
        return -1;
    /*ignore framing and parity error*/
    tty->options.c_iflag = IGNPAR;
    switch (tty->parity){
        case 'n':
        case 'N':
            /* Clear parity enable */
            tty->options.c_cflag &= ~PARENB;
            /* Enable parity checking */
            tty->options.c_iflag &= ~INPCK;
            break;
        case 'o':
        case 'O':
            /* 设置为奇校检*/
            tty->options.c_cflag |= (PARODD|PARENB);
            /* Disnable parity checking */
            tty->options.c_iflag |= (INPCK|ISTRIP);
            break;
        case 'e':
        case 'E':
            /* Enable parity */
            tty->options.c_cflag |= PARENB;
            /* 转换为偶效验*/
            tty->options.c_cflag &= ~PARODD;
            /* Disnable parity checking */
            tty->options.c_iflag |= (INPCK|ISTRIP);  
            break;
        default:
            printf("SERIAL: unsupported parity %c\n",tty->parity);
            return -2;
}
    if(serial_attr_update(tty) < 0)
        return -3;
    printf("SERIAL: set parity to %c\n",tty->parity);
    return 0;
}
static int serial_init_stopbit(struct serial_t *tty)
{
    if(serial_get_attr(tty)<0)
        return -1;
    switch(tty->stopbit){
        case 1:
            tty->options.c_cflag &= ~CSTOPB;break;
        case 2:
            tty->options.c_cflag |= CSTOPB;break;
        default:
            printf("SERIAL: unsupported stopbit %d\n",tty->stopbit);  
            return -2;    
}
    if(serial_attr_update(tty) < 0)
        return -3;
    printf("SERIAL: set stopbit to %d\n",tty->stopbit);
    return 0;
}
/**
*@brief   设置串口数据位,停止位和效验位
*@param  fd     类型  int  打开的串口文件句柄*
*@param  databits 类型  int 数据位   取值 为 7 或者8*
*@param  stopbits 类型  int 停止位   取值为 1 或者2*
*@param  parity  类型  int  效验类型 取值为N,E,O,,S
*/
int set_Parity(int fd,int databits,int stopbits,int parity)
{
    struct termios options;
 if  ( tcgetattr( fd,&options)  !=  0)
  {
    perror("SetupSerial 1");
    return(FALSE);
  }
  options.c_cflag &= ~CSIZE;
  switch (databits) /*设置数据位数*/
  {
    case 7:
        options.c_cflag |= CS7;
        break;
    case 8:
        options.c_cflag |= CS8;
        break;
    default:
        fprintf(stderr,"Unsupported data size\n");
        return (FALSE);
    }
  switch (parity)
    {
    case 'n':
    case 'N':
        options.c_cflag &= ~PARENB;   /* Clear parity enable */
        options.c_iflag &= ~INPCK;     /* Enable parity checking */
        break;
    case 'o':
    case 'O':
        options.c_cflag |= (PARODD | PARENB);  /* 设置为奇效验*/
        options.c_iflag |= INPCK;             /* Disnable parity checking */
        break;
    case 'e':
    case 'E':
        options.c_cflag |= PARENB;     /* Enable parity */
        options.c_cflag &= ~PARODD;   /* 转换为偶效验*/
        options.c_iflag |= INPCK;       /* Disnable parity checking */
        break;
    case 'S':
    case 's':  /*as no parity*/
        options.c_cflag &= ~PARENB;
        options.c_cflag &= ~CSTOPB;
        break;
    default:
        fprintf(stderr,"Unsupported parity\n");
        return (FALSE);
        }
  /* 设置停止位*/
  switch (stopbits)
    {
    case 1:
        options.c_cflag &= ~CSTOPB;
        break;
    case 2:
        options.c_cflag |= CSTOPB;
        break;
    default:
        fprintf(stderr,"Unsupported stop bits\n");
        return (FALSE);
    }
  /* Set input parity option */
  if (parity != 'n')
        options.c_iflag |= INPCK;
    options.c_cc[VTIME] = 150; // 15 seconds
    options.c_cc[VMIN] = 0;
  tcflush(fd,TCIFLUSH); /* Update the options and do it NOW */
  if (tcsetattr(fd,TCSANOW,&options) != 0)
    {
        perror("SetupSerial 3");
        return (FALSE);
    }
  return (TRUE);
 }
//用法:只要指定serial_t的baud就可以了
static struct serial_t __seri_conf[] = {
    [0] = {//connect with b board, ttyS0
        .device = "/dev/ttyS1",
        .baud = 28800,
        .databit = 8,
        .parity = 'N',
        .stopbit = 1,
    },
};
/**
*@breif     main()
*/
int main(int argc, char **argv) {
    int fd;
    int nread;
    char buff[512];
    fd = open(__seri_conf->device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    __seri_conf->fd = fd;
    serial_set_speci_baud(__seri_conf, __seri_conf->baud);
    /*
    if (set_Parity(__seri_conf->fd, 8, 1, 'N') == FALSE)
        {
            printf("Set Parity Error\n");
        }
    */
    if(serial_init_databit(__seri_conf)<0)
        printf("serial_init_databit error\n");
    if(serial_init_parity(__seri_conf)<0)
        printf("serial_init_parity error\n");
    if(serial_init_stopbit(__seri_conf)<0)
        printf("serial_init_stopbit error\n");
    //struct termios opt;
    tcgetattr(__seri_conf->fd,&__seri_conf->options);
    __seri_conf->options.c_iflag &=~(BRKINT|ICRNL|INPCK|ISTRIP|IXON);
    __seri_conf->options.c_lflag &=~(ICANON|ECHO|ECHOE|ECHONL|ISIG|IEXTEN);
    __seri_conf->options.c_oflag &=~(OPOST);
    if(tcsetattr(__seri_conf->fd,TCSANOW,&__seri_conf->options)!=0)
        printf("error");
    while (1) {
        char ct[10] = "hello";
        write(__seri_conf->fd, ct, 10);
        puts("hello world 28800 test 8888!\n");
        sleep(1);
        nread = read(__seri_conf->fd,buff,256);
        if(nread>0)
        {
            printf("recv :%d ***%s\r\n",nread,buff);           
        }
    }
    close(fd);
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Linux系统下串口编程指的是在Linux操作系统中使用程序来控制串口设备,通常可以用于与串口设备进行通信。 要在Linux系统中进行串口编程,需要使用特定的API(应用程序编程接口)。常用的API包括POSIX的termios库和Linux专有的serial API。 使用termios库的步骤如下: 1. 使用open函数打开串口设备文件,例如"/dev/ttyS0"。 2. 使用tcgetattr函数获取串口的属性。 3. 使用修改串口属性的函数(如cfsetispeed和cfsetospeed)设置串口的输入/输出波特率。 4. 使用tcsetattr函数将修改后的属性设置回串口。 5. 使用read和write函数进行串口的数据读写。 6. 使用close函数关闭串口。 使用serial API的步骤如下: 1. 使用open函数打开串口设备文件,例如"/dev/ttyS0"。 2. 使用ioctl函数设置串口的属性,包括波特率、数据位、停止位和校验方式等。 3. 使用read和write函数进行串口的数据读写。 4. 使用close函数关闭串口。 在编写串口程序时,还需要注意其他问题,如确保串口设备文件有足够的权限访问、处理串口通信中 ### 回答2: Linux下串口编程是通过使用系统调用函数来实现的。在Linux系统中,串口设备可以被看作是一种特殊的文件,通过打开和操作该文件,我们可以进行串口通信操作。 在Linux中,常用的串口编程函数是open、close、read、write和ioctl等。我们首先需要使用open函数来打开串口设备文件,例如/dev/ttyS0。打开成功后,我们可以使用read函数从串口读取数据,使用write函数向串口写入数据,使用close函数关闭串口设备。 除了基本的读写操作,我们还可以使用ioctl函数来设置和获取串口的属性。通过设置串口的波特率、数据位、校验位、停止位等参数,我们可以实现不同的串口通信需求。一般情况下,我们需要使用termios结构体来保存和配置串口属性,然后通过ioctl函数来设置。 另外,Linux下还提供了一种轮询和一种中断的方式来进行串口通信。轮询方式是通过不断地查询串口是否有数据到达,然后进行读取。中断方式是通过设置串口的中断响应函数,当有数据到达时,会触发中断并执行相应的处理函数。 总之,Linux下串口编程是一种通过打开、读写和ioctl等系统调用函数来操作串口设备文件的方法。通过设置串口属性,我们可以实现不同的串口通信需求。 ### 回答3: Linux下的串口编程是指在Linux操作系统下对串行端口(串口)进行数据输入输出的一种编程技术。串口编程通常用于连接外部设备与计算机之间进行数据交互。 在Linux下,串口设备被视作特殊的文件,通过打开和读写这些特殊文件来对串口进行操作。常用的串口编程接口有标准C库的系统调用,如open()、read()、write()等,也可以使用Linux提供的串口库函数,如termios库函数。 串口编程的基本流程如下: 1. 打开串口设备文件,使用open()函数,得到串口文件描述符。 2. 配置串口参数,使用termios库函数,设置波特率、数据位、停止位、奇偶校验等参数。 3. 读取或写入串口数据,使用read()或write()函数进行数据交互。 4. 关闭串口设备,使用close()函数关闭串口文件描述符。 在进行串口编程时,需要注意以下几点: - 波特率、数据位、停止位、奇偶校验等参数需要与外设保持一致。 - 需要使用合适的访问权限打开串口设备文件。 - 需要适当处理读写时可能发生的错误和异常。 - 可以使用非阻塞模式进行读写,以提高程序的响应性。 通过Linux下的串口编程,可以实现与各种外设的通信,如传感器、控制器、无线模块等。它被广泛应用于嵌入式系统、物联网设备、机器人等领域,具有较高的灵活性和扩展性。同时,针对不同需求,还可以使用一些开源的串口通信库,如pyserial、libserial等,简化串口编程的过程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值