Serial port reading fails

I have the following C program:

#include <fcntl.h> #include <termios.h> #include <stdio.h> int main() { int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK); if(fd < 0) { perror("Could not open device"); } printf("Device opened\n"); struct termios options; tcgetattr(fd, &options); cfmakeraw(&options); cfsetispeed(&options, B19200); cfsetospeed(&options, B19200); tcsetattr(fd, TCSANOW, &options); char txpacket[] = {0x23, 0x06, 0x00, 0x00, 0xdd, 0xf9}; ssize_t written = write(fd, txpacket, sizeof(txpacket)); printf("Written %d bytes\n", written); printf("Starting to wait for target to respond\n"); while(1) { fd_set readset; FD_ZERO(&readset); FD_SET(fd, &readset); int nCount = select(fd + 1, &readset, NULL, NULL, NULL); if(nCount > 0) { if(FD_ISSET(fd, &readset)) { int i; char buffer[128]; ssize_t bytesread = read(fd, buffer, sizeof(buffer)); printf("Received %d bytes\n", bytesread); for(i = 0; i < bytesread; i++) { printf(" %02x", buffer[i]); } } } } } 

This program opens the serial device / dev / ttyS 0, writes a sequence of data to it and starts listening to the response. I get the following output:

 Device opened Written 6 bytes Starting to wait for target to respond Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes Received 0 bytes ... 

And the application consumes 100% processor. I cannot get any data, even if the target equipment does transmit it.

What's wrong?

+6
linux serial-port
source share
2 answers

read() return 0 indicates the state of the end of the file. You should check this out of the loop if that happens.

As for what leads to - the end of the file on the serial port indicates that it has detected a hang, which means that the DCD line has been deleted.

You can set the CLOCAL flag in options.c_cflag to ignore modem control lines if your device does not install them correctly.

+7
source share

You should try without the O_NONBLOCK flag. in raw mode, if the settings c_cc[VMIN] and c_cc[VTIME] are 0, the serial port behaves like this (according to man cfmakeraw):

If data is available, reading is returned immediately, with fewer bytes available or the number of bytes requested. If no data is available, reading is returned 0

So what you should try:

 options->c_cc[VMIN]=1; 
+1
source share

All Articles