Build a Distance Meter With LED Indicators and a Live LCD Readout

by pouyan-asgharian in Circuits > Arduino

28 Views, 0 Favorites, 0 Comments

Build a Distance Meter With LED Indicators and a Live LCD Readout

I built a distance meter using a SparkFun VL53L4CD time-of-flight sensor and an Arduino board. A 16×2 LCD shows the live distance in millimeters, and three LEDs indicate how close the object is.

I needed to measure distance for another project, so I built this prototype to see how well the sensor worked. The LCD gives me the exact reading, and the LEDs let me see the distance range at a glance.

Supplies

Required components

  1. SparkFun RedBoard Plus, an Arduino Uno–compatible board
  2. SparkFun VL53L4CD Qwiic distance sensor and Qwiic cable
  3. 5 V, 16×2 LCD with a 16-pin parallel interface
  4. 10 kΩ potentiometer for LCD contrast
  5. Three LEDs, one red, one yellow, and one green
  6. Three 100 Ω resistors, one for each LED
  7. One 100 Ω or 220 Ω resistor for the LCD backlight, depending on your LCD module
  8. Breadboard and jumper wires
  9. USB cable to power and program the RedBoard from a laptop

Introduction

For one of my projects, I needed a simple way to measure how far away an object was. After looking at a few options, I chose the SparkFun VL53L4CD. It’s a compact, affordable time-of-flight (ToF) sensor that measures distance by timing how long it takes light to travel to an object and back.

SparkFun lists a precision of 1 mm, a minimum reading distance of 1 mm, and an accuracy of about ±7 mm under indoor test conditions with a white target and no interfering infrared light. The sensor has a typical 18° field of view and can take up to 100 readings per second. The breakout operates from 2.6 to 3.5 V and gets 3.3 V through the Qwiic cable in this build. SparkFun VL53L4CD specifications

I tested the sensor before building this project. You can find my test setup and results here on GitHub.

In this build, a SparkFun RedBoard Plus reads the sensor and displays the live distance in millimeters on a 16×2 LCD. Three LEDs let you tell the distance range at a glance.

Distance

  1. Less than 50 mm ---> Red
  2. 50–120 mm, -- > Yellow
  3. More than 120 mm ---> Green

Here’s a quick look at the finished circuit in action.

YouTube video

Connect the Distance Sensor

Plug one end of the Qwiic cable into the VL53L4CD breakout and the other end into the RedBoard Plus’s Qwiic port. I powered the finished circuit from my laptop over USB.

Wire the LCD and Adjust the Contrast

With the USB cable unplugged, set the RedBoard’s LOGIC switch to 5V. Use the circuit diagram and pin table below to wire the LCD. For the backlight, connect LCD pin 15 (A or LED+) to 5 V through a series resistor. Check your LCD module’s specifications when choosing the resistor value. Arduino LCD wiring guide

Connect the two outer legs of the 10 kΩ potentiometer to 5 V and GND, one leg to each. Connect the center leg to LCD pin 3 (VO). Once you’ve powered the circuit and uploaded the main sketch, turn the knob until the text is easy to read.

Connect the LEDs

For each LED, connect the longer leg (anode) to its assigned digital pin through a 100 Ω resistor. Connect the shorter leg (cathode) to GND.

  1. Green ---> D4
  2. Yellow ---> D5
  3. Red ---> D6

I built the prototype on a breadboard with jumper wires. I used the side rails to distribute 5 V and GND to the components that needed them. For a permanent build, you could transfer the circuit to a PCB.

Calibrate the Sensor

I used two Arduino sketches, one to calibrate the sensor and one to run the distance indicator. The calibration sketch is based on SparkFun’s example. In my setup, I had to add distanceSensor.startRanging(); before the sketch could detect the target and begin the countdown.

  1. Upload the calibration sketch and open the Serial Monitor.
  2. Hold a flat target less than 10 cm from the sensor for at least one second.
  3. When the five-second countdown starts, move the target to 140 mm from the front of the sensor and hold it steady.
  4. Record the offset reported by the calibration sketch so you can apply it in the main sketch.

I used white paper for my test. The calibration procedure this example is based on specifies a target with 17% reflectance at 940 nm. STMicroelectronics calibration guide


/*
Calling distance offset calibration for the laser based VL53L1X
By: Armin Joachimsmeyer
for SparkFun Electronics
Date: February 20th, 2020
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).

SparkFun labored with love to create this code. Feel like supporting open source hardware?
Buy a board from SparkFun! https://www.sparkfun.com/products/14667

This example calls the offset calibration for a VL53L1X sensor and stores the value to EEPROM.

Are you getting weird readings? Be sure the vacuum tape has been removed from the sensor.
*/

