pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

Hat ToF Arduino Tutorial

1. Preparation

2. Example Program

Example Description
Hat ToF is a high-precision laser ranging sensor designed specifically for StickC. It integrates the ST laser ranging chip VL53L0X and a 940nm VCSEL emitter. By measuring the round-trip time of the laser signal to the target object, it can measure absolute distance within a 2m range in less than 30ms. In this example, StickC-Plus2 will drive and control Hat ToF via the I2C interface, and print data on the StickC-Plus2 screen and in the computer’s serial monitor.

Full Program

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <M5Unified.h>
#include <Wire.h>
#include <VL53L0X.h>

VL53L0X sensor;

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

    // I2C initialization (SDA: G0, SCL: G26)
    Wire.begin(0, 26);

    // Sensor initialization
    sensor.setTimeout(500);
    if (!sensor.init()) {
        Serial.println("Sensor init failed!");
        while (1);
    }

    // Set measuring mode (default: 120cm)
    sensor.setMeasurementTimingBudget(200000);

    Serial.println("Hat ToF Ready");
}

void loop() {
    M5.update();

    uint16_t distance = sensor.readRangeSingleMillimeters();

    if (sensor.timeoutOccurred()) {
        Serial.println("Timeout!");
    } else {
        Serial.printf("Distance: %.1f cm\n", distance / 10.0);
        M5.Display.fillScreen(BLACK);
        M5.Display.setRotation(1);
        M5.Display.setTextSize(2);
        M5.Display.setCursor(10, 40, 2);
        M5.Display.setTextColor(WHITE);
        M5.Display.printf("Distance: %.1f cm\n", distance / 10.0);
    }

    delay(100);
}

3. Compile and Upload

  1. Enter download mode: Before flashing a program, different Stick devices require the corresponding driver to be installed. Different main controllers may use different drivers and installation steps. For details, refer to the device program download tutorial list at the bottom of the Arduino IDE Getting Started Guide page to find the operation method for your specific device.

  2. Select the device port, click the Compile and Upload button in the upper-left corner of the Arduino IDE, and wait for the program to finish compiling and uploading to the device.

4. Hat ToF Laser Ranging Sensor Data Display

This program will read the Hat ToF laser ranging sensor data and print it on the StickC-Plus2 screen and in the computer’s serial monitor:

On This Page