I want to make two Raspberry Pi send message to each other using ZigBee protocol. I have connected XBee S2C (ZigBee) module to Raspberry Pi using USB Explorer (CH430g). I had written a python script which will do the desired work,
import serial ser = serial.Serial('/dev/ttyUSB0', 9600) while True: incoming = ser.readline().strip() print ('%s' %incoming.decode()) string = input("") + '\n' ser.write(string.encode()) But I need a C program to do the same, I looked into libserial library for C and C++, found that it's buggy and never compiled for me.
I tried this thread it works pretty well, but at the receiver side I need to keep read(fd, &buffer, sizeof(buffer)); in a while loop to continuously open for listening unlike a C socket program where read() function will halt till it receives the data just like my python script will wait in line incoming = ser.readline().strip() till it receives some message.
Is there any solution for it without using while loop ?
Edit 1:
In aforementioned python code, while loop is used to receive multiple messages. The line incoming = ser.readline().strip() will catch the message, process it and waits for next message since its in a while loop.
In C if my code is something like this:
while(1){ str = read(); //some processing } it throws error since read is not halting till it gets the data, it's just returning read fail. Since the read data is NULL the post processing of the data will throw an error. To make it work I have introduce another while loop like this:
while(1){ while(1){ str = read(); if(str!=NULL) break; } //some processing } I want to eliminate this extra loop and make read() to wait for the message. PS: I'm opening serial device like this: uart0_filestream = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
read()in the mentioned thread is blocking, will put the process in sleep waiting for data, so yes, you can use it within a loop (careful with the&buffer, it is the bug, look at the answer too). May I ask why if the python script is working do you need it in C?read()in a while loop since the code is just a part of other vast project. So I'm asking how I can avoid while loop or any library available for C/C++. As I said, its a part of a project, which should be in C/C++ I cant use python script in that.select()to do some other stuff while waiting for data, but I don't see how you can get rid of a loop if you are expecting more data