Search code examples
pythonraspberry-piradio-transmission

Serial data transmission input-output delay with Raspberry Pi


The Goal:

  • Drive several servo/RC motors wireless from one pi to another pi.
  • In essence, I want to build a RC remote control using a pi, with a second pion the receiver end.

Now I have a serial transmission over a RF link module that is stable and has very few corrupt entries. The serial transmission has a max baud rate of 4800 due to the RF link module.

Problem:

It seems there is a 2-4 seconds difference between the transmitter pi printing values and the receiver pi printing values. I cannot figure out where and why this delay comes from and why is it so large. Please note that the signal on the receiving pi is exactly the same data that is sent by the transmitter pi, but 2-4 seconds later. EVEN when I bypassed the the transmitter/receiver module and connected the Tx and Rx pins with a jumper wire the same delay was seen.

What is causing the data on the receiving Pi to be decoded so much later? I have pasted in the code below.

---------- Tx Pi -----------------

import serial
import struct

ser = serial.Serial("/dev/ttyAMA0")
ser.baudrate = 4800

iCount = 0
bProgramLoop = True
while (bProgramLoop == True):

    iOne = iCount
    if (iOne == 100):
        iOne = 0
        iTwo += 1
        iCount = 0
    if (iTwo == 100):
        iTwo = 0
        iThree += 1
    if (iThree == 100):
        iThree = 0
        iFour += 1
    if (iFour == 100):
        iFour = 0
        iFive += 1
    if (iFive == 100):
        iFive = 0

    lData = [iOne,iTwo,iThree,iFour,iFive] # i have done it like this so that I can track in real time where the transmitter is and receiver is with respect to real time changes on the transmitter side
    sData = struct.pack('5B',*lData)
    ser.write(sData)
    print sData

    iCount += 1

-------------- Rx Pi -----------------

import serial
import struct

ser = serial.Serial("/dev/ttyAMA0")
ser.baudrate = 4800

bProgramLoop = True
while (bProgramLoop == True):
    sSerialRead = ser.read(5)
    tData = struct.unpack('5B',sSerialRead)
    print tData

The time difference between when the Tx Pi prints the string sData and the Rx Pi prints the touple tData is somewhere between 2-4 seconds. Is the struct.unpack function slow?

I need this time difference to be absolutely minimal. Any ideas?


Solution

  • First, I'm not sure the ser.write() is an async call. If this is using the pySerial library, the docs say that it is a blocking call.

    Perhaps try:

    ...
    ser.write(sData)
    ser.flush()    # Force the 'send'
    print sData
    ...
    

    Also, your ldata might be easier to populate like so:

    lData = [iCount % 100, iCount % 10000, ...etc]
    

    Also, setting a write timeout might help (but I don't think so).