#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h> int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
struct termios newtio,oldtio;
if ( tcgetattr( fd,&oldtio) != )
{
perror("SetupSerial 1");
return -;
}
bzero( &newtio, sizeof( newtio ) );
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE; switch( nBits )
{
case :
newtio.c_cflag |= CS7;
break;
case :
newtio.c_cflag |= CS8;
break;
} switch( nEvent )
{
case 'O': //奇校验
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E': //偶校验
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N': //无校验
newtio.c_cflag &= ~PARENB;
break;
} switch( nSpeed )
{
case :
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case :
cfsetispeed(&newtio, B4800);
cfsetospeed(&newtio, B4800);
break;
case :
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case :
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}
if( nStop == )
{
newtio.c_cflag &= ~CSTOPB;
}
else if ( nStop == )
{
newtio.c_cflag |= CSTOPB;
}
newtio.c_cc[VTIME] = ;
newtio.c_cc[VMIN] = ;
tcflush(fd,TCIFLUSH);
if((tcsetattr(fd,TCSANOW,&newtio))!=)
{
perror("com set error");
return -;
}
printf("set done!\n");
return ;
} int open_port(int fd,int comport)
{
char *dev[]={"/dev/ttySAC0","/dev/ttySAC1","/dev/ttySAC3","/dev/ttySAC4"};
long vdisable;
if (comport==)
{
fd = open( dev[comport - ], O_RDWR|O_NOCTTY|O_NDELAY);
if (- == fd)
{
perror("Can't Open Serial Port");
return(-);
}
else
{
printf("%s .....\n", dev[comport - ]);
}
}
else if(comport==)
{ fd = open( dev[comport - ], O_RDWR|O_NOCTTY|O_NDELAY);
if (- == fd)
{
perror("Can't Open Serial Port");
return(-);
}
else
{
printf("%s .....\n", dev[comport - ]);
}
}
else if (comport==)
{
fd = open( dev[comport - ], O_RDWR|O_NOCTTY|O_NDELAY);
if (- == fd)
{
perror("Can't Open Serial Port");
return(-);
}
else
{
printf("%s .....\n", dev[comport - ]);
}
}
if(fcntl(fd, F_SETFL, )<)
{
printf("fcntl failed!\n");
}
else
{
printf("fcntl=%d\n",fcntl(fd, F_SETFL,));
}
if(isatty(STDIN_FILENO)==)
{
printf("standard input is not a terminal device\n");
}
else
{
printf("isatty success!\n");
}
printf("fd-open=%d\n",fd);
return fd;
} int main(void)
{
int fd;
int nread,i;
char buff[]="Hello\n"; if((fd=open_port(fd,))<)
{
perror("open_port error");
return;
}
if((i=set_opt(fd,,,'N',))<)
{
perror("set_opt error");
return;
}
printf("fd=%d\n",fd);
while(){
errno = ;
nread=read(fd,buff,);
if( < nread){
printf("nread=%d,%s\n",nread,buff);
}
}
close(fd);
return;
}