#include <Wire.h>
#include "SparkFun_VL53L1X.h" //Click here to get the library: http://librarymanager/All#SparkFun_VL53L1X

#define VERSION_EXAMPLE "1.0"

#define EEPROM_ADDRESS_FOR_OFFSET (E2END - 2) // last 2 bytes of EEPROM

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

SFEVL53L1X distanceSensor;
//Uncomment the following line to use the optional shutdown and interrupt pins.
//SFEVL53L1X distanceSensor(Wire, SHUTDOWN_PIN, INTERRUPT_PIN);

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

// initialize the digital pin as an output.
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
#if defined(__AVR_ATmega32U4__)
while (!Serial)
; //delay for Leonardo, but this loops forever for Maple Serial
#endif
#if defined(SERIAL_USB)
delay(2000); // To be able to connect Serial monitor after reset and before first printout
#endif
// Just to know which program is running on my Arduino
Serial.println(F("START " __FILE__ "\r\nVersion " VERSION_EXAMPLE " from " __DATE__));

#if !defined(ESP32) && !defined(ARDUINO_SAM_DUE) && !defined(__SAM3X8E__)
tone(TONE_PIN, 1000, 100);
delay(200);
#endif

Serial.println();
Serial.println("*****************************************************************************************************");
Serial.println(" Offset calibration");
Serial.println("Place a light grey (17 % gray) target at a distance of 140mm in front of the VL53L1X sensor.");
Serial.println("The calibration will start 5 seconds after a distance below 10 cm was detected for 1 second.");
Serial.println("Use the resulting offset distance as parameter for the setOffset() function called after begin().");
Serial.println("*****************************************************************************************************");
Serial.println();

#ifdef AVR
Serial.print("Old offset value read from EEPROM=");
Serial.print((int16_t)eeprom_read_word((uint16_t *)EEPROM_ADDRESS_FOR_OFFSET));
Serial.println(" mm");
#endif

if (distanceSensor.begin() != 0) //Begin returns 0 on a good init
{
Serial.println("Sensor failed to begin. Please check wiring. Freezing...");
while (1)
;
}
Serial.println("VL53L1X Sensor online!");

// Short mode max distance is limited to 1.3 m but has a better ambient immunity.
// Above 1.3 meter error 4 is thrown (wrap around).
distanceSensor.setDistanceModeShort();
//distanceSensor.setDistanceModeLong(); // default
distanceSensor.setTimingBudgetInMs(50);

int tLowDistanceCount = 0;
while (tLowDistanceCount < 20)
{
distanceSensor.startRanging();
while (!distanceSensor.checkForDataReady())
{
delay(1);
}
if (distanceSensor.getDistance() < 100)
{
tLowDistanceCount++;
}
else
{
tLowDistanceCount = 0;
}
distanceSensor.clearInterrupt();
}

Serial.println("Distance below 10cm detected for more than a second, start offset calibration in 5 seconds");
#if !defined(ESP32) && !defined(ARDUINO_SAM_DUE) && !defined(__SAM3X8E__)
tone(TONE_PIN, 1000, 100);
delay(1000);
tone(TONE_PIN, 1000, 100);
delay(1000);
tone(TONE_PIN, 1000, 100);
delay(1000);
tone(TONE_PIN, 1000, 100);
delay(1000);
tone(TONE_PIN, 1000, 900);
delay(1000);
#else
delay(5000);
#endif

/*
* Place a target, 17 % gray, at a distance of 140 mm from the sensor and call the VL53L1X_CalibrateOffset (dev, 140, &offset) function.
* The calibration may take a few seconds. The offset correction is applied to the sensor at the end of calibration.
*
* The calibration function takes 50 measurements and then takes the difference between the target distance
* and the average distance and then calls setOffset() with this value. Thats all. No magic.
*/
distanceSensor.calibrateOffset(140);
Serial.print("Result of offset calibration. RealDistance - MeasuredDistance=");
Serial.print(distanceSensor.getOffset());
Serial.print(" mm");
Serial.println();

#ifdef AVR
eeprom_write_word((uint16_t *)EEPROM_ADDRESS_FOR_OFFSET, distanceSensor.getOffset());
Serial.println("Offset value written to end of EEPROM.");
#endif

// measure periodically. Intermeasurement period must be >/= timing budget.
distanceSensor.setIntermeasurementPeriod(100);
distanceSensor.startRanging(); // Start once

