串口操作代码
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFFER_SIZE 1024
#define HOST_PORT 1
int set_port(int fd, int baud_rate, int data_bits, char parity, int stop_bits)
{
struct termios newtio,oldtio;
if( tcgetattr(fd,&oldtio) != 0)
{
perror("Setup Serial 1");
return -1;
}
bzero(&newtio,sizeof(newtio));
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
/* set baud_speed*/
switch(baud_rate)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 19200:
cfsetispeed(&newtio,B19200);
cfsetospeed(&newtio,B19200);
break;
case 38400:
cfsetispeed(&newtio,B38400);
cfsetospeed(&newtio,B38400);
break;
default:
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
}
/* set data_bits upon 7 or 8*/
switch(data_bits)
{
case 7:
newtio.c_cflag |= CS7;
break;
default :
case 8:
newtio.c_cflag |= CS8;
break;
}
/**/
switch(parity)
{
default:
case 'N':
case 'n':
{
newtio.c_cflag &= ~PARENB;
newtio.c_iflag &= ~INPCK;
}
break;
case 'o':
case 'O':
{
newtio.c_cflag |= (PARODD | PARENB);
newtio.c_iflag |= INPCK;
}
break;
case 'e':
case 'E':
{
newtio.c_