赞
踩
最近由于项目需要, 研究了关于在ubuntu下串口通信的功能实现。期间遇到一些问题,跟大家分享下。
1. 代码
comm_service.h
-
- #ifndef comm_service_h
- #define comm_service_h
-
- //串口相关的头文件
- #include <stdio.h> /*标准输入输出定义*/
- #include <stdlib.h> /*标准函数库定义*/
- #include <unistd.h> /*Unix 标准函数定义*/
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/ioctl.h>
- #include <linux/serial.h>
- #include <fcntl.h> /*文件控制定义*/
- #include <termios.h> /*PPSIX 终端控制定义*/
- #include <errno.h> /*错误号定义*/
- #include <string.h>
- //宏定义
- #define FALSE -1
- #define TRUE 0
-
- namespace dst_ccms_api
- {
- class comm_service
- {
- public:
- comm_service();
- ~comm_service();
-
- /*******************************************************************
- *名称: CommOpen
- *功能: 打开串口并返回串口设备文件描述
- *param: port 串口号(ttyS0,ttyS1,ttyS2)
- *return: void
- *******************************************************************/
- int CommOpen(char *port);
-
- /*******************************************************************
- *名称: CommClose
- *功能: 关闭串口并返回串口设备文件描述
- *param: fd 文件描述符
- *return: void
- *******************************************************************/
- void CommClose();
-
- /*******************************************************************
- *名称: CommInit
- *功能: 串口初始化
- *param: fd 串口文件描述符
- * speed 串口速度
- * flow_ctrl 数据流控制 (0:不使用 1:硬件流控制 2:软件流控制)
- * databits 数据位 取值为 7 或者8
- * stopbits 停止位 取值为 1 或者2
- * parity 效验类型 取值为N(无校验位),E(偶检验),O(奇校验)
- *return: 正确返回为1,错误返回为-1
- *******************************************************************/
- int CommInit(int baudrate, int flow_ctrl, int databits, int stopbits, int parity);
-
- /*******************************************************************
- *名称: CommRecv
- *功能: 接收串口数据
- *param: rcv_buf 接收串口中数据存入rcv_buf缓冲区中
- * data_len 一帧数据的长度
- *return: 正确返回为1,错误返回为-1
- *******************************************************************/
- int CommRecv(char *rcv_buf, int data_len);
-
- /*******************************************************************
- *名称: CommSend
- *功能: 发送数据
- *param: send_buf 存放串口发送数据
- * data_len 一帧数据的长度
- *return: 正确返回为1,错误返回为-1
- *******************************************************************/
- int CommSend(char *send_buf, int data_len);
-
- /*******************************************************************
- *名称: getCommFD
- *功能: 获取文件描述
- *return: 文件描述句柄
- *******************************************************************/
- int CommGetFD() const;
-
- /*******************************************************************
- *名称: serialFlush
- *功能: 清除缓冲区 TCIOFLUSH(刷清输入、输出队列) TCIFLUSH(刷清输入队列) TCIFLUSH (刷清输出队列)
- *return: true:开启 flase:关闭
- *******************************************************************/
- void CommFlush(int flush);
-
- private:
- /*******************************************************************
- *名称: commSet
- *功能: 设置串口数据位,停止位和效验位
- *param: fd 串口文件描述符
- * baudrate 波特率
- * flow_ctrl 数据流控制
- * databits 数据位 取值为 7 或者8
- * stopbits 停止位 取值为 1 或者2
- * parity 效验类型 取值为N,E,O,,S
- *return: void
- *******************************************************************/
- int commSet(int baudrate, int flow_ctrl, int databits, int stopbits, int parity);
-
- /*******************************************************************
- *名称: commIsOpen
- *功能: 串口是否开启
- *return: true:开启 flase:关闭
- *******************************************************************/
- bool commIsOpen() const;
-
- /*******************************************************************
- *名称: serial_set_speci_baud
- *功能: 非特定波特率设置
- *param: options 配置
- baud 非标准波特率(如28800..)
- *return: 正确返回为0,错误返回为-1
- *******************************************************************/
- int serial_set_speci_baud(struct termios &options,int baud);
-
- int m_fd; // 文件描述句柄
- };
- } // namespace qh_dst_ccms_api
- #endif

