在使用终端开发使用串口时,配置串口的方式尤为重要
1、要使用串口就先打开串口
int OpenUartPort(const char *UartPort)
{
int fd;
fd = open(UartPort,O_RDWR|O_NONBLOCK);
if(fd<0)
{
perror("open serial port");
return -1;
}
if(isatty(fd) == 0)
{
perror("this is not a terminal device");
return -1;
}
return fd;
}
isatty,函数名。主要功能是检查设备类型 , 判断文件描述词是否是为终端机。
2、使用串口就要配置串口
int SetUartConfig(int fd, int Baud)
{
struct termios new_cfg,old_cfg;
if(tcgetattr(fd,&old_cfg) !=0 )
{
perror("tcgetattr");
return -1;
}
new_cfg = old_cfg;
new_cfg.c_cc[VTIME] = 0;
new_cfg.c_cc[VMIN] = 0;//控制字符
new_cfg.c_iflag = 0;//输入模式标志
new_cfg.c_oflag = 0;//输出模式标志
new_cfg.c_lflag = 0;//本地模式标志
switch(Baud)
{
case 9600:new_cfg.c_cflag = B9600 | CS8 | CLOCAL | CREAD;break;//控制模式标志
case 19200:new_cfg.c_cflag = B19200 | CS8 | CLOCAL | CREAD;break;
case 115200:new_cfg.c_cflag = B115200 | CS8 | CLOCAL | CREAD;break;
}
tcflush(fd,TCIOFLUSH);
if(tcsetattr(fd,TCSANOW,&new_cfg) !=0)
{
perror("tcsettattr");
return -1;
}
return 0;
}
tcflush函数是
Unix终端I/O函数。作用:清空终端未完成的输入/输出请求及数据。
tcgetattr是一个函数,用来获取终端参数,成功返回零;失败返回非零,发生失败接口将设置
errno错误标识。
相关函数:tcsetattr用来设置终端参数。
3、从串口中读取数据
int ReadUartPort(int fd, int Num, u_int8_t *Buff)
{
int res = 0;
memset(Buff,0,Num);
res = read(fd,Buff,Num);
return res;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)