最近在做串口编程,在linux下串口编程设置繁多,一个参数设置不对,收到的数据就会出错或者漏掉数据,现发一个多方测试正确的config。
int uart_config(int fd,int baude ,int databits,int stopbits,int parity)
{
struct termios opt;
if( tcgetattr(fd ,&opt) != 0)
{
perror("get attr failed!\n");
return -1;
}
switch(baude)
{
case 4800:
cfsetispeed(&opt,B4800);
cfsetospeed(&opt,B4800);
break;
case 9600:
cfsetispeed(&opt,B9600);
cfsetospeed(&opt,B9600);
break;
case 19200:
cfsetispeed(&opt,B19200);
cfsetospeed(&opt,B19200);
break;
case 38400:
cfsetispeed(&opt,B38400);
cfsetospeed(&opt,B38400);
break;
default:
fprintf(stderr,"Unknown baude!");
return -1;
}
opt.c_cflag &= ~CSIZE;
switch (databits)
{
case 5:
opt.c_cflag |= CS5;
break;
case 6:
opt.c_cflag |= CS6;
break;
case 7:
opt.c_cflag |= CS7;
break;
case 8:
opt.c_cflag |= CS8;
break;
default:
printf("Unsupported data size\n");
return -1;
}
switch(parity)
{
case 'n':
case 'N':
opt.c_cflag &= ~PARENB;
opt.c_iflag &= ~INPCK;
break;
case 'o':
case 'O':
opt.c_cflag |= (PARODD|PARENB);
opt.c_iflag |= INPCK;
break;
case 'e':
case 'E':
opt.c_cflag |= PARENB;
opt.c_cflag &= ~PARODD;
opt.c_iflag |= INPCK;
break;
default:
printf("Unsupported parity\n");
return -1;
}
switch(stopbits)
{
case 1:
opt.c_cflag &= ~CSTOPB;
break;
case 2:
opt.c_cflag |= CSTOPB;
break;
default:
printf("Unsupported stop bits\n");
return -1;
}
opt.c_iflag &= ~(IXON | IXOFF | IXANY | BRKINT | ICRNL | INPCK | ISTRIP);
opt.c_lflag &= ~(ICANON | ECHO | ECHOE | IEXTEN | ISIG);
opt.c_oflag &= ~OPOST;
opt.c_cc[VTIME] = 5;
opt.c_cc[VMIN] = 0;
tcflush(fd, TCIOFLUSH);
if (tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("set attr failed!\n");
return -1;
}
return 0;
}
大家有啥问题可以留言啊,一起探讨。
原文参考:
https://www.linuxidc.com/Linux/2014-11/109307.htm //这个config设置的很对。
https://blog.csdn.net/continue_862/article/details/79919028//这位仁兄的程序也做了参考,但是在我这测试没法正确接收数据。