comm_service.cpp
-
- #include "comm_service.h"
- #include "common_logger.h"
-
- using namespace dst_ccms_api;
- using namespace J_COMMON_UTIL;
-
- comm_service::comm_service() : m_fd(-1) {}
- comm_service::~comm_service() {}
-
- int comm_service::CommOpen(char *port)
- {
-
- if (commIsOpen())
- return 1;
-
- m_fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
- if (m_fd < 0)
- {
- LError("Can't Open Serial Port.");
- return -1;
- }
- //恢复串口为阻塞状态
- if (fcntl(m_fd, F_SETFL, 0) < 0)
- {
- LError("fcntl failed.");
- return -1;
- }
- //测试是否为终端设备
- if (0 == isatty(STDIN_FILENO))
- {
- LError("standard input is not a terminal device.");
- return -1;
- }
- return 1;
- }
-
- void comm_service::CommClose()
- {
- if (!commIsOpen())
- return;
- close(m_fd);
- }
-
- int comm_service::commSet(int baudrate, int flow_ctrl, int databits, int stopbits, int parity)
- {
- if (!commIsOpen())
- return -1;
-
- int i;
- int status;
- int speed_arr[] = {B115200, B19200, B9600, B4800, B2400, B1200, B300};
- int name_arr[] = {115200, 19200, 9600, 4800, 2400, 1200, 300};
-
- struct termios options;
-
- /* tcgetattr(fd,&options)得到与fd指向对象的相关参数,并将它们保存于options,该函数还可以测试配置是否正确,
- 该串口是否可用等。若调用成功,函数返回值为0,若调用失败,函数返回值为1. */
- if (tcgetattr(m_fd, &options) != 0)
- {
- LError("commSet tcgetattr error.");
- return (FALSE);
- }
- bool isStandard = false;
- //设置串口输入波特率和输出波特率
- for (i = 0; i < sizeof(speed_arr) / sizeof(int); i++)
- {
- if (baudrate == name_arr[i])
- {
- cfsetispeed(&options, speed_arr[i]);
- cfsetospeed(&options, speed_arr[i]);
- isStandard =true;
- break;
- }
- }
-
- if(!isStandard){
- // 非标准波特率
- int res = serial_set_speci_baud(options, baudrate);
- if (res != 0)
- {
- LError("commSet serial_set_speci_baud error.");
- return (FALSE);
- }
- }
-
- //修改控制模式,保证程序不会占用串口
- options.c_cflag |= CLOCAL;
- //修改控制模式,使得能够从串口中读取输入数据
- options.c_cflag |= CREAD;
-
- //设置数据流控制
- switch (flow_ctrl)
- {
- case 0: //不使用流控制
- options.c_cflag &= ~CRTSCTS;
- break;
- case 1: //使用硬件流控制
- options.c_cflag |= CRTSCTS;
- break;
- case 2: //使用软件流控制
- options.c_cflag |= IXON | IXOFF | IXANY;
- break;
- }
-
- //设置数据位,屏蔽其他标志位
- options.c_cflag &= ~CSIZE;
- switch (databits)
- {
- case 5:
- options.c_cflag |= CS5;
- break;
- case 6:
- options.c_cflag |= CS6;
- break;
- case 7:
- options.c_cflag |= CS7;
- break;
- case 8:
- options.c_cflag |= CS8;
- break;
- default:
- LError("Unsupported data size.");
- return (FALSE);
- }
-
- //设置校验位
- switch (parity)
- {
- case 'n':
- case 'N': //无奇偶校验位。
- options.c_cflag &= ~PARENB;
- options.c_iflag &= ~INPCK;
- //options.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
- break;
- case 'o':
- case 'O': //设置为奇校验
- options.c_cflag |= (PARODD | PARENB);
- options.c_iflag |= INPCK;
- break;
- case 'e':
- case 'E': //设置为偶校验
- options.c_cflag |= PARENB;
- options.c_cflag &= ~PARODD;
- options.c_iflag |= INPCK;
- break;
- case 's':
- case 'S': //设置为空格
- options.c_cflag &= ~PARENB;
- options.c_cflag &= ~CSTOPB;
- break;
- default:
- LError("Unsupported parity.");
- return (FALSE);
- }
-
- // 解决二进制传输时,数据遇到0x0d , 0x11,0x13 会被丢掉的问题 J. 1027
- options.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
-
- // 设置停止位
- switch (stopbits)
- {
- case 1:
- options.c_cflag &= ~CSTOPB;
- break;
- case 2:
- options.c_cflag |= CSTOPB;
- break;
- default:
- LError("Unsupported stop bits.");
- return (FALSE);
- }
-
- //修改输出模式,原始数据输出
- options.c_oflag &= ~OPOST;
-
- options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
- //options.c_lflag &= ~(ISIG | ICANON);
-
- //设置等待时间和最小接收字符
- options.c_cc[VTIME] = 1; /* 读取一个字符等待1*(1/10)s */
- options.c_cc[VMIN] = 1; /* 读取字符的最少个数为1 */
-
- //如果发生数据溢出,接收数据,但是不再读取 刷新收到的数据但是不读
- tcflush(m_fd, TCIFLUSH);
-
- //激活配置 (将修改后的termios数据设置到串口中)
- if (tcsetattr(m_fd, TCSANOW, &options) != 0)
- {
- LError("com set error!");
- return (FALSE);
- }
- return (TRUE);
- }
-
- int comm_service::CommInit(int speed, int flow_ctrl, int databits, int stopbits, int parity)
- {
- if (!commIsOpen())
- return -1;
- //设置串口数据帧格式
- return commSet(speed, flow_ctrl, databits, stopbits, parity) ;
- }
-
- int comm_service::CommRecv(char *rcv_buf, int data_len)
- {
- if (!commIsOpen())
- return -1;
-
- int len, fs_sel;
- fd_set fs_read;
-
- FD_ZERO(&fs_read);
- FD_SET(m_fd, &fs_read);
-
- struct timeval time;
- time.tv_sec = 10;
- time.tv_usec = 0;
- //使用select实现串口的多路通信
- fs_sel = select(m_fd + 1, &fs_read, NULL, NULL, &time);
- if (fs_sel)
- {
- len = read(m_fd, rcv_buf, data_len);
- return len;
- }
- else
- return FALSE;
- }
-
- int comm_service::CommSend(char *send_buf, int data_len)
- {
- if (!commIsOpen())
- return -1;
-
- CommFlush(TCIFLUSH);
- int len = 0;
- len = write(m_fd, send_buf, data_len);
- if (len == data_len)
- return len;
- else
- {
- tcflush(m_fd, TCOFLUSH);
- return FALSE;
- }
- }
-
- void comm_service::CommFlush(int flush)
- {
- if (!commIsOpen())
- return;
-
- tcflush(m_fd, flush);
- }
-
- int comm_service::CommGetFD() const
- {
- return m_fd;
- }
-
- bool comm_service::commIsOpen() const
- {
- return m_fd < 0 ? false : true;
- }
-
- int comm_service::serial_set_speci_baud(struct termios &options,int baud)
- {
- struct serial_struct ss,ss_set;
-
- cfsetispeed(&options,B38400);
- cfsetospeed(&options,B38400);
-
- if((ioctl(m_fd,TIOCGSERIAL,&ss))<0){
- LInfo("1.serial_set_speci_baud ioctl.");
- return -1;
- }
-
- ss.flags = ASYNC_SPD_CUST;
- ss.custom_divisor = ss.baud_base / baud;
-
- if((ioctl(m_fd,TIOCSSERIAL,&ss))<0){
- return -1;
- }
-
- ioctl(m_fd,TIOCGSERIAL,&ss_set);
-
- return 0;
- }

2. 代码注释写的挺详细,就不说代码了,下面说下遇到的几个问题
1. 非标准波特率的问题。参考: 转帖:linux串口编程中非标准波特率的实现 (amobbs.com 阿莫电子论坛 - 东莞阿莫电子网站)
通常,在linux下面,设置串口使用终端IO的相关函数设置,如tcsetattr等函数,linux内部有一个对常用波特率列表的索引,根据设置的波特率用底层驱动来设置异步通信芯片的寄存器
但是在一些特定应用中需要用到非标准的波特率,比如125000、28800等 。对于非标准的任意波特率需要用ioctl(fd, TIOCGSERIAL, p)和ioctl(fd, TIOCSSERIAL, p)的配合,ioctl的最后一个参数是struct serial_struct *类型,在linux/serial.h中定义。其中baud_base是基准晶振频率/16(对于SEP4020来说,baud_base=sysclk/16),你需要设的是custom_divisor这个值,最终的波特率计算公式为baud=baud_base/custom_divisor,所以要设置custom_divisor=baud_base/baud,。
具体过程为,先设置波特率设为38400(tcsetattr),然后用TIOCGSERIAL得到当前的设置,将flags设置ASYNC_SPD_CUST位,设置custom_divisor,最后用TIOCSSERIAL设置。
代码实现:
- int comm_service::serial_set_speci_baud(struct termios &options,int baud)
- {
- struct serial_struct ss,ss_set;
-
- cfsetispeed(&options,B38400);
- cfsetospeed(&options,B38400);
-
- if((ioctl(m_fd,TIOCGSERIAL,&ss))<0){
- LInfo("1.serial_set_speci_baud ioctl.");
- return -1;
- }
-
- ss.flags = ASYNC_SPD_CUST;
- ss.custom_divisor = ss.baud_base / baud;
-
- if((ioctl(m_fd,TIOCSSERIAL,&ss))<0){
- return -1;
- }
-
- ioctl(m_fd,TIOCGSERIAL,&ss_set);
-
- return 0;
- }

2. 在测试过程中,发现接受的字符中缺少内容,总是接受不全。
解决办法:参考 :解决方法:Linux串口接收字节0x11,0x0d,0x13丢失_Leung_ManWah的博客-CSDN博客
options.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON);
最后:
1. 以上内容均来自网上,有一些原文找不到了,就没附原文链接,如作者有意见,please 楼下留言,我会及时修改。
2. 有需要的小伙伴可以参考下,也许可以少绕一些弯路 。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。