Qwiic Distance Sensor (VL53L1X) Hookup Guide

Pages
Contributors: Englandsaurus
Favorited Favorite 0

Introduction

The VL53L1X is the latest Time Of Flight (ToF) sensor to be released. It uses a VCSEL (vertical cavity surface emitting laser) to emit a class 1 IR laser (940 nm) and time the reflection to the target. (You can’t see the laser but cell phones can) What does all this mean? You can measure the distance to an object up to 4 meters away with millimeter resolution! That’s pretty incredible.

SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

SEN-14722
$21.95
3

We’ve found the precision of the sensor to be 1mm but the accuracy is around +/-5mm. The minimum read distance of this sensor is 4cm. In this hookup guide we’ll go over how to read distance, change ranging modes, and check the status of our range measurement along with the sample rate. We’ll also check out how to display distance and speed over an LCD display.

Required Materials

To get started, you’ll need a microcontroller to, well, control everything.

SparkFun RedBoard - Programmed with Arduino

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
39
SparkFun ESP32 Thing

SparkFun ESP32 Thing

DEV-13907
$21.95
60
Particle Photon (Headers)

Particle Photon (Headers)

WRL-13774
$19.00
29

Raspberry Pi 3

DEV-13825
92

Now to get into the Qwiic ecosystem, the key will be one of the following Qwiic shields to match your preference of microcontroller:

SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
SparkFun Qwiic HAT for Raspberry Pi

SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$5.95
1
SparkFun Qwiic Shield for Photon

SparkFun Qwiic Shield for Photon

DEV-14477
$5.95

You will also need a Qwiic cable to connect the shield to your distance sensor, choose a length that suits your needs.

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95

Suggested Reading

If you aren’t familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We would also recommend taking a look at the following tutorials if you aren’t familiar with them.

Serial Communication

Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

Qwiic Shield for Arduino & Photon Hookup Guide

Get started with our Qwiic ecosystem with the Qwiic shield for Arduino or Photon.

Hardware Overview

First let’s check out some of the characteristics of the VL53L1X sensor we’re dealing with, so we know what to expect out of the board.

CharacteristicRange
Operating Voltage2.6V-3.5V
Power Consumption20 mW @10Hz
Measurement Range~40mm to 4,000mm
Resolution+/-1mm
Light SourceClass 1 940nm VCSEL
I2C Address0x29
Field of View15° - 27°
Max Read Rate50Hz

Pins

The following table lists all of the VL53L1X’s pins and their functionality.

PinDescriptionDirection
GNDGroundIn
3.3VPowerIn
SDADataIn
SCLClockIn
INTInterrupt, goes low when data is ready.Out
SHUTShutdown, can be pulled low to put the IC in shutdown mode.In

Optional Features

The VL53L1X breakout has pull up resistors attached to the I2C bus as well as the interrupt pin; if multiple sensors are connected to the bus with the pull-up resistors enabled, the parallel equivalent resistance will create too strong of a pull-up for the bus to operate correctly. As a general rule of thumb, disable all but one pair of pull-up resistors if multiple devices are connected to the bus. If you need to disconnect the pull up resistors they can be removed by cutting the traces on the corresponding jumpers highlighted below.

Pullup Jumpers

The onboard LED (highlighted below) will light up when the board is powered, and the sensor (also highlighted below) should be left uncovered in your application.

Sensor and LED

Hardware Assembly

If you haven’t yet assembled your Qwiic Shield, now would be the time to head on over to that tutorial. Depending on the microcontroller and shield you’ve chosen, your assembly may be different, but here’s a handy link to the Qwiic Shield for Arduino and Photon Hookup Guide to get you started!

Qwiic Shield for Arduino Photon Hookup Guide

With the shield assembled, SparkFun’s new Qwiic environment means that connecting the sensor could not be easier. Just plug one end of the Qwiic cable into the VL53L1X breakout, the other into the Qwiic Shield and you’ll be ready to upload a sketch and figure out how far away you are from that thing over there. It seems like it’s too easy too use, but that’s why we made it that way!

Connected to Qwiic Shield

SparkFun RedBoard and Qwiic Shield with the Qwiic Distance Sensor Attached

Library Overview

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

First, you’ll need the SparkFun VL53L1X Arduino library, which is an easy to use wrapper of ST’s driver. You can obtain these libraries through the Arduino Library Manager. Search for Sparkfun VL53L1X Arduino Library to install the latest version. If you prefer downloading the libraries from the GitHub repository and manually installing it, you can grab them here:

DOWNLOAD THE SPARKFUN VL53L1X ARDUINO LIBRARY (ZIP)

