0

I'm reading information from a serial port using this code:

struct termios tio;
memset(&tio, 0, sizeof(tio));

// Open serial port in mode `8N1', non-blocking
tio.c_cflag = CS8 | CREAD | CLOCAL;
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 10;

int fd = open("/dev/ttyACM1", O_RDONLY);

cfsetospeed(&tio, B9600);
cfsetispeed(&tio, B9600);
tcsetattr(fd, TCSANOW, &tio);
unsigned char byte = '0';

// check for input from arduino
while (!quit)
{
    keyboardInput(quit);
    read(fd, &byte, 1);

    if ((byte == '1' || quit)
    {
        oldByteDoor = '1';
        break;
    }
}

where keyboardInput(quit) sets quit to true when the close button of the window is pressed.

If nothing is in the serial port it gets stuck at read(fd, &byte, 1) forever.

How can I prevent this?

Thanks

picklechips
  • 746
  • 2
  • 8
  • 28
  • Put the file descriptor in non-blocking mode. Use `poll()`, and you will also need to figure out how to simultaneously block until either the file descriptor is readable (as indicated by the poll() system call) or until "the close button of the window is pressed", whatever that means (in the 1400+ pages that define the current C++ standard there is no mention of anything called a "window"). – Sam Varshavchik Nov 05 '16 at 22:59
  • Solution: http://stackoverflow.com/q/5616092/3722896 – woockashek Nov 05 '16 at 23:01
  • @woockashhek perfect, that fixed the issue - much easier than I was expecting. Thanks! I'm very new to serial programming so I wasn't sure what I should be searching. – picklechips Nov 05 '16 at 23:05

0 Answers0