Coder Social home page Coder Social logo

mjbogusz / vl53l0x-linux Goto Github PK

View Code? Open in Web Editor NEW

This project forked from pololu/vl53l0x-arduino

23.0 6.0 14.0 114 KB

Library for interfacing with VL53L0X time-of-flight distance sensor under Linux

Home Page: https://www.pololu.com/product/2490

License: Other

C++ 99.42% CMake 0.58%
library linux sensor vl53l0x range time-of-flight i2c i2c-sensors

vl53l0x-linux's Introduction

VL53L0X library for Linux

Version: 0.2.0
Release date: 05.05.2018
Changelog: see git log

Summary

This is a library for GNU/Linux that helps to interface with ST's VL53L0X time-of-flight distance sensor. This library makes it simple to configure the sensor and read range data from it via I²C.

Additionally it provides support for managing multiple sensors connected to the same bus by managing their hardware standby state via their XSHUT pins, see multiple sensors section

It uses i2cdev library for I2C access and /sys/class/gpio/* files for GPIO.

Feedback, bugs, feature requests...

Pull requests and issue reports are welcome!

Table of Contents


Development status

  • WORKING
  • Wire.h replaced with i2cdev and /sys/class/gpio access
  • Multiple sensors support added
  • Hardware standby (XSHUT) management support added (part of multiple sensors support)
  • Single sensor: tested and working (examples/single)
  • Continuous measurement, multiple sensors: tested and working (examples/continuousMultipleSensors)
  • Code style consistency improved
  • Using std::exception for errors
  • Documentation moved to header (why would you want them with source?)
  • Other minor improvements

TODO:

  • Improve/add missing documentation
  • Update/modify/merge-in(?) I2Cdev to accept i2c device path as argument

Supported platforms

The library should work on all platforms supporting Linux I2Cdev access (/dev/i2c-* device files) and GPIO access via /sys/class/gpio/*.

It was tested on a BeagleBone Green Wireless with 5 sensors working on the same bus.

As per #6 it also works on BeagleBone Blue with Seeed Studio's Time of Flight Distance Sensor (yet another breakout board with Grove connector) However, using multiple sensors will require soldering additional connectors for the XSHUT pins (one of the two 2.54 pads by the Grove connector) and wiring them to the main BBU board, see Multiple sensors section for details.


Usage

Hardware

A VL53L0X carrier can be purchased e.g. from Pololu's website. Before continuing, careful reading of the product page as well as the VL53L0X datasheet is recommended.

Important notes on hardware:

  • XSHUT is connected via pull-up resistor to VIN, therefore the sensor can be powered from GPIO even if VIN is disconnected
  • Even putting the sensor to hardware standby (XSHUT low, VIN connected) will reset its address! (see Multiple sensors secton on why that's important)

Connections

Odroid C2

Example connection:

           Odroid C2   VL53L0X board
--------------------   -------------
 3.3V Power (Pin #1) - VIN
   I2CA_SDA (Pin #3) - SDA
   I2CA_SCL (Pin #5) - SCL
GPIOX.BIT21 (Pin #7) - XSHUT
     Ground (Pin #9) - GND

Of course, you can also use I2CB_SDA/SCL and any other GPIOX and Ground pins, see Hardkernel's page for pins' description.

Raspberry Pi
      Raspberry Pi 3   VL53L0X board
--------------------   -------------
 3.3V Power (Pin #1) - VIN
       SDA1 (Pin #3) - SDA
       SCL1 (Pin #5) - SCL
  GPIO_GCLK (Pin #7) - XSHUT
     Ground (Pin #9) - GND
BeagleBone Green Wireless

NOTE: you have to configure BeagleBone to enable I2C and GPIO on the specific pin you want to use via DTBs.

NOTE2: GPIOs are organised in blocks of 32 and the resulting GPIO number in /sys/class/gpio/ is (block number * 32 + gpio number), e.g. GPIO3_19 -> /sys/class/gpio/gpio115

               BBGW   VL53L0X board
-------------------   -------------
 3.3V Power (P9_03) - VIN
       SDA2 (P9_20) - SDA
       SCL2 (P9_19) - SCL
   GPIO3_19 (P9_27) - XSHUT
     Ground (P9_01) - GND

Software

Installation

Simply add all the .cpp and .hpp files to your project and modify your build script to include them.

See included CMakeLists.txt and examples section for an example on how to do it using CMake.

NOTE: If you intend to use other I2C bus than /dev/i2c-1, modify the #define I2C_DEV_PATH in I2Cdev.hpp file.

Using the library

  • Include "VL53L0X.hpp"
  • Create an object of VL53L0X class
  • Call .init()
  • (Optional) set timing budget etc
  • For single range reading:
    • Call .readRangeSingleMillimeters()
    • Check for possible timeout using .timeoutOccurred() (returned range value will be at maximum of 65535)
  • For continuous ranging:
    • Call .startContinuous()
    • Read rangings using .readRangeContinuousMillimeters()
    • Check for timeout (like in single ranging)
    • End with .stopContinuous()

See examples section for reference and Multiple sensors section for instructions how to use multiple sensors at once.

Multiple sensors

Multiple sensors can be used easily by connecting them all to the same I²C bus and connecting their XSHUT pins to free GPIO pins of your board.

Note that even putting the sensor to hardware standby (XSHUT low) will reset its address! Thus, the workflow is as such:

  • disable (power off) all sensors
  • enable (power on) first sensor
  • set its address
  • enable second sensor, set its address
  • ...and so on

That translates to following steps within your code:

  • pass XSHUT GPIO pin number to sensor object constructor (VL53L0X(pin))
  • disable all sensors either by calling their .powerOff() method
  • initialize sensors one-by-one and set different address for each one before initializing the next one

After that, reading range values from sensors is just like with single one. See examples/continuousMultipleSensors.cpp for reference.

Examples

Build examples with:

cd build
cmake ..
make

and run with

./examples/single
./examples/singleMinimal
./examples/continuousMultipleSensors

Single ranging mode, single sensor

examples/singleMinimal.cpp shows the minimal working example.

examples/single.cpp shows how to use a single sensor in single ranging mode in more detail and with proper commentary on what's going on.

Continuous ranging mode, multiple sensors

examples/continuousMultipleSensors.cpp shows how to use continuous ranging mode (with back-to-back measurements) while using multiple sensors at once. This is the most complex and thorough example and (after minor modifications) it was used in a real-life application on a mobile robot.

Note: in my experiments on Odroid C2 board with Linux-RT kernel, I've managed to run 6 sensors at once with stable frequency of more than 50Hz!


ST's VL53L0X API and this library

Most of the functionality of this library is based on the VL53L0X API provided by ST (STSW-IMG005), and some of the explanatory comments in the code are quoted or paraphrased from the API source code, API user manual (UM2039), and the VL53L0X datasheet. For more explanation about the library code and how it was derived from the API, see the block comments in VL53L0X.hpp and in-code comments in VL53L0X.cpp.

This library is intended to provide a quicker and easier way to get started using the VL53L0X with a GNU/Linux-driven single-board computer (like BeagleBone Black or Raspberry Pi), in contrast to customizing and compiling ST's API for that platform. The library has a more streamlined, object-oriented interface. However, it does not implement some of the more advanced functionality available in the API (for example, calibrating the sensor to work well under a cover glass), and it has less robust error checking. For advanced applications consider using the VL53L0X API directly (or opening PR/issue to add that functionality!).


Library reference

This section was not yet updated to match Linux version of the library - see header file for updated descriptions!

  • uint8_t last_status
    The status of the last I²C write transmission. 0 for success, errno for errors (you can use strerrno from to see error description)

  • VL53L0X()
    Constructor.

  • void setAddress(uint8_t new_addr)
    Changes the I²C slave device address of the VL53L0X to the given value (7-bit).

  • uint8_t getAddress()
    Returns the current I²C address.

  • bool init(bool io_2v8 = true)
    Iniitializes and configures the sensor. If the optional argument io_2v8 is true (the default if not specified), the sensor is configured for 2V8 mode (2.8 V I/O); if false, the sensor is left in 1V8 mode. The return value is a boolean indicating whether the initialization completed successfully.

  • void writeReg(uint8_t reg, uint8_t value)
    Writes an 8-bit sensor register with the given value. Register address constants are defined by the REGISTER_ADDRESSES enumeration type in VL53L0X.h.
    Example use: sensor.writeReg(VL53L0X::SYSRANGE_START, 0x01);

  • void writeReg16Bit(uint8_t reg, uint16_t value)
    Writes a 16-bit sensor register with the given value.

  • void writeReg32Bit(uint8_t reg, uint32_t value)
    Writes a 32-bit sensor register with the given value.

  • uint8_t readReg(uint8_t reg)
    Reads an 8-bit sensor register and returns the value read.

  • uint16_t readReg16Bit(uint8_t reg)
    Reads a 16-bit sensor register and returns the value read.

  • uint32_t readReg32Bit(uint8_t reg)
    Reads a 32-bit sensor register and returns the value read.

  • void writeMulti(uint8_t reg, uint8_t const * src, uint8_t count)
    Writes an arbitrary number of bytes from the given array to the sensor, starting at the given register.

  • void readMulti(uint8_t reg, uint8_t * dst, uint8_t count)
    Reads an arbitrary number of bytes from the sensor, starting at the given register, into the given array.

  • bool setSignalRateLimit(float limit_Mcps)
    Sets the return signal rate limit to the given value in units of MCPS (mega counts per second). This is the minimum amplitude of the signal reflected from the target and received by the sensor necessary for it to report a valid reading. Setting a lower limit increases the potential range of the sensor but also increases the likelihood of getting an inaccurate reading because of reflections from objects other than the intended target. This limit is initialized to 0.25 MCPS by default. The return value is a boolean indicating whether the requested limit was valid.

  • float getSignalRateLimit()
    Returns the current return signal rate limit in MCPS.

  • bool setMeasurementTimingBudget(uint32_t budget_us)
    Sets the measurement timing budget to the given value in microseconds. This is the time allowed for one range measurement; a longer timing budget allows for more accurate measurements. The default budget is about 33000 microseconds, or 33 ms; the minimum is 20 ms. The return value is a boolean indicating whether the requested budget was valid.

  • uint32_t getMeasurementTimingBudget()
    Returns the current measurement timing budget in microseconds.

  • bool setVcselPulsePeriod(vcselPeriodType type, uint8_t period_pclks) Sets the VCSEL (vertical cavity surface emitting laser) pulse period for the given period type (VL53L0X::VcselPeriodPreRange or VL53L0X::VcselPeriodFinalRange) to the given value (in PCLKs). Longer periods increase the potential range of the sensor. Valid values are (even numbers only):

    Pre: 12 to 18 (initialized to 14 by default)
    Final: 8 to 14 (initialized to 10 by default)

    The return value is a boolean indicating whether the requested period was valid.

  • uint8_t getVcselPulsePeriod(vcselPeriodType type)
    Returns the current VCSEL pulse period for the given period type.

  • void startContinuous(uint32_t period_ms = 0)
    Starts continuous ranging measurements. If the optional argument period_ms is 0 (the default if not specified), continuous back-to-back mode is used (the sensor takes measurements as often as possible); if it is nonzero, continuous timed mode is used, with the specified inter-measurement period in milliseconds determining how often the sensor takes a measurement.

  • void stopContinuous()
    Stops continuous mode.

  • uint16_t readRangeContinuousMillimeters()
    Returns a range reading in millimeters when continuous mode is active.

  • uint16_t readRangeSingleMillimeters()
    Performs a single-shot ranging measurement and returns the reading in millimeters.

  • void setTimeout(uint16_t timeout)
    Sets a timeout period in milliseconds after which read operations will abort if the sensor is not ready. A value of 0 disables the timeout.

  • uint16_t getTimeout()
    Returns the current timeout period setting.

  • bool timeoutOccurred()
    Indicates whether a read timeout has occurred since the last call to timeoutOccurred().


Special thanks

License

This library is licensed under MIT license, see LICENSE.txt file for full license text.

vl53l0x-linux's People

Contributors

kevin-pololu avatar mirkix avatar mjbogusz avatar romainreignier avatar shervinemami avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

vl53l0x-linux's Issues

2 sensors

Hi
Thank you so much for sharing this!
I was able to stream one sensor correctly, even without connecting the xshut pin (default addess 0x29)
Now I would like to stream 2 vl53l0x with a raspberry pi 4
I am using pins 17 and 27 (wiPi 0 and 2) for the xshut.
Here is how I modified the continousMultipleSensors.cpp example:

	// Configuration constants
	// Number of sensors. If changed, make sure to adjust pins and addresses accordingly (ie to match size).
	const int SENSOR_COUNT = 2;
	// GPIO pins to use for sensors' XSHUT. As exported by WiringPi.
	const uint8_t pins[SENSOR_COUNT] = { 0, 2 };
	// Sensors' addresses that will be set and used. These have to be unique.
	const uint8_t addresses[SENSOR_COUNT] = {
		VL53L0X_ADDRESS_DEFAULT + 2,
		VL53L0X_ADDRESS_DEFAULT + 6
	};

I also notice that with this code, after calling

sensors[i]->initialize();

if I check $ i2cdetec -y 1 the output is (weird):

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 
10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 
20: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 
30: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 
40: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 
50: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 
60: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 
70: 70 71 72 73 74 75 76 77  

Also if instead I use the single.cpp with 2 sensors and I wave my hand in front of one of them one at a time, I get both measures (not sure in which order..)

What am I doing wrong? Can you help me somehow?
Hope I was clear

Raspberry Pi 3. Runtime error (multiple sensors)

Board: Raspberry Pi 3B
OS: Raspbian Stretch

Can't run multiple sensors example. I have 3 pcs, so I changed the count of sensors in example. Also added 10K pull-up resistors between 3.3v and XSHUT.

Catch runtime error:
terminate called after throwing an instance of 'std::runtime_error'
what(): Failed opening file: /sys/class/gpio/gpio1/direction
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

Any ideas?

The issue in Single Sensor Reads in line 55 and 56.

The issue in Single Sensor Reads in line 55 and 56.
Error :

Scanning dependencies of target single
[ 8%] Building CXX object examples/CMakeFiles/single.dir/single.cpp.o
/home/debian/VL53L0X_TOF_Module/vl53l0x-linux-master/examples/single.cpp: In function ‘int main()’:
/home/debian/VL53L0X_TOF_Module/vl53l0x-linux-master/examples/single.cpp:63:31: error: ‘VcselPeriodPreRange’ is not a member of ‘VL53L0X’
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodPreRange, 18);
^~~~~~~
/home/debian/VL53L0X_TOF_Module/vl53l0x-linux-master/examples/single.cpp:64:31: error: ‘VcselPeriodFinalRange’ is not a member of ‘VL53L0X’
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodFinalRange, 14);
^~~~~~~
examples/CMakeFiles/single.dir/build.make:62: recipe for target 'examples/CMakeFiles/single.dir/single.cpp.o' failed
make[2]: *** [examples/CMakeFiles/single.dir/single.cpp.o] Error 1
CMakeFiles/Makefile2:89: recipe for target 'examples/CMakeFiles/single.dir/all' failed
make[1]: *** [examples/CMakeFiles/single.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

¿max sensors amount?

Hi! Thanks for your great contribution!

I was wondering if your library would work with 96 sensors.

Do you think it would?

And what could be the max reading frequency it could handle?

Or, what do you think would be the limit in amount of sensors and frequency? (if trying to connect the most sensors possible)

Thank you so much for your reply : )

Kiko from Perú

Works with BeagleBone Blue too

I tested this with one Seeedstudio Grove - Time of Flight Distance Sensor(VL53L0X).
The 'Grove Universal 4 Pin to Beaglebone Blue 4 Pin Female JST/SH Conversion Cable' allows an easy connection.
The Grove - I2C Hub also can be used.

Unfortunately the Grove sensor doesn't provide XSHUT/GPIO. So multi sensor or other features requiring XSHUT probably don't work with the Grove sensor.

Many thanks for the linux port and the nice code!

img_0466

Port to WiringX

Port the VL53L0X library to WiringX.

Mostly because it supports RaspberryPi, Odroid and many others in mainline (as opposed to my hacked-together version of WiringPi).
Also it is supported more actively, has (subjectively) better codebase, is licensed under MPL (vs GPL) and so on.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.