I2C data corruption using AStar slave library

(Crosspost of https://github.com/pololu/pololu-rpi-slave-arduino-library/issues/5)

I have been unable to reliably read data from the pololu AStar 32U4 SV stacked on top of a RPi 3 B. Can anybody figure out what’s going on here? I have a minimal case, and have reproduced it on multiple boards. In my minimal case, I send a single int16_t, which I have arbitrarily set to 1029, inside a struct, like this:

AStar code:


#include <AStar32U4.h>
#include <PololuRPiSlave.h>

struct Data
{
  int16_t enc0; 
};

PololuRPiSlave<struct Data,5> slave;

void setup() {
  slave.init(20);
}

void loop(){
  slave.updateBuffer();
  slave.buffer.enc0 = 1029;
  slave.finalizeWrites();
}

Python code:

import smbus
import struct
import time

bus = smbus.SMBus(1)
i2c_address = 20

def read_unpack(data_address, size, format):
    bus.write_byte(i2c_address, data_address)
    time.sleep(0.01)
    byte_list = [bus.read_byte(i2c_address) for _ in range(size)]
    return struct.unpack(format, bytes(byte_list))

while True:
    try:
        print(read_unpack(0, 2, 'h')[0])
    except OSError:
        print('error')
    time.sleep(0.1)

Example result:

pi@raspberrypi:~/isee-code/rpi/isee-curses $ python3 i2c_err_mincase.py
1026
517
error
516
514
error
1284
517
error
1284
1029
error
516
error
1282
1029
1026
error
516
514
1029
1029
error
516
1026
1029
1029
error
1284
error
1282
1029
1026
517
1026
1026
1029
1029
1029
1029
1029

Fixed it. Just had to increase pi_delay_us in the instantiation of the slave, so

PololuRPiSlave<struct Data,5> slave;

becomes

PololuRPiSlave<struct Data,20> slave;

. As suggested in the comments inside PololuRPiSlave.h, 20 microseconds seems to work.

Hello.

I am glad you figured out the problem and fixed it; thanks for letting us know and sharing your solution.

- Amanda