Cirkit Designer Logo
Cirkit Designer
Your all-in-one circuit design IDE
Home / 
Project Documentation

ESP32-Based Ultrasonic Distance Sensor with LED Indicator

Image of ESP32-Based Ultrasonic Distance Sensor with LED Indicator

Circuit Documentation

Summary

This circuit integrates an ESP32 microcontroller with an HC-SR04 Ultrasonic Sensor and a red LED. The ESP32 is used to control the sensor and the LED based on the distance measurements obtained from the ultrasonic sensor. When an object is detected within a 10 cm range, the red LED is turned on as an indicator.

Component List

ESP32 (30 pin)

  • Description: A microcontroller with Wi-Fi and Bluetooth capabilities, featuring a wide range of GPIO pins.
  • Pins: EN, VP, VN, D34, D35, D32, D33, D25, D26, D27, D14, D12, D13, GND, Vin, D23, D22, TX0, RX0, D21, D19, D18, D5, TX2, RX2, D4, D2, D15, 3V3

HC-SR04 Ultrasonic Sensor

  • Description: A sensor that measures distance by emitting ultrasonic waves and measuring the time taken for the echo to return.
  • Pins: VCC, TRIG, ECHO, GND

LED: Two Pin (red)

  • Description: A simple red LED used for indication purposes.
  • Pins: cathode, anode

Wiring Details

ESP32 (30 pin)

  • GND connected to:
    • HC-SR04 Ultrasonic Sensor GND
    • LED cathode
  • Vin connected to HC-SR04 Ultrasonic Sensor VCC
  • D23 connected to HC-SR04 Ultrasonic Sensor ECHO
  • D22 connected to HC-SR04 Ultrasonic Sensor TRIG
  • D2 connected to LED anode

HC-SR04 Ultrasonic Sensor

  • VCC connected to ESP32 Vin
  • TRIG connected to ESP32 D22
  • ECHO connected to ESP32 D23
  • GND connected to ESP32 GND

LED: Two Pin (red)

  • cathode connected to ESP32 GND
  • anode connected to ESP32 D2

Documented Code

#include <NewPing.h>

// Define sensor pins
#define TRIGGER_PIN 22
#define ECHO_PIN 23

// Define maximum distance to measure (in centimeters)
#define MAX_DISTANCE 200

int red=2;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  pinMode(red,OUTPUT);
}

void loop() {
  // Measure distance
  int distance = sonar.ping_cm();

  // Logic for LED
  if(distance < 10) {          // If condition
    digitalWrite(red,HIGH);    // Turn on LED if object is closer than 10 cm
  } else {
    digitalWrite(red,LOW);     // Turn off LED otherwise
  }

  // Print distance to serial monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Add a delay to avoid overwhelming the serial monitor
  delay(100);
}

This code is designed to run on the ESP32 microcontroller. It initializes the HC-SR04 Ultrasonic Sensor and the red LED. The loop function continuously measures the distance using the ultrasonic sensor. If an object is detected within 10 cm, the red LED is turned on. The measured distance is also printed to the serial monitor every 100 milliseconds.