- 论坛徽章:
- 0
|
串口通信
1 串口接口分DB9和DB25两种。其中DB9的2为发送,3为接受,5为接地。
串口参数主要为:波特率,数据位,停止位,奇偶校验位,流控制协议位
2 重要数据结构
struct termios{
tcflag_t c_iflag; /* input flags*/
tcflag_t c_olag; /* output flags*/
tcflag_t c_cflag; /* control flags*/
tcflag_t c_lflag; /* local flags*/
cc_t c_cc[NCCS]; /* control characters*/
};
/*
c_cflag:
CREAD 启用接受
CSIZE 字符大小
CSTOPB 停止位:1--2位;0--1位
PARENB 奇偶校验位
PARODD 奇校验位
*/
3 串口通信流程
a Tcgetattr函数取属性(termios struct)
保存原串口属性,返回时可以恢复现场。
struct termios newtio,oldtio;
tcgetattr(fd,&oldtio);/*保存到fd当中*/
b 激活选项 CLOCAL--本地连接; CREAD--接受使能
newtio.c_cflag=CLOCAL|CREAD;
c 波特率设置i/o speed
cfsetispeed(&newtio,B115200); //输入波特率为115200
cfsetospeed(&newtio,B115200); //输出波特率为115200
d 数据位设置
newtio.c_cflag&=~CSIZE; //字符大小
newtio.c_cflag|=CS8;
e 奇偶校验位c_cflag.c_iflag
奇:newtio.c_cflag|=PARENB;
newtio.c_cflag|=PARODD;
偶:newtio.c_cflag|=(INPCK|ISTRIP);
newtio.c_cflag|=PARENB;
newtio.c_cflag|=~PARODD;
f 停止位设置
newtio.c_cflag&=~CSTOPB; //0:1位
//1:2位
g 最少字符,等待时间设置(都设置为0)
newtio.c_cc[VTIME]=0;
newtio.c_cc[vmin]=0;
h 处理应用对象
tcflush(fd,quenue);
i/o缓存处理:
TCIFLUSH //清理输入缓存队列
TCOFLUSH //清理输出缓存队列
TCIOFLUSH //清理输入输出缓存队列
i 激活配置
tcsetattr(fd,opt,termios*);
tcsetattr(fd,TCNOW,&newtio);
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/66913/showart_708052.html |
|