linux 下串口编程简单实例
1 、 linux 中的串口设备文件存放于 /dev 目录下,其中串口一,串口二对应设备名依次为
“
/dev/ttyS0 ” 、
“
/dev/ttyS1 ” 。在 linux 下操作串口与操作文件相同。
2 、 在使用串口之前必须设置相关配置,包括:波特率、数据位、校验位、停止位等。串口设置由下面结
构体实现:
de>struct termios{
tcflag_t c_iflag; /*input flags*/
tcflag_t c_oflag; /*output flags*/
tcflag_t c_cflag; /*control flags*/
tcflag_t c_lflag; /*local flags*/
cc_t c_cc[NCCS]; /*control characters*/
};de>
该结构中 c_cflag 最为重要 , 可设置波特率 、 数据位 、 校验位 、 停止位 。 在设置波特率时需在数字前加上 ‘ B ’
,
如 B9600 、 B19200 。使用其需通过 “ 与 ” “ 或 ” 操作方式。
常用的串口控制函数:
Tcgetattr 取属性 (termios 结构 )
Tcsetattr 设置属性 (termios 结构 )
cfgetispeed 得到输入速度
Cfgetospeed 得到输出速度
Cfsetispeed 设置输入速度
Cfsetospeed 设置输出速度
tcflush 刷清未决输入和 / 或输出
3 、 串口的配置
(1) 保存原先串口配置使用 tcgetattr(fd,&oldtio) 函数:
struct termios newtio,oldtio;
tcgetattr(fd,&oldtio);
(2) 激活选项有 CLOCAL 和 CREAD, 用于本地连接和接收使能。
newtio.c_cflag
|
= CLOCAL
|
CREAD;
(3) 设置波特率,使用函数 cfsetispeed 、 cfsetospeed
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);