I am getting successful reads of a fd in Linux, but with 0 bytes read which means EOF has been reached. I should be reading 19 bytes in every read.
The project is a motor driver that sends out packets of 19 bytes to drive 2 DC motors, and it also needs to read the same size packet coming from the motor with updated position, command, and status info.
I open the fd like this:
mc_fd = InitPort("/dev/ttyS1", "COM2", O_NONBLOCK | O_RDWR | O_SYNC, B115200);
Here is the function to initialize the port:
int InitPort( char *port, char *name, int oflags, speed_t baudRate ) {
int fd; // File descriptor
fd = open(port, oflags); // Open the port like a file
assert(fd > 0); // Open returns -1 on error
struct termios options; // Initialize a termios struct
tcgetattr(fd, &options); // Populate with current attributes
cfsetospeed (&options, baudRate); // Set baud rate out
cfsetispeed (&options, baudRate); // Set baud rate in (same as baud rate out)
options.c_cflag &= ~CSIZE; // Clear bit-length flag so it can be set
//8N1 Serial Mode
options.c_cflag |= CS8; // Set bit-length: 8
options.c_cflag &= ~PARENB; // Set parity: none
options.c_cflag &= ~CSTOPB; // Set stop bit: 1
options.c_cflag &= ~CRTSCTS; // Set flow control: none
options.c_iflag &= ~ICANON; // Enable canonical input
options.c_oflag &= ~OPOST; // Disables all output processing (prevents CR in output)
options.c_cflag |= (CLOCAL | CREAD);// Enable receiver, and set local mode
tcsetattr(fd, TCSANOW, &options); // Set new attributes to hardware
return fd;
}
Originally, I only used the O_RDWR flag and reads of the fd would fail with EAGAIN (or EWOULDBLOCK). I have been trying synchronization and non-blocking settings to see if I could receive packets. At least now I am reading successfully (I think).
I am able to write packets out at 120Hz, and reads of the fd return "success" at the same rate, although with 0 bytes read.
How do I get read() to read the incoming packets? Here is the read code along with the output from the terminal:
bytesRead = read( mc_fd, readPacket, MC_PACKET_SIZE );
printf("\npacket: %019X\n", &readPacket);
perror("error type ");
printf("bytes read = %d\n", bytesRead);
packet: 00000000000B63B4140
error type : Success
bytes read = 0
The 8-digit hex number in the least significant part of the packet is always similar to that shown, and is not what is expected in the packet.
This is Debian running on an embedded linux SBC (single board computer). I am able to read other file descriptors in the program with no problems. I am still fairly new to Linux and may be missing something obvious. Thanks!