Before we get started developing a sketch, let’s look at the available functions of the library.

  • boolean init(); — Initialize the sensor
  • void startRanging(); — Starts taking measurements.
  • void stopRanging(); — Stops taking measurements.
  • bool checkForDataReady(); — Checks if a measurement is ready.
  • void setTimingBudgetInMs(uint16_t timingBudget) — Set the timing budget for a measurement in ms. The timing budget is the amount of time over which a measurement is taken. This can be set to any of the following.
    • 15
    • 20
    • 33
    • 50
    • 100 (default)
    • 200
    • 500
  • uint16_t getTimingBudgetInMs(); — Get’s the current timing budget in ms.
  • void setDistanceModeLong(); — Sets to 4M range.
  • void setDistanceModeShort(); — Sets to 1.3M range
  • uint8_t getDistanceMode(); — Returns 1 for short range, 2 for long range.
  • void setIntermeasurementPeriod(uint16_t intermeasurement); — Set’s the period in between measurements. Must be greater than or equal to the timing budget. Default is 100 ms.
  • uint16_t getIntermeasurementPeriod(); — Returns the intermeasurement period in ms.
  • bool checkBootState(); — Checks whether the device has been booted. Returns true if the device has been booted.
  • uint16_t getSensorID(); — Get the sensor ID, should be 0xEEAC.
  • uint16_t getDistance(); — Returns the results from the last measurement, distance in mm
  • uint16_t getSignalPerSpad(); — Returns the average signal rate per SPAD (The sensitive pads that detect light, the VL53L1X has a 16x16 array of these) in kcps/SPAD, or kilo counts per second per SPAD.
  • uint16_t getAmbientPerSpad(); — Returns the ambient noise when not measuring a signal in kcps/SPAD.
  • uint16_t getSignalRate(); — Returns the signal rate in kcps. All SPADs combined.
  • uint16_t getSpadNb(); — Returns the current number of enabled SPADs
  • uint16_t getAmbientRate(); — Returns the total ambinet rate in kcps. All SPADs combined.
  • uint8_t getRangeStatus(); — Returns the range status, which can be any of the following.
    • 0: No error
    • 1: Signal fail
    • 2: Sigma fail
    • 7: Wrapped target fail
  • void setOffset(int16_t offset); — Manually set an offset for a measurement in mm.
  • int16_t getOffset(); — Get the current offset in mm.
  • void setXTalk(uint16_t xTalk); — Manually set the value of crosstalk in counts per second (cps), which is interference from any sort of window in front of your sensor.
  • uint16_t getXTalk(); — Returns the current crosstalk value in cps.
  • void setDistanceThreshold(uint16_t lowThresh, uint16_t hiThresh, uint8_t window); — Set bounds for the interrupt. lowThresh and hiThresh are the bounds of your interrupt while window decides when the interrupt should fire. The options for window are shown below.
    • 0: Interrupt triggered on measured distance below lowThresh.
    • 1: Interrupt triggered on measured distance above hiThresh.
    • 2: Interrupt triggered on measured distance outside of bounds.
    • 3: Interrupt triggered on measured distance inside of bounds.
  • uint16_t getDistanceThresholdWindow(); — Returns distance threshold window option.
  • uint16_t getDistanceThresholdLow(); — Returns lower bound in mm.
  • uint16_t getDistanceThresholdHigh(); — Returns upper bound in mm
  • void setROI(uint16_t x, uint16_t y); — Set the height and width of the ROI in SPADs, lowest possible option is 4. ROI is always centered.
  • uint16_t getROIX(); — Returns the width of the ROI in SPADs
  • uint16_t getROIY(); — Returns the height of the ROI in SPADs
  • void setSignalThreshold(uint16_t signalThreshold); — Programs the necessary threshold to trigger a measurement. Default is 1024 kcps.
  • uint16_t getSignalThreshold(); — Returns the signal threshold in kcps
  • void setSigmaThreshold(uint16_t sigmaThreshold); — Programs a new sigma threshold in mm. (default=15 mm)
  • uint16_t getSigmaThreshold(); — Returns the current sigma threshold.
  • void startTemperatureUpdate(); — Recalibrates the sensor for temperature changes. Run this any time the temperature has changed by more than 8°C
  • void calibrateOffset(uint16_t targetDistanceInMm); — Autocalibrate the offset by placing a target a known distance away from the sensor and passing this known distance into the function.
  • void calibrateXTalk(uint16_t targetDistanceInMm); — Autocalibrate the crosstalk by placing a target a known distance away from the sensor and passing this known distance into the function.

Example Code

Now that we have our library installed and we understand the basic functions, let’s run some examples for our distance sensor to see how it behaves.

Example 1 - Read Distance

To get started with the first example, open up File > Examples > SparkFun VL53L1x 4M Laser Distance Sensor > Example1_ReadDistance. In this example, we begin by creating a SFEVL53L1X object called distanceSensor with our wire port, Wire, and then our shutdown and interrupt pins. Then we initialize our sensor object in the setup() loop. The code to do this is shown below and is repeated in some form in all of the examples.

language:c
#include <Wire.h>
#include "SparkFun_VL53L1X.h"

//Optional interrupt and shutdown pins.
#define SHUTDOWN_PIN 2
#define INTERRUPT_PIN 3

SFEVL53L1X distanceSensor(Wire, SHUTDOWN_PIN, INTERRUPT_PIN);

void setup(void)
{
  Wire.begin();

  Serial.begin(9600);
  Serial.println("VL53L1X Qwiic Test");

  if (distanceSensor.init() == false)
    Serial.println("Sensor online!");

}

