#include<errno.h> #include<windows.h> #include<termios.h> #include<unistd.h> #include<string.h> #include<stdio.h> #include<fcntl.h> #include<stdlib.h> int set_attributes (int fd, int speed, int parity) { struct termios tty; if (tcgetattr (fd, &tty) != 0) { perror("error\n"); return -1; } cfsetospeed (&tty, speed); cfsetispeed (&tty, speed); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; tty.c_iflag &= ~IGNBRK; tty.c_lflag = 0; tty.c_oflag = 0; tty.c_cc[VMIN] = 0; tty.c_cc[VTIME] = 5; tty.c_iflag &= ~(IXON | IXOFF | IXANY); tty.c_cflag |= (CLOCAL | CREAD); tty.c_cflag &= ~(PARENB | PARODD); tty.c_cflag |= parity; tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if (tcsetattr (fd, TCSANOW, &tty) != 0) { perror("error in setting attributes\n"); return -1; } return 0; } int set_blocking (int fd, int should_block) { struct termios tty; memset (&tty, 0, sizeof tty); if (tcgetattr (fd, &tty) != 0) { perror("error in setting attributes\n"); return -1; } tty.c_cc[VMIN] = should_block ? 1 : 0; tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout if (tcsetattr (fd, TCSANOW, &tty) != 0) perror("error in setting attributes\n"); } int main() { char *portname = "/dev/tty"; int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { perror("error\n"); return -1; } set_attributes (fd, B9600, 0); set_blocking (fd, 0); while (1){ char data[20]; char buf[100]; sleep(10); int n = read (fd, buf, sizeof buf); printf(" the character read from serial port is = %s",buf); printf("\n"); } close(fd); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)