I've got this strange issue with reading from a serial port on Linux. About 50% of the time, I won't get any data back from the serial port when I'm reading from it, yet if I use GTKTerm I get data back 100% of the time. I've double-checked my settings, and the terminal settings that I'm using are the exact same that GTKTerm uses, so I'm mystified as to why this would occur. The only thing that I could think of is that the port is set in canonical mode, not raw mode, but I set it properly - the device that I'm reading from does not send back newlines with all of the commands. However, everything is working properly when the device sends back commands with a newline character.
Here's the code I'm using:
int fd = open(serial_port, O_RDWR );
if( fd < 0 ){
perror("open");
}
//Set the serial port settings
struct termios newio;
if( tcgetattr( fd, &newio ) < 0 )
perror("tcgetattr");
if( cfsetospeed( &newio, B9600 ) < 0 )
perror("cfsetospeed");
newio.c_cflag &= ~CSTOPB;
newio.c_cflag &= ~CSIZE;
newio.c_cflag |= CS8;
newio.c_cflag |= CREAD;
newio.c_iflag |= IGNPAR;
newio.c_iflag |= IGNBRK;
newio.c_iflag &= ~BRKINT;
newio.c_iflag &= ~ICRNL;
newio.c_iflag &= ~IXON;
newio.c_cflag |= CLOCAL;
newio.c_oflag = 0;
newio.c_lflag = 0;
newio.c_cc[VTIME] = 0;
newio.c_cc[VMIN] = 1;
if( tcsetattr( fd, TCSANOW, &newio ) < 0 )
perror("tcsetattr");
tcflush( fd, TCOFLUSH );
tcflush( fd, TCIFLUSH );
Reading code (in separate thread)
void* thr(void* ign){
char buffer[10];
while( 1 ){
int got = read(fd, buffer, 10);
buffer[got] = 0;
printf("got %s\n", buffer);
}
}