1

I'm using an I2C device connected to an RPi. The device only handles receiving one byte (which is then transferred via radio to a similar device on the other end, that acknowledges the reception of the byte) or receiving one byte (same consideration, in inverse path).
It happens that when sending a sequence of bytes within a loop in a python script, they are sent faster than the device is able to process them, so I get a considerable amount of IOError exceptions when this happens.
Right now the only way I found to ensure that I send every byte is to catch the exception and retry after a while:

import time
import I2C
# connect with device on address 0x23, bus 1
d=I2C.Device(0x23,1)

# function to retry the sending a <byte> to device, at most <times> times
def retry(byte,times):
        s=0
        for i in range(1,times):
                try:
                        print ' {1}'.format(byte,i),
                        # try to send the byte
                        d.writeRaw8(byte)
                        s=1
                # if there is an IOError sending the byte, wait some time
                except IOError,e:
                        time.sleep(0.5*i)
                # if writeRaw8 worked (byte was sent), do not retry
                if s==1:
                        print 'Ok'
                        break;
        if s==0:
                print 'Ko'
        return s
# loop for sending 50 bytes
for i in range(0,50):
        print 'sending {0}'.format(i),
        retry(i,10)

This works, but I feel that this is not the most appropriate way to do this. However, I've not found a way to check if the slave device is ready to receive a new byte or not. Do you know about a way to do this?

4

Doesn't the device provide a method?

Some I2C devices will return 0xFF if you try to read then when they are not ready.

Alternatively record the time when you sent a message and don't send a new one until x milliseconds has elapsed (where x is determined by experiment).

  • Nope, this device (elecrow.com/…) just returns a particular byte value (0x71 if I don't remember wrong) whenever you ask it to get a value and it has no value to return. But when sending, you can just send the byte and hope it gets there (I understand Rosetta and Philae now...) – Roberto Nov 13 '14 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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