1

I would like to send one string over the serial port; it works in a loop but not when I send only one string:

I have two Raspberry Pi 2. Each one have a xbee module. I want to send data from one to the other. They are correctly connected.

To test sending data I have this little Python script:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=.5)

while True:
    ser.write('Hello world!\r\n')

My other Raspberry Pi connected with minicom receives correct data:

Hello world!
Hello world!
Hello world!
...

Everything works, but I want to send only one string and remove the loop, however with this code:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=.5)

ser.write('Hello world!\r\n')

I received nothing... I don't know why. Does anyone know what's wrong?

1
  • I'd first try instantiating an integer to 0 outside your while loop, then incrementing and printing it alongside your 'Hello world' message on each successive pass. That should allow you to check that every single message is successfully sent and received, and rule out the possibility that the message has just gotten lost somewhere.
    – goobering
    Commented Feb 16, 2016 at 10:47

1 Answer 1

1

Radio isn't reliable. It can and will get lost if you only send it once. I recommend sending it multiple times and implement a debouncing logic on the receiving side.

Sending sample code:

for x in range(0, 10):
    ser.write('Sending ten times! \r\n')

Receiving sample code:

data_fresh = ser.readline()
data_old = " "

if data_fresh != data_old:
   data_old = data_fresh

   [the rest of your code]

else:
   [ignore or do something if cache data is equal to received data]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.