I am using termios
in C to write a simple program to write to a serial port and read the returned data. The communication with the device on the serial line terminates with a carriage return. The program is simple and currently looks like:
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <termios.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
struct termios s_alicat;
int tty_fd, count;
// Ports connected in USB as sudo
if ((tty_fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY)) < 0)
{
printf("Line failed to open with %d\n", tty_fd);
return -1;
}
else
{
printf("fd is %d\n", tty_fd);
}
s_alicat.c_cflag = B19200 | CS8 | CREAD | CLOCAL;
//No parity 8N1:
s_alicat.c_cflag &= ~PARENB;
s_alicat.c_cflag &= ~CSTOPB;
s_alicat.c_cflag &= ~CSIZE;
s_alicat.c_iflag = IGNPAR | ICRNL; // Ignore parity errors
//Disable hardware flow control
s_alicat.c_cflag &= ~CRTSCTS;
//Disable software flow control
s_alicat.c_iflag &= ~(IXON | IXOFF | IXANY);
//Raw output
s_alicat.c_oflag &= ~OPOST;
//Raw input
s_alicat.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcflush(tty_fd, TCIFLUSH);
tcsetattr(tty_fd, TCSANOW, &s_alicat);
unsigned char transmit[2] = "C\r";
if ((count = write(tty_fd, &transmit, 2)) < 0)
{
printf("Failed to write to device");
}
printf("Transmited %d characters\n", count);
usleep(500000);
unsigned char receive[255];
if ((count = read(tty_fd, &receive, 255) < 0))
{
printf("Error receiving text %d", count);
}
else
{
if (count == 0)
{
printf("No data read in...\n");
}
else
{
printf("%s", receive);
}
}
printf("Closting port...\n");
close(tty_fd);
return 0;
}
So:
- The port opens correctly
- I am able to write the data (can physically see that it is going across the line via LEDs that light up when data is transmitted and received)
- The read returns with 0 characters
If I send the same command (C\r
) through another program set up with 19.2, 8N1, no flow control, I get the following string ( or something very similar) back
C\s+012.05\s+031.73\s+000.01\s+000.01\s010.24\s\s\s\s\sAir\r
So, what am I doing wrong here? Does this have something to do with the fact that the IO is carriage return terminated? Or is my configuration incorrect?
EDIT: So, it appears that if I watch the character device (/dev/ttyUSB0
) I can actually see the data coming back - see snap shot below. So, it looks like my issue is in reading into and getting information from the read buffer.