Pololu Robotics & Electronics
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

OPT3101-RPi wrong distance

Im using OPT3101 to measure distance with raspi.

I have tried translate the arduino code c++ to python, but i have som trouble with the distance. i get some random numbers.

Best regards
destest.py (5.7 KB)


Thank you for your interest in the OPT3101. I read part of your code and I saw some issues. Here are your functions for writing and reading registers:

def OPT3101_writeReg(adress, data):
    bus.write_byte_data(OPT3101, adress, np.int8(data >> 0))
    bus.write_byte_data(OPT3101, adress, np.int8(data >> 8))
    bus.write_byte_data(OPT3101, adress, np.int8(data >> 16))

def OPT3101_readReg(adress):
    regData = bus.read_byte_data(OPT3101, adress)
    regData |= np.uint16(bus.read_byte_data(OPT3101, adress) << 8)
    regData |= np.uint32(bus.read_byte_data(OPT3101, adress) << 16)
    return regData

I suspect that your OPT3101_writeReg function will result in three different I2C transfers, with each one writing one byte to the same address. Instead, I recommend making a single I2C transfers as shown in the “Programming” section of the OPT3101 datasheet. It looks like OPT3101_readReg has a similar issue.

I recommend testing your functions by writing some different 24-bit values to a register and reading them back to make sure they are correct. Register 0xB4 would work well for such a test, since all of its bits readable and writable.

I am not sure if the library you are using is flexible enough to do the kinds of I2C transfers that are needed. You might consider using the smbus2 library instead. Its i2c_rdwr method is very flexible and we have example code showing how to use it (for a different product) in the “Example I²C code for Linux in Python” section of the Pololu Tic User’s Guide.

Also, in resetAndWait, your code writes a value of 0 to register 0, but it should write a 1 instead.

Please let me know if you have any further questions. Once you get distance readings working, it would be nice if you can post your code somewhere for others to benefit from.