Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program hangs when closing serial port connection

I am reading data through a USB connection as a serial port with the PL2303 driver. It returns successfully when doing an open and when I set they TTY options and non blocking. When I try to close the connection, it hangs. In this state it reads "�" instead of characters.

I can connect to the device perfectly fine with cutecom. Here is the strange part:

  1. If I first connect to the device via cutecom (a serial monitor), my program will connect and close perfectly fine every time afterwards. It reads the characters as I expect them to be read. (No �).
  2. If I disconnect and reconnect the hardware, my program will hang again until I run cutecom.

Since it works after I use cutecom, it makes me think that I am missing something in my initial connection, or connection settings. Here's what I use to connect:

baud_rate = 38400;
fd =  open (device_path, O_RDONLY | O_NOCTTY );

In my set_tty_options function:

struct termios tty_options;

memset (&tty_options, 0, sizeof(tty_options));
tcgetattr (fd, &tty_options);

cfsetispeed(&tty_options, baud_rate);                         // set baud rate
tty_options.c_cflag = (tty_options.c_cflag & ~CSIZE) | CS8;   // 8 bit msgs
tty_options.c_cflag |= (CLOCAL | CREAD);                      // enable reading

tty_options.c_cflag &= ~(PARENB | PARODD);                    // shut off parity
tty_options.c_cflag |= parity;
tty_options.c_cflag &= ~CSTOPB;
tty_options.c_cflag &= ~CRTSCTS;

if (tcsetattr (fd, TCSANOW, &tty_options) != 0) 
{
  printf("error %d from tcsetattr\n", errno);
  return TTY_ERROR;
}

In set_blocking function:

if (tcgetattr (fd, &tty) != 0)
{
  printf("error %d from tggetattr", errno);
  return FAILURE;
}

// 0 or 1 byte is enough to return from read
tty.c_cc[VMIN]  = should_block ? 1 : 0; 
tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

if (tcsetattr (fd, TCSANOW, &tty) != 0) 
{
  printf("error %d setting term attributes", errno);
  return FAILURE;
}
like image 711
Nate Avatar asked Nov 12 '22 08:11

Nate


1 Answers

I think you want to add | O_SYNC to the open flags to insist on synchronous i/o. I doubt that is causing a problem though.

However, I think you want to ignore the break signal, which is reported as a NUL character like you are getting:

tty_settings.c_iflag &= ~IGNBRK;         // ignore break signal

Also, you want to be sure the input processing is completely turned off, so that receipt of a backspace, ^C, ^\, etc. aren't triggering any reaction:

tty_settings.c_lflag = 0;                // no signaling chars, no echo,
                                         // no canonical processing

It looks like you are already using my set_blocking() function, so that should be okay.

like image 101
wallyk Avatar answered Nov 15 '22 06:11

wallyk