Free Shipping over ₹1199

ESP32-S3 Ultrasonic Sensor with Arduino IDE

Introduction

This tutorial guides you through using an ultrasonic sonar sensor with the ESP32-S3 to measure distances.
Ultrasonic sensors work by emitting sound waves and measuring the time it takes for the echo to return, enabling accurate distance measurement and obstacle detection.

Required Components

  • ESP32-S3 Board
  • Ultrasonic sensor 
  • Jumper Wires
  • Breadboard (optional)

Pinout

Circuit Diagram / Wiring

  • ULTRASONIC SENSOR VCC → 3.3V (ESP32-S3)
  • ULTRASONIC SENSOR GND → GND (ESP32-S3)
  • ULTRASONIC SENSOR TRIG → Pin 5 (ESP32-S3)
  • ULTRASONIC SENSOR ECHO → Pin 18 (ESP32-S3)

Code / Programming

/*
  Filename: ol_ultrasonic_distance.ino
  Description: Measure distance using HC-SR04 ultrasonic sensor and ESP32-S3
  Author: www.oceanlabz.in
  Modification: 1/4/2025
*/
 
#define TRIG_PIN  5    // GPIO pin connected to TRIG of HC-SR04
#define ECHO_PIN  18   // GPIO pin connected to ECHO of HC-SR04
 
long duration;
float distanceCm;
 
void setup() {
  Serial.begin(115200);        // Initialize serial communication
  pinMode(TRIG_PIN, OUTPUT);   // Set TRIG pin as output
  pinMode(ECHO_PIN, INPUT);    // Set ECHO pin as input
}
 
void loop() {
  // Send a 10µs pulse to trigger pin
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
 
  // Read echo time
  duration = pulseIn(ECHO_PIN, HIGH);
 
  // Convert time to distance (speed of sound = 0.034 cm/µs)
  distanceCm = duration * 0.034 / 2;
 
  // Display distance on serial monitor
  Serial.print("Distance: ");
  Serial.print(distanceCm);
  Serial.println(" cm");
 
  delay(500);  // Wait half a second before next reading
}

Explanation

  • The HC-SR04 sensor emits ultrasonic pulses using the Trig pin and listens for the echo using the Echo pin.
  • The ESP32-S3 measures the time taken for the echo to return using pulseIn() to calculate the distance.
  • This allows accurate, non-contact distance measurement ideal for obstacle detection and automation.

Troubleshooting

  • Make sure Trig is set as OUTPUT and Echo as INPUT, and both are connected to valid GPIO pins.
  • Use a 5V power supply for the sensor, but ensure Echo pin is level-shifted or tolerable by ESP32-S3 (consider using a resistor divider).
  • If distance always reads zero or unstable, check for loose wires, or poor power supply, and keep sensor free from obstructions.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Need Help?