pdf-icon

Arduino Guide

Unit Ultrasonic-I2C Arduino Tutorial

1. Preparation

2. Example

Case Explanation
This example uses the Unit Ultrasonic-I2C to implement an ultrasonic distance measurement function and displays the measurement results on the screen.
#include <M5Unified.h>
#include <Unit_Sonic.h>

SONIC_I2C sensor;

void setup()
{
    M5.begin();
    // sensor.begin(TwoWire* wire, uint8_t addr, uint8_t sda, uint8_t scl, uint32_t speed);
    sensor.begin(&Wire, 0x57, 2, 1, 400000U);
    M5.Display.setColorDepth(1);
    M5.Display.setFont(&fonts::Orbitron_Light_32);
    M5.Display.setTextDatum(middle_center);
}

int point      = 0;
int last_point = 0;

void loop()
{
    float Distance = sensor.getDistance();
    Serial.printf("Distance: %.2fmm\r\n", Distance);
    M5.Display.fillScreen(TFT_BLACK);
    M5.Display.drawString(String(Distance) + "mm", M5.Display.width() / 2, M5.Display.height() / 2);
    delay(100);
}

3. Compilation and Upload

    1. Download Mode: Before uploading the program, different devices require entering download mode. This step may vary depending on the main control device. For details, please refer to the list of device programming download tutorials at the bottom of the Arduino IDE Getting Started Tutorial .
  • For CoreS3, press and hold the reset button (for about 2 seconds) until the internal green LED lights up, then release; the device will have entered download mode and is ready for programming.

    1. Select the device port, click the compile and upload button at the upper left corner of the Arduino IDE, and wait until the program finishes compiling and uploading to the device.

4. Ultrasonic Distance Measurement

On This Page