#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <signal.h> #include <termios.h> #define false 0 #define true 1
void sighandler ( int status ); int setup_com(int fd);
int wait_flag = false; /* set up the options for serial port */
int fd;
int setup_com(int fd) { struct termios options; tcgetattr(fd, &options); /* * Set the baud rates to 115200... */ cfsetispeed(&options, B57600); cfsetospeed(&options, B57600);
/* * Enable the receiver and set local mode... */
options.c_cflag |= (CLOCAL | CREAD);
/* * Set global options. */ options.c_cflag &= ~PARENB; options.c_cflag &= ~PARODD; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; /* set the input options */
options.c_iflag &=~(IXON | IXOFF | IXANY); options.c_iflag &=~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //options.c_lflag |= ISIG;
/* set the output options */ options.c_oflag=0;// &= ~OPOST;
/* set the timeout options */ options.c_cc[VMIN] = 0; options.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &options); return 1;
}
void sighandler ( int status ) { printf("receive data.
"); wait_flag = true; }
int main(int argc, char **argv) {
int nbytes,i; unsigned char *buffer; int ctrlbits;
struct sigaction action; fd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NDELAY ); if (fd == -1) { perror("open_port: Unable to open /dev/ttyS0 - "); return -1; } else {
action.sa_handler = sighandler; action.sa_flags = 0; sigaction(SIGIO, &action, NULL);
fcntl(fd, F_SETOWN, getpid()); fcntl(fd,F_SETFL,FASYNC); //fcntl(fd, F_SETFL, 0); setup_com(fd);
//receive enable ioctl(fd,TIOCMGET,&ctrlbits);
ctrlbits |= TIOCM_RTS;//set enable //ctrlbits &= ~TIOCM_RTS;//disable ioctl(fd,TIOCMSET,&ctrlbits);
while(1) { if (wait_flag == true ) { if((nbytes = read(fd, buffer, 5)) > 0) printf("nbytes =0x%x.
",nbytes); for(i=0;i<nbytes;i++) { printf("the receive data =0x%x.
",buffer); } printf("send data.
"); //send enable ioctl(fd,TIOCMGET,&ctrlbits); ctrlbits &= ~TIOCM_RTS;//send enable ioctl(fd,TIOCMSET,&ctrlbits); buffer[0]+=1; if((nbytes=write(fd, buffer, 1))>0); sleep(1); //receive enable ioctl(fd,TIOCMGET,&ctrlbits); ctrlbits |= TIOCM_RTS;//send enable ioctl(fd,TIOCMSET,&ctrlbits); wait_flag = false; } }
close(fd); }
return 0; } |