I have a C / Python installation on my machine, I am testing with serial communication, and for some reason I never read more than 1 byte.
My setup: I have a Windows 7 machine running OpenSUSE in a virtual box. I have 2 USB-RS232 converters and an adapter between them (so this is a loop from one USB port to another).
On the Windows side, I was able to get them to communicate with each other through Python-to-Python and C-to-Python. When I use the Linux virtual machine, I can get data from C (Linux) to Python (Windows), but when I do it the other way around, I only get 1 byte. I think something is wrong with the way I open a file or read Linux C code, but I'm not sure what the problem is.
Python code (using PySerial):
>>> import serial >>> ser = serial.Serial(3) >>> ser Serial<id=0x2491780, open=True>(port='COM4', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False) >>> ser.read(5) 'Hello' >>> ser.write("hi you") 6L
Code C:
#include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> int open_port() { int fd; fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY); if(fd < 0) perror("open_port: Unable to open /dev/ttyUSB0 - "); else fcntl(fd, F_SETFL, 0); return fd; } int swrite(int fd, char * str) { int n; n = write(fd, str, strlen(str)); if (n<0) printf("write() of %d bytes failed\n", strlen(str)); return n; } int main() { int fd, databytes; char buf[100] = {0}; struct termios options; fd = open_port(); //Set the baud rate to 9600 to match tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); tcsetattr(fd, TCSANOW, &options); tcgetattr(fd, &options); databytes = swrite(fd, "Hello"); if(databytes > 0) printf("Wrote %d bytes\n", databytes); databytes = read(fd, buf, 100); if(databytes < 0) printf("Error! No bytes read\n"); else printf("We read %d bytes, message: %s\n", databytes, buf); close(fd); return 0; }
And I come back:
mike@linux-4puc :~> gcc serial_com.c mike@linux-4puc :~> ./a.out Wrote 5 bytes We read 1 bytes, message: h
So Linux-> Windows write works, python shows the correct string "Hello", but for some reason I only get one byte on the Windows-> Linux side.
Does anyone see something wrong?
EDIT:
Based on the feedback I received, I tried two code settings. It seems like I cannot guarantee that all the data will be there, so I tried:
1) sleep
if(databytes > 0) printf("Wrote %d bytes\n", databytes); sleep(15); // Hack one to get the data there in time, worked databytes = read(fd, buf, 100);
2) while loop
while(1){
It seems that the loop is not working, so that data that is not being read is failing ?? / EDIT