static int uart_set(int baude,int c_flow,int bits,char parity,int stop)
{
struct termios options;
if(tcgetattr(fd,&options) < 0)
{
perror("tcgetattr error");
return -1;
}
switch(baude)
{
case 4800:
cfsetispeed(&options,B4800);
cfsetospeed(&options,B4800);
break;
case 9600:
cfsetispeed(&options,B9600);
cfsetospeed(&options,B9600);
break;
case 19200:
cfsetispeed(&options,B19200);
cfsetospeed(&options,B19200);
break;
case 115200:
cfsetispeed(&options,B115200);
cfsetospeed(&options,B115200);
break;
case 38400:
cfsetispeed(&options,B38400);
cfsetospeed(&options,B38400);
break;
default:
fprintf(stderr,"Unkown baude!\n");
return -1;
}
options.c_cflag |= CLOCAL;
options.c_cflag |= CREAD;
switch(c_flow)
{
case 0://不进行流控制
options.c_cflag &= ~CRTSCTS;
break;
case 1://进行硬件流控制
options.c_cflag |= CRTSCTS;
break;
case 2://进行软件流控制
options.c_cflag |= IXON|IXOFF|IXANY;
break;
default:
fprintf(stderr,"Unkown c_flow!\n");
return -1;
}
switch(bits)
{
case 5:
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS5;
break;
case 6:
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS6;
break;
case 7:
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unkown bits!\n");
return -1;
}
switch(parity)
{
case 'n':
case 'N':
options.c_cflag &= ~PARENB;
options.c_cflag &= ~INPCK;
break;
case 's':
case 'S':
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
case 'o':
case 'O':
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag |= INPCK;
options.c_cflag |= ISTRIP;
break;
case 'e':
case 'E':
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_cflag |= INPCK;
options.c_cflag |= ISTRIP;
break;
default:
fprintf(stderr,"Unkown parity!\n");
return -1;
}
switch(stop)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unkown stop!\n");
return -1;
}
options.c_oflag &= ~OPOST;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 1;
tcflush(fd,TCIFLUSH);
if(tcsetattr(fd,TCSANOW,&options) < 0)
{
perror("tcsetattr failed");
return -1;
}
return 0;
}