#if !defined(ESP32) && !defined(ARDUINO_SAM_DUE) && !defined(__SAM3X8E__)
tone(TONE_PIN, 1000, 900);
#endif
}

void loop(void)
{
}



Upload and Test the Main Sketch

Install the SparkFun VL53L1X Arduino Library, which also supports the VL53L4CD breakout, and the LiquidCrystal library. In the main sketch, apply your measured offset with setOffset() after the sensor initializes successfully. SparkFun sensor hookup guide

Upload the main C++ sketch below. I’ve added comments to explain how it reads the sensor, updates the LCD, and selects an LED.

#include <Wire.h> // Adds I²C communication for the Qwiic sensor.
#include <LiquidCrystal.h> // Adds commands for the 16-pin LCD.
#include "SparkFun_VL53L1X.h" // Adds SparkFun's distance sensor commands.

const uint8_t GREEN_LED_PIN = 4; // Green LED uses RedBoard digital pin D4.
const uint8_t YELLOW_LED_PIN = 5; // Yellow LED uses D5.
const uint8_t RED_LED_PIN = 6; // Red LED uses D6.
// const means these values stay fixed. uint8_t is an 8-bit unsigned integer.

// Creates the LCD object. The six arguments are RedBoard pins for
// these LCD signals in order: RS, E, DB4, DB5, DB6, DB7.
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

SFEVL53L1X distanceSensor; // Creates the object used to control the sensor.

void setup() // Runs once. void means it returns no value.
{
pinMode(GREEN_LED_PIN, OUTPUT); // Makes D4 an output so it can drive the LED.
pinMode(YELLOW_LED_PIN, OUTPUT); // Makes D5 an output.
pinMode(RED_LED_PIN, OUTPUT); // Makes D6 an output.

digitalWrite(GREEN_LED_PIN, LOW); // Starts with green off.
digitalWrite(YELLOW_LED_PIN, LOW); // Starts with yellow off.
digitalWrite(RED_LED_PIN, LOW); // Starts with red off.

lcd.begin(16, 2); // Configures the LCD for 16 columns and 2 rows.
lcd.print("Distance"); // Writes the heading on the top row.

Wire.begin(); // Starts I²C communication.
Serial.begin(115200); // Sets the Serial Monitor speed to 115200 baud.
distanceSensor.setOffset(2037); // Keeps the offset setting from your original sketch.

if (distanceSensor.begin() != 0) // Tries to start the sensor. A nonzero result means failure.
{
lcd.setCursor(0, 1); // Goes to the first column of the second row.
lcd.print("Sensor error"); // Shows the error on the LCD.
Serial.println("Sensor failed to begin. Please check wiring.");
// Also shows the error in the Serial Monitor.
while (true) // Stays here indefinitely if startup failed.
{
delay(1000); // Waits one second on each pass through this block.
}
}

Serial.println("VL53L4CD sensor is online!"); // Reports successful startup.
}

void loop() // Runs repeatedly after successful setup.
{
distanceSensor.startRanging(); // Starts a distance measurement.

while (!distanceSensor.checkForDataReady()) // The ! means "while data is not ready."
{
delay(1); // Waits 1 ms before checking again.
}

// Stores the reading in millimeters as a 16-bit unsigned integer.
const uint16_t distanceMm = distanceSensor.getDistance();

distanceSensor.clearInterrupt(); // Clears the sensor's measurement-ready flag.
distanceSensor.stopRanging(); // Stops ranging until the next pass through loop().

// condition ? HIGH : LOW selects HIGH (LED on) when the condition is true.
digitalWrite(GREEN_LED_PIN, distanceMm < 50 ? HIGH : LOW); // Below 50 mm.
digitalWrite(YELLOW_LED_PIN, distanceMm >= 50 && distanceMm <= 120 ? HIGH : LOW); // 50–120 mm, inclusive.
digitalWrite(RED_LED_PIN, distanceMm > 120 ? HIGH : LOW); // Above 120 mm.
// && means both comparisons must be true.

lcd.setCursor(0, 1); // Goes back to the start of the second row.
lcd.print(distanceMm); // Writes the new distance.
lcd.print(" mm "); // Adds the unit and overwrites leftover characters.

Serial.print("Distance(mm): "); // Writes the label without starting a new line.
Serial.println(distanceMm); // Writes the reading and ends the line.

delay(100); // Waits 100 ms before starting the next measurement.
}

To test the finished circuit, move a flat object to about 30 mm, 80 mm, and 150 mm from the sensor. You should see the red, yellow, and green LEDs light up in that order as the LCD updates.

Download both sketches on GitHub