Parking sensor (VL53L0X)
A laser time-of-flight sensor measures the distance to the wall in millimetres; a buzzer beeps faster as you get closer and holds a tone when you should stop.
Sensors · Beginner
In a real product: Car parking assist (Automotive): A laser sensor beeps faster as the car gets closer.
A VL53L0X times how long an infrared laser pulse takes to come back. Light travels 30 cm a nanosecond, so the chip measures picoseconds, and reports millimetres. Here it drives a parking beeper: the closer the wall, the faster the beeps, and a steady tone under 10 cm.
What you'll learn
- Starting a sensor with a long setup sequence through its library, and checking it worked
- Continuous ranging, and why it is faster than asking for one reading at a time
- Mapping a distance onto a beep interval without blocking the loop
How it works
sensor.init() runs ST's start-up sequence: it reads the chip's calibration, loads tuning settings and calibrates the reference. startContinuous() keeps it measuring, each measurement taking its timing budget (33 ms by default), and readRangeContinuousMillimeters() waits for the next result.
The beep interval is the distance in millimetres divided by four, so at 400 mm it beeps every 100 ms. Under 100 mm the tone is continuous; over 1 m it is silent.
Try this
- Click the sensor and drag the distance down: the beeps speed up until the tone holds.
- Set the target to
none: the sensor reads 8190, out of range. Make the sketch say so instead of staying silent. - Call
sensor.setMeasurementTimingBudget(200000): readings get steadier and five times slower.
sketch.ino
// A parking sensor: a VL53L0X measures the distance continuously; the buzzer on pin 8 beeps every distance / 4 ms,
// holds a tone under 100 mm and is silent over 1 m.
#include <Wire.h>
#include <VL53L0X.h>
VL53L0X sensor;
const int BUZZER = 8;
unsigned long lastBeep = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
sensor.setTimeout(500);
if (!sensor.init()) {
Serial.println("No VL53L0X found");
while (true) {}
}
sensor.startContinuous();
}
void loop() {
int mm = sensor.readRangeContinuousMillimeters();
if (sensor.timeoutOccurred()) Serial.println("Timeout");
Serial.print(mm);
Serial.println(" mm");
if (mm < 100) {
tone(BUZZER, 2000);
} else if (mm > 1000) {
noTone(BUZZER);
} else if (millis() - lastBeep >= (unsigned long)mm / 4) {
lastBeep = millis();
tone(BUZZER, 2000, 40);
}
}