Once we’ve initialized our sensor, we can start grabbing measurements from it. To do this, we send some configuration bytes to our sensor using distanceSensor.startRanging() to initiate the measurement. We then wait for data to become available and when it does, we read it in, convert it from millimeters to feet, and print it out over serial. The void loop() function that does this is shown below.

language:c
void loop(void)
{
  distanceSensor.startRanging(); //Write configuration bytes to initiate measurement
  int distance = distanceSensor.getDistance(); //Get the result of the measurement from the sensor
  distanceSensor.stopRanging();

  Serial.print("Distance(mm): ");
  Serial.print(distance);

  float distanceInches = distance * 0.0393701;
  float distanceFeet = distanceInches / 12.0;

  Serial.print("\tDistance(ft): ");
  Serial.print(distanceFeet, 2);

  Serial.println();
}

Opening your serial monitor to a baud rate of 9600 should show the distance between the sensor and the object it’s pointed at in both millimeters and feet. The output should look something like the below image.

Read Distance

Distance readings in mm and ft

Example 2 - Set Distance Mode

In this example, we’ll change the distance mode of the VL53L1X. The default long range mode is the most robust as far as sample rate and range are concerned, but for a slightly higher sample rate, you can bring the range down to short (~1.3M). To get started with the second example, open up File > Examples > SparkFun VL53L1x 4M Laser Distance Sensor > Example2_SetDistanceMode. The main difference between this example and the previous example is that we call distanceSensor.setDistanceModeShort to change the range of our sensor to short range. Although this feature is available, we’d recommend sticking with long range as it is the most robust.

Example 3 - Status and Rate

In the third example, we’ll read and average our distance as well as read the sample rate and status of each measurement. To get started with the third example, open up File > Examples > SparkFun VL53L1x 4M Laser Distance Sensor > ExampleStatusandRate. The status of a measurement can be any of 8 values. Our void loop() interprets the value returned by distanceSensor.getRangeStatus() and prints that value over serial. The below table shows the possible values of rangeStatus and their corresponding errors.

Range StatusError
0Valid measurement
1Raised if sigma estimator (uncertainty in measurement) check is above the internal defined threshold
2 Raised if signal value is below the internal defined threshold
4Raised when phase is out of bounds
5Raised in case of HW or VCSEL failure
7Wrapped target, not matching phases
8Internal algorithm underflow or overflow
14The reported range is invalid

In the example code, notice how the sketch stores our previous values in the array history so that the average distance can also be calculated. Uploading this sketch to your microcontroller and opening the serial monitor to a baud rate of 9600 should give you an output similar to the image shown below.

Status and Rate

Click the image for a closer look.

Example 4 - Set Intermeasurement Period

The fourth example allows you to change the time alotted for a measurement. The VL53L1X will send out a laser pulse and then listen for the alotted time. We’d recommend 20, 33, and 100 ms for short, medium and long distance modes respectively. To open up the example, head to File > Examples > SparkFun VL53L1x 4M Laser Distance Sensor > Example4_SetIntermeasurementPeriod. There’s not much that needs to be done to change the intermeasurement period other than a call to distanceSensor.setIntermeasurementPeriod(33) to change the time alotted time for a measurement to 33 ms. This will give us a data rate of roughly 30 Hz, lengthening the intermeasurement period will give us a lower sample rate, but will yield higher accuracy at longer ranges. Opening the serial monitor should yield an output similar to example 1.

Example 5 - LCD Demo

The fifth example requires a serial enabled LCD screen for us to write our distance values to. If you haven’t played around with a Serial enabled LCD before, checkout our hookup guide on the matter. To get started with the fourth example, open up File > Examples > SparkFun VL53L1x 4M Laser Distance Sensor > Example5_LCDDemo. We’ll first need to connect the RX pin of our Serial LCD to pin A3 on our Arduino. Connect 5V and ground on the LCD and the backlight should light up. Notice how we also include the SoftwareSerial library. Uploading the sketch to our Arduino then takes in our sample rate and distances. By using these values, it calculates a velocity. Like the sketch before, distances are stored in an array. The sketch uses these values in the array to calculate velocity and the velocity is then displayed along with the current distance on the LCD. The output on the LCD should look something like the below GIF.

LCD Distance Display

Resources and Going Further

Now that you’ve successfully got your Qwiic Distance Sensor up and running, it’s time to incorporate it into your own project!

For more information, check out the resources below:

Want a great use case for your ToF sensor? How about integrating one into your AVC submission? Have a look here:

Need even more inspiration for your next project? Check out some of these related tutorials:

SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

Qwiic Flex Glove Controller Hookup Guide

Is your finger bent? Is your finger straight? The Qwiic Flex Glove controller board will answer this age old question for you with the flex sensor!

SparkFun Pro nRF52840 Mini Hookup Guide

A hardware overview and hookup guide for the SparkFun Pro nRF52840 Mini -- a breakout for Nordic's impossibly cool Bluetooth/ARM Cortex M4 SoC.
New!

Qwiic Single Relay Hookup Guide

Get started switching those higher power loads around with the Qwiic Single Relay.