Time-of-Flight (TOF) sensors have revolutionized distance measurement in embedded projects, offering precise laser-based ranging capabilities. In this blog post, we’ll explore a complete Arduino implementation that combines the M5StickC Plus2 with a VL53L1X TOF sensor to create a real-time distance measurement display.
What You’ll Need
- M5StickC Plus2: A compact ESP32-based development board with a 1.14-inch TFT display
- VL53L1X TOF Sensor: A laser ranging sensor capable of measuring distances up to 4 meters
- Grove Cable: For connecting the sensor to the M5StickC Plus2
Understanding the Hardware
The M5StickC Plus2 is powered by the ESP32-PICO-V3-02 chip and features:
- 1.14-inch TFT display (135 x 240 resolution)
- Built-in I2C interface via Grove connector
- 200mAh battery for portable operation
- Multiple programmable buttons
The VL53L1X sensor offers significant advantages over its predecessor (VL53L0X):
- Extended range up to 4 meters (vs 2 meters)
- Better accuracy (±1-2% vs ±3%)
- Adjustable field of view (27° adjustable vs 25° fixed)
Code Breakdown
Library Includes and Setup
#include "M5Unified.h"
#include <Wire.h>
#include <VL53L1X.h>
#include <M5StickCPlus2.h>
VL53L1X sensor;
The code starts by including essential libraries:
M5Unified.h
: Core M5Stack functionalityWire.h
: I2C communicationVL53L1X.h
: TOF sensor driverM5StickCPlus2.h
: Device-specific functions
Initialization Process
void setup() {
// Initialize M5StickC Plus2
auto cfg = M5.config();
StickCP2.begin(cfg);
// Set up serial communication
Serial.begin(115200);
Serial.println("M5StickC Plus2 TOF Demo Starting...");
The setup begins by initializing the M5StickC Plus2 with default configuration and establishing serial communication for debugging.
Display Configuration
// Configure display
StickCP2.Display.setRotation(1); // Landscape orientation
StickCP2.Display.fillScreen(BLACK);
StickCP2.Display.setTextColor(WHITE);
StickCP2.Display.setTextSize(1);
The display is configured in landscape mode with a black background and white text for optimal readability.
TOF Sensor Initialization
// Initialize I2C for TOF sensor
M5.Ex_I2C.begin();
sensor.setBus(&Wire);
sensor.setTimeout(500);
// Initialize TOF sensor
if (!sensor.init()) {
Serial.println("Failed to detect and initialize sensor!");
StickCP2.Display.drawString("TOF Init Failed!", 10, 10);
while (1) {
delay(100);
}
}
This section initializes the I2C bus and attempts to connect to the TOF sensor. If initialization fails, the program displays an error message and halts execution.
Sensor Configuration
// Configure TOF sensor settings
sensor.setDistanceMode(VL53L1X::Long);
sensor.setMeasurementTimingBudget(50000);
sensor.startContinuous(50);
The sensor is configured for:
- Long distance mode: Enables maximum 4-meter range
- 50ms timing budget: Balances accuracy with measurement speed
- Continuous measurement: Takes readings every 50ms
Main Loop: Real-Time Display
The main loop continuously reads sensor data and updates the display:
Data Acquisition
void loop() {
// Read sensor data
sensor.read();
// Clear display
StickCP2.Display.fillScreen(BLACK);
Each loop iteration starts by reading fresh sensor data and clearing the display for new information.
Formatted Display Output
// Display TOF data with proper formatting
StickCP2.Display.setCursor(5, 5);
StickCP2.Display.setTextColor(GREEN);
StickCP2.Display.setTextSize(2);
StickCP2.Display.println("TOF Sensor");
// Display range
StickCP2.Display.setCursor(5, 30);
StickCP2.Display.setTextColor(CYAN);
StickCP2.Display.setTextSize(1);
StickCP2.Display.print("Range: ");
StickCP2.Display.setTextColor(WHITE);
StickCP2.Display.print(String(sensor.ranging_data.range_mm));
StickCP2.Display.println(" mm");
The display shows multiple data points:
- Range: Distance measurement in millimeters
- Status: Measurement validity indicator
- Peak Signal: Signal strength in MCPS (Mega Counts Per Second)
- Ambient Light: Background light level
Serial Output for Debugging
// Serial output for debugging
Serial.print("Range: ");
Serial.print(sensor.ranging_data.range_mm);
Serial.print(" mm\tStatus: ");
Serial.print(VL53L1X::rangeStatusToString(sensor.ranging_data.range_status));
// ... additional serial output
Parallel serial output enables real-time monitoring and debugging through the Arduino IDE’s Serial Monitor.
Key Features and Benefits
Real-Time Performance
The 100ms loop delay provides smooth, responsive updates while preventing display flickering.
Comprehensive Data Display
Beyond basic distance measurement, the code displays:
- Measurement status (valid/invalid readings)
- Signal strength indicators
- Ambient light conditions
Error Handling
Robust initialization checks ensure the system fails gracefully if the sensor isn’t properly connected.
Dual Output
Both visual display and serial output provide flexibility for different use cases and debugging scenarios.
Practical Applications
This TOF sensor implementation opens doors to numerous applications:
- Proximity Detection: Automated lighting or security systems
- Robotics: Obstacle avoidance and navigation
- Industrial Automation: Precise positioning and measurement
- Smart Home: Occupancy detection and automated controls
Conclusion
This implementation demonstrates the power of combining modern TOF sensor technology with the M5StickC Plus2’s integrated display capabilities. The VL53L1X sensor’s improved range and accuracy, paired with the ESP32’s processing power, creates a versatile platform for distance measurement applications.
The code’s modular structure makes it easy to extend with additional features like data logging, wireless connectivity, or integration with larger IoT systems. Whether you’re building a prototype or developing a commercial product, this foundation provides a solid starting point for TOF-based distance measurement projects.
Ready to build your own TOF distance sensor? The complete code is available and ready to upload to your M5StickC Plus2!