当前位置: 技术问答>linux和unix
linux下rs485测试代码问题
来源: 互联网 发布时间:2017-05-27
本文导语: 测试代码贴上 #define GIO_RS485_CTRL 51 #define URAT0_RXD 19 #define URAT0_TXD 18 int set_com_config(int fd,int baud_rate,int data_bits,char parity,int stop_bits){ struct termios new_cfg,old_cfg; int speed; /*保存并测试现有的串口参数设置*/ if(t...
测试代码贴上
#define GIO_RS485_CTRL 51
#define URAT0_RXD 19
#define URAT0_TXD 18
int set_com_config(int fd,int baud_rate,int data_bits,char parity,int stop_bits){
struct termios new_cfg,old_cfg;
int speed;
/*保存并测试现有的串口参数设置*/
if(tcgetattr(fd,&old_cfg)!=0){
perror("tcgetattr");
return -1;
}
/*设置字符大小*/
new_cfg = old_cfg;
cfmakeraw(&new_cfg);
new_cfg.c_cflag &= ~CSIZE;
/**/
switch(baud_rate)
{
case 2400:
{
speed = B2400;
}
break;
case 4800:
{
speed = B4800;
}
break;
case 9600:
{
speed = B9600;
}
break;
case 19200:
{
speed = B19200;
}
break;
case 38400:
{
speed = B38400;
}
break;
case 115200:
{
speed = B115200;
}
break;
}
cfsetispeed(&new_cfg,speed);
cfsetospeed(&new_cfg,speed);
/*停止位*/
switch(data_bits)
{
case 7:
{
new_cfg.c_cflag |=CS7;
}
break;
default:
case 8:
{
new_cfg.c_cflag |=CS8;
}
break;
}
/*奇偶校验*/
switch(parity)
{
default:
case 'n':
case 'N':
{
new_cfg.c_cflag &=~PARENB;
new_cfg.c_iflag &=~INPCK;
}
break;
case 'o':
case 'O':
{
new_cfg.c_cflag |= (PARODD | PARENB);
new_cfg.c_iflag |= INPCK;
}
break;
case 'e':
case 'E':
{
new_cfg.c_cflag |= PARENB;
new_cfg.c_cflag &= ~PARODD;
new_cfg.c_iflag |= INPCK;
}
break;
case 's':
case 'S':
{
new_cfg.c_cflag &= ~PARENB;
new_cfg.c_cflag &= ~CSTOPB;
}
break;
}
/*设置停止位*/
switch(stop_bits)
{
default:
case 1:
{
new_cfg.c_cflag &= ~CSTOPB;
}
break;
case 2:
{
new_cfg.c_cflag |= CSTOPB;
}
}
new_cfg.c_cc[VTIME] = 0;
new_cfg.c_cc[VMIN] = 1;
/*处理未接受字符*/
tcflush(fd,TCIFLUSH);
/*激活新配置*/
if((tcsetattr(fd,TCSANOW,&new_cfg))!=0){
perror("tcsetattr");
return -1;
}
return 0;
}
int open_port(void){
fd =open("dev/tty0",O_RDWR|O_NOCTTY|O_NDELAY);
if(fcntl(fd,F_SETFL,0)