Finfa811
Finfa811

Reputation: 638

Serial Programming - Termios. Getting stuck when reading 0x00 byte from device

I'm using termios API to read from / write to a device configured in the serial interface. The code I'm using is the following:

// Open serial interface
const char *device = "/dev/ttyS0";
int fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1)
  printf( "failed to open port\n" );

fcntl(fd, F_SETFL, 0);

// Get current configuration of serial interface
struct termios config;
tcgetattr(fd, &config);

// Set configuration of device
...
...
//

// Apply configuration to descriptor
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &config);

// Send order to device
unsigned char order[2];
int res;
unsigned char m = 0x00;
unsigned char s = 0x00;

order[0] = 0xc1; // Byte 193
order[1] = m;

res = write(fd, &order[0], 2);
if (res != 2)
  return -1;

res = read(fd, &s, 1);
if ((res != 1) || (res == -1))
  return -1;

The serial port opens correctly and the device is also correctly configured. If I print the configuration (config) in gdb I get the following:

{c_iflag = 8240, c_oflag = 0, c_cflag = 3251, c_lflag = 0, c_cc = "\003\034\177\025\004\000\000\000\021\023\032\000\000\000\000\026\001\000\000\000\033[\000\000\000\000\000\000DCAB@P\000\000HY\000", reserved = {0, 0, 1552337580}, c_ispeed = 9600, c_ospeed = 9600}

Then I can use the write function to send orders to the device but I cannot use the read function. The code gets stuck after running the line res = read(fd, &s, 1); and I get no response (see below). Any hint?

enter image description here

EDIT:

The // Set configuration of device block is as follows:

cfsetispeed(&config, B9600);
cfsetospeed(&config, B9600);

config.c_cflag &= ~CSIZE;
config.c_cflag |= CS8;    

config.c_cflag &= ~CSTOPB;
config.c_cflag |= 0;

config.c_cflag &= ~PARENB;
config.c_cflag &= ~PARODD;
config.c_cflag |= (0 | 0);

config.c_cflag |= (CLOCAL | CREAD);
config.c_iflag |= (INPCK | ISTRIP);

config.c_oflag = 0;
config.c_lflag = 0;

config.c_cc[VMIN]=1;
config.c_cc[VTIME]=0;

Upvotes: 0

Views: 665

Answers (1)

ccxxshow
ccxxshow

Reputation: 914

Although O_NONBLOCK was added at the time of open, fcntl(fd, F_SETFL, 0) was called below, equivalent to blocking mode.

fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
fcntl(fd, F_SETFL, 0);   // The O_NONBLOCK flag is overwritten

If there is no data on the serial port, it will be blocked.

Upvotes: 1

Related Questions