VL53L0X Sensor Interfacing with ESP32

Overview of VL53L0X Sensor

VL53L0X Sensor Module
VL53L0X Sensor

 

  • The VL53L0X is a new generation laser-ranging module that works on the Time-of-Flight (ToF) principle which is developed by ST Microelectronics
  • It is used to measure the distance up to 2 meters.
  • This Module is 4 Pin, which works on the I2C communication protocol.
  • This sensor operates on a 2.8 to 5.5 V power supply

 

What is Time-of-Flight?

  • Time of flight is the measurement of the time taken by an object, particle, or wave to travel a distance through a medium.
  • The time-of-flight principle is based on measuring the time it takes for a wave to travel from a source (a time-of-flight sensor) to an object and back.
  • In the below diagram how much time is required to receive the light at the collector which is emitted by the emitter is a principle of Time-of-Flight.
Picture of Time of Flight Principle
Time of Flight Principle

 

VL53L0X Hardware Connection with ESP32

ESP32 interfacing with VL53L0X
ESP32 interfacing with VL53L0X

 

 

Distance measurement using VL53L0X and ESP32

Let’s interface the VL53L0X sensor to ESP32 and measure the distance in centimetres and display it on the serial monitor and web server.

 

Install Require Library for VL53L0X

Here we are using Adafruit libraries for the above example. We will need to install the Adafruit VL53L0X library using the Arduino Library Manager.

Open the Arduino IDE and navigate to Sketch ► Include Library ► Manage Libraries…

Arduino Manage Library

 

The library Manager window will pop up. Now enter VL53L0X into the search box and click Install on the Adafruit_VL53L0X library option to install version 1.2.0 or higher.

 

Now open example of vl53l0x. To open it navigate to File ► Examples ► Adafruit_VL53L0X ► vl53l0x

 

Here we have used the same code for the above example.

 

Code for VL53L0X Distance Measurement using ESP32 and Arduino IDE

#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

void setup() {
  Serial.begin(115200);

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }
 
  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power 
  Serial.println(F("VL53L0X API Simple Ranging example\n\n")); 
}


void loop() {
  VL53L0X_RangingMeasurementData_t measure;
   
  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }
   
  delay(100);
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 to see the output.

 

VL53L0X Output on the Serial Window

 

Let’s understand the code

The code is beginning with including the supporting library which is Adafruit_VL53L0X.h

#include "Adafruit_VL53L0X.h"

Then, define the object of Adafruit_VL53L0X() function. Here you can use the same library to read distance from multiple VL53L0X modules.

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

 

In setup function

We have initiated the serial communication with a 115200 Baud rate.

Serial.begin(115200);

Wait until the serial port opens for native USB devices. If open, code will execute further, otherwise stuck in this while() loop.

while (! Serial) {
      delay(1);
}

Check whether the VL53L0X sensor connection is correct or not, if all ok then move forward to print the distance else fail to boot the VL53L0X.

Serial.println("Adafruit VL53L0X test");
if (!lox.begin()) {
      Serial.println(F("Failed to boot VL53L0X"));
      while(1);
}
// power 
Serial.println(F("VL53L0X API Simple Ranging example\n\n"));

 

In loop function

Create an object for VL53L0X_RangingMeasurementData_t class

VL53L0X_RangingMeasurementData_t measure;

Here, there are two modes for sensor data mode and debug mode, you can also set it in debug mode by sending “true” and set the data mode by sending “false”

Serial.print("Reading a measurement... ");
lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

Finally reads data from the sensor and print the distance in mm on the serial monitor.

if (measure.RangeStatus != 4) {  // phase failures have incorrect data
      Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } 
else {
      Serial.println(" out of range ");
  }

 

Reading VL53L0X Distance over ESP32 WebServer

ESP32 has oh-chip Wi-Fi, we can utilize it and monitor the readings over our smartphone, Laptop, or even smart TV. This can offer much more flexibility and real world applications.

We can use the ESP32 web server to monitor the distance.

 

Let’s take another example to display the same readings on the web server using the ESP32 and Arduino IDE.

Before uploading the code make sure you have added your SSID, and Password as follows.

const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/

Code for VL53L0X Web Server using ESP32

#include <WiFi.h>
#include <WebServer.h>
#include "html.h"
#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();
WebServer server(80);


const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/

int cm;

void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send the code to the web server*/
}

void Distance() {
  String data = "[\""+String(cm)+"\"]";
  server.send(200, "text/plane", data);
}

void setup(void){
  Serial.begin(115200);                 /*Set the baudrate to 115200*/

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }

  Serial.println(F("VL53L0X API Simple Ranging example\n\n")); 
  WiFi.mode(WIFI_STA);                  /*Set the WiFi in STA Mode*/
  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  delay(1000);                          /*Wait for 1000mS*/
  while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");} /*Wait while connecting to WiFi*/
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("Your Local IP address is: ");
  Serial.println(WiFi.localIP());       /*Print the Local IP*/

  server.on("/", MainPage);             /*Display the Web/HTML Page*/
  server.on("/readDistance", Distance); /*Display the updated Distance value(CM and INCH)*/
  server.begin();                       /*Start Server*/
  delay(1000);                          /*Wait for 1000mS*/
}

void loop(void){
 VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  Serial.print("Distance (mm): "); 
  cm = measure.RangeMilliMeter;
  Serial.println(cm);
  server.handleClient();
  Serial.println();
  delay(1000);
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 then reset the ESP32 board and check the IP address as shown in the below image

 

 

Output on the webserver

  • Now open any mobile browser and type the IP address which is shown in the serial monitor and hit the enter button. 
  • If all are ok, then the web page will start the showing current distance on the web server like in the below image.

Note: make sure your ESP32 and mobile are connected to the same router/server, if they are connected to the same router or server then only you will be able to visible the web page.

 

 

Let’s Understand the code

To understand this code, please refer to the basics guide of “How to create the ESP32 Server”.

Once you get the basics of ESP32 server creation, it will be very simple to understand the code.

This code starts with important header files and libraries, In WiFi.h file contains all ESP32 WiFi related definitions, here we have used them for network connection purposes. 

The WebServer.h file supports handling the HTTP GET and POST requests as well as setting up a server. In the html.h file contains all the web page code.

#include <WiFi.h>
#include <WebServer.h>
#include "html.h"
#include "Adafruit_VL53L0X.h"
Let’s define HTTP port i.e., Port 80 as follows
WebServer server(80);

 

Setup Function

In the setup function, first we set the WiFi as an STA mode and connect to the given SSID and password

WiFi.mode(WIFI_STA);          /*Set the WiFi in STA Mode*/
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
delay(1000);                  /*Wait for 1000mS*/
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}

After successfully connecting to the server print the local IP address on the serial window.

Serial.print("Your Local IP address is: ");
Serial.println(WiFi.localIP());     /*Print the Local IP*/

 

Handling Client Requests and Serving the Page

To handle the client request, we use server.on() function.

It takes two parameters, The first is the requested URL path, and the second is the function name, which we want to execute.

As per the below code, when a client requests the root (/) path, the “MainPage()” function executes. 

Also, when a client requests the “/readDistance” path, The Distance() function will be called.

server.on("/", MainPage);           /*Client request handling: calls the function to serve HTML page */
server.on("/readDistance", Distance);/*Display the updated Distance value(CM and INCH)*/

Now start the server using server.begin() function.

server.begin();                     /*Start Server*/

 

Functions for Serving HTML

We have defined the complete HTML page in a file named “html.h” and added it to the header file. With the following function, we are sending the complete page to the client via server.send() function.

While sending, we are passing the first parameter “200” which is the status response code as OK (Standard response for successful HTTP requests). 

Second parameter is the content type as “text/html“, and the third parameter is html page code.

void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send HTM page to Client*/
}

Now in the below function only we are sending the updated Distance measurement to the web page.

void Distance() {
  String data = "[\""+String(cm)+"\"]";
  server.send(200, "text/plane", data);
}

 

Loop Function

Now to handle the incoming client requests and serve the relevant HTML page, we can use handleClient() function. It executing relevant server.on() as a callback function although it is defined in void setup()

So, it continuously serves the client requests.

server.handleClient();

 

HTML Page Code

/*
  ESP32 HTML WebServer Page Code
  http:://www.electronicwings.com
*/

const char html_page[] PROGMEM = R"RawString(
<!DOCTYPE html>
<html>
  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>

<body>
  <h1>VL53L0X Time of Flight Distance Measurement</h1><br>
  <p>Distance in CM : <span id="_CM">0</span> mm</p>

<script>
  setInterval(function() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const text = this.responseText;
        const myArr = JSON.parse(text);
       document.getElementById("_CM").innerHTML = myArr[0];
      }
    };
    xhttp.open("GET", "readDistance", true);
    xhttp.send();
  },50);
</script>
</body>
</html>
)RawString";

 

Let’s understand the code step by step

All html pages start with the <!DOCTYPE html> declaration, it is just information to the browser about what type of document is expected.

<!DOCTYPE html>

The html tag is the container of the complete html page which represents on the top of the html code.

<html>

Now here we are defining the style information for a web page using the <style> tag. Inside the style tag we have defined the font name, size, color, and test alignment. 

  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>

 

Inside the body, we are defining the document body, in below we have used headings, and paragraphs if you want you can add images, hyperlinks, tables, lists, etc. also.

On the web page, we are displaying the heading of the page, and inside a paragraph distance readings. 

Now distance readings updates under the span id which is manipulated with JavaScript using the id attribute.

<body>
  <h1>VL53L0X Time of Flight Distance Measurement</h1><br>
  <p>Distance in CM : <span id="_CM">0</span> mm</p> 

Now, this is the javascript that comes under the <script> tag, this is also called a client-side script.

<script>

In setInterval() method we are calling the function at every 50mS intervals.

setInterval(function() {},50);

here we are creating the html XMLHttpRequest object

var xhttp = new XMLHttpRequest();

 

The xhttp.onreadystatechange event is triggered every time the readyState changes and the readyState holds the status of the XMLHttpRequest.

Now in the below code, the ready state is 4 means the request finished and response is ready and the status is 200 which means OK.

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const myArr = JSON.parse(this.responseText);

now here is the main thing, we are updating the distance reaging in html page using _CM id.

document.getElementById("_CM").innerHTML = myArr[0]; 

 

Here we used the AJAX method to send the updated values to the server without refreshing the page.

In the below function we have used the GET method and sent the readDistance function which we defined in the main code asynchronously.

xhttp.open("GET", "readDistance", true); 

Send the request to the server using xhttp.send(); function.

xhttp.send();

 

Close the script

</script>

Close the body

</body>

Close the html.

</html>

Components Used

VL53L0X Time-of-Flight Ranging and Gesture Detection Sensor
VL53L0X is Time-of-Flight ranging and gesture detection sensor.
1
ESP32 WROOM
WiFi Development Tools - 802.11 ESP32 General Development Kit, embeds ESP32-WROOM-32E, 4MB flash.
1

Downloads

VL53L0X_ESP32_Serial Download
VL53L0X_ESP32_WebServer Download
Ad