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.
#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.