#include #include #include #include #include #include #include #include /* File control definitions */ #include /* Error number definitions */ #include /* POSIX terminal control definitions */ #include #include int fd, fser1, fser2; int baud, parity; int open_port(void) { int fd; // File Descriptor for serial port char s[60]="/dev/com4"; baud=19200; parity=0; printf("Checking communication port : %s\n",s); fd = open(s, O_RDWR | O_NOCTTY | O_NDELAY); if(fd == -1) { perror("-- Unable to open /dev/com --"); exit(1); } else { fcntl(fd, F_SETFL, 0); printf("...Done\n"); } return(fd); } void init_port(int fd) { struct termios configs; tcgetattr(fd, &configs); switch(baud) { case 9600: baud=B9600;break; case 19200: baud=B19200;break; case 38400: baud=B38400;break; default: baud=B19200; } cfsetispeed(&configs, baud); cfsetospeed(&configs, baud); // Setting Control Mode switch (parity) { case 1: // even parity configs.c_cflag |= PARENB; // Parity enable configs.c_cflag &= ~PARODD; // Even Parity break; case 2: // odd parity configs.c_cflag |= PARENB; // Parity enable configs.c_cflag |= PARODD; // Even Parity break; default : // no parity //configs.c_cflag |= PARENB; // Parity enable //configs.c_cflag &= ~PARODD; // Even Parity configs.c_cflag &= ~PARENB; // Parity disable } configs.c_cflag &= ~CSTOPB; // 1 stop bit //configs.c_cflag |= CSTOPB; // 2 stop bit configs.c_cflag &= ~CSIZE; configs.c_cflag |= CS8; // 8-bit data configs.c_cflag &= ~CRTSCTS; // Disable hardware flow control // Setting Local Mode configs.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //RAW input // Setting Input mode configs.c_iflag |= INPCK; // Enabling Parity Check configs.c_iflag &= ~ISTRIP; // Disable strip off 8th bit when received configs.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control // Setting Output Mode configs.c_oflag &= ~OPOST; // RAW output // Setting Control chars configs.c_cc[VTIME] = 0; // Timeout in 0.1s, 0 (no timeout) configs.c_cc[VMIN] = 0; tcflush(fd, TCIFLUSH); // clean line if (tcsetattr(fd, TCSANOW, &configs)!=0) { fprintf(stderr, "ERROR ! Unable to write configuration to hardware\n"); } } int main(int argc, char **argv) { FILE *fdata; int comm, count,n; unsigned char i; fd_set read_fd; struct timeval tv; tv.tv_sec=0; tv.tv_usec=100; unsigned char test[10]; //Open serial port fd = open_port(); //Initialize serial init_port(fd); int fd0, retval; struct timeval tv0, tv1; gettimeofday(&tv0, NULL); printf("start reading..\n"); while(1) { gettimeofday(&tv1, NULL); fcntl(fd, F_SETFL, FNDELAY); // set reading as non blocking n=read(fd, &test, 10); // return -1 in version 1.7.10 and up if (n>0) { printf("%d, ",(tv1.tv_sec-tv0.tv_sec)*1000+(tv1.tv_usec/1000-tv0.tv_usec/1000)); printf("read (%d bytes) : ", n); for (i=0;i