说明
随着嵌入式开发在物联网行业中站的比重日益增加,Linux 环境下的C++也不断变得更为大众化。习惯了Window平台开发的开发人员, 都被Visual Studio的强大宠坏了, 无论是什么样的开发需求, 总能有现成的轮子可以直接拿来用。就好比这里要介绍的串口通信, 在Windows开发中, 无论是C++, MFC,还是C#, 巨硬大大都给我们做好了封装。可是在Linux下就没那么简单了,虽然开源, 但是很多的开发都偏底层,连一个标准库级别的串口通信SDK都没有,很是无奈。作为开发人员, 要么自己花时间熟悉底层接口然后造轮子,要么去开源社区找一些别人造好的轮子。而实际上,C++的开发大多对项目的耦合性比较大,很多别人造的轮子也都是在作者自己开发项目的过程中慢慢积累的,那些公开的接口如果别人拿来直接用,并不见得会很友好。所以大部分情况下都是开发者自己根据系统级别的api来自己造轮子
当然大多数情况下使用现有的串口库会节省很多时间, 本篇文章仅仅时为了记录学习Linux 环境下串口编程的一些基础原理
如果要使用现有库的话, ros-kinetic-serial
库应该是一个不错的选择
串口通信流程
1. 使用串口名(Linux下面通常为/dev/tty*, windows下通常为COM*)打开串口
2. 给打开的串口设定参数, 如 波特率、数据位、停止位、校验位等等
3. 向串口发送数据
4. 从串口中接收数据
需要使用到的一些接口
// 头文件
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
// 串口打开关闭与读写
int open(const char *name, int flag)
int write(int fd, const void *data, size_t size)
int read(int fd, void *data, size_t size)
int close(int fd)
// 串口配置相关
struct termios;
tcgetattr(int fd, struct termios* tios)
cfsetispeed(struct termios*tios, int baudrate)
cfsetospeed(struct termios*tios, int baudrate)
int tcsetattr (int __fd, int __optional_actions, const struct termios *__termios_p)
示例
接口头文件
/**
* file: serialport.h
* created by oyoung on 2018/05
*/
#ifndef SERIALPORT_H
#define SERIALPORT_H
#include <string>
#include <vector>
struct termios;
class SerialPort
{
public:
enum BaudRate {
BR0 = 0000000,
BR50 = 0000001,
BR75 = 0000002,
BR110 = 0000003,
BR134 = 0000004,
BR150 = 0000005,
BR200 = 0000006,
BR300 = 0000007,
BR600 = 0000010,
BR1200 = 0000011,
BR1800 = 0000012,
BR2400 = 0000013,
BR4800 = 0000014,
BR9600 = 0000015,
BR19200 = 0000016,
BR38400 = 0000017,
BR57600 = 0010001,
BR115200 = 0010002,
BR230400 = 0010003,
BR460800 = 0010004,
BR500000 = 0010005,
BR576000 = 0010006,
BR921600 = 0010007,
BR1000000 = 0010010,
BR1152000 = 0010011,
BR1500000 = 0010012,
BR2000000 = 0010013,
BR2500000 = 0010014,
BR3000000 = 0010015,
BR3500000 = 0010016,
BR4000000 = 0010017
};
enum DataBits {
DataBits5,
DataBits6,
DataBits7,
DataBits8,
};
enum StopBits {
StopBits1,
StopBits2