adafruit / Adafruit_CircuitPython_VL53L0X

CircuitPython module for interacting with the VL53L0X distance sensor.
MIT License
38 stars 26 forks source link

reading range is an order of magnitude slower than expected #5

Closed rlake closed 6 years ago

rlake commented 6 years ago

I have a Trinket M0 with the module connected to gpio pins 0/2 and gpio pin 3 as a pwm output for an LED (through a transistor). Circuitpython bundle build is 3.x dated 20180809 with the 3.0.0 uf2 firmware.

For some reason with the default configuration the sensor is taking approximately 2 seconds to take a reading:

sensor distance 8191mm, time 2.08398 sensor distance 257mm, time 2.08203 sensor distance 190mm, time 2.08203 sensor distance 294mm, time 2.08179

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_vl53l0x.VL53L0X(i2c)
#sensor.measurement_timing_budget = 20000

while True:
    start = time.monotonic()
    distance = sensor.range
    print("sensor distance " + str(distance) + "mm, time " + str(time.monotonic() - start))

Dropping the timing budget to 20ms helps by roughly 300ms and in both modes there is the occasional fast read:

sensor distance 8191mm, time 1.76489 sensor distance 8190mm, time 0.0290527 sensor distance 8190mm, time 1.76611 sensor distance 149mm, time 1.76904 sensor distance 212mm, time 1.76587 sensor distance 296mm, time 1.76392 sensor distance 8190mm, time 1.76611

Any idea what would cause such a delay?

ladyada commented 6 years ago

yah - just tried it and you're right! but we're not sure exactly where the math error is. we adapted the code from pololu's non-API-based library... do you want to try the arduino version and see if that's also slow (thus bug in both) or if its correct (thus bug is in our port)? https://github.com/pololu/vl53l0x-arduino

rlake commented 6 years ago

Interesting! In Arduino mode both Pololu and Adafruit VL53L0X example sketches are very responsive.

ladyada commented 6 years ago

are you feeling up to investigating the circuitpython lib to see where it might be miscalculating?

rlake commented 6 years ago

You bet! I think I might have spotted the problem from comparing the code side by side. In the reference function VL53L0X::setMeasurementTimingBudget it calls timeoutMicrosecondsToMclks to set final_range_timeout_mclks. In the circuitpython function it calls _timeout_mclks_to_microseconds(so the reverse!). I'd bet that's the problem, just need to get back into circuitpython mode from sketch.

ladyada commented 6 years ago

amazing ! thanks- we're debugging some other libraries today but if you have a pull req we can test tonite!

rlake commented 6 years ago

Please see note in pull request. I hit some snags building/testing but hopefully that should do the trick.

ladyada commented 6 years ago

ok thanx i will test and report back