3

I am trying to communicate between a pair of RPi's both with Ciseco XRF Radios on Slice of Pi's.

My end goal is for RPi1 to send a specific phrase to RPi2 which will pick it up, perform some actions(collecting data from some sensors) and send a response; I figured serialport.read/write is the best way to do this.

I'm working on the very basic stage of this which is simply RPi2 listening to the serial port and printing whatever it recieves. My code is as follows:

import serial
while True:
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
command = serialport.read()
print str(command)

I can run this fine and it picks things up that I type/paste into RPi1 but not reliably; for example if I paste 'hello world' into the terminal on RPi1 I get:

l
l
o

appearing at RPi2. If I add a time delay (time.sleep(3) for example) I get nothing. My guess is that it is only picking up data if it is sent at the same time as it is reading.

Is there some way to reliably read everything that comes out of the serial port? (Maybe RPi2 store the input somewhere and read everything since its last read or something.)

asked Dec 31, 2014 at 13:07

1 Answer 1

6

You should not re-create the object Serial at each iteration of the loop. I suppose that the line serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5) closes and re-opens the serial port, flushing all the buffers.

Try this :

import serial
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
while True: 
 command = serialport.read()
 print str(command)
answered Dec 31, 2014 at 13:55
2
  • That's great, thanks a lot, it's now reliably recieving all data. Is there some way to make it wait for a certain number of bits to arrive and display them all at once? I've been playing around with inWaiting but I'm not sure if that the right track or not. Commented Jan 3, 2015 at 10:38
  • The function read() takes an optional parameter allowing you to specify how much bytes you want to read (Here is the API documentation.). If you specify a number of bytes, it will wait until this number of bytes arrive or a maximum amount of time, which you can set with the property 'timeout'. By default, it seems it is set to None, so, it will wait for ever. Commented Jan 3, 2015 at 13:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.