To interface an Ultrasonic sensor with an ESP32 and activate a buzzer when an object is detected within a certain range, you’ll need to connect the ultrasonic sensor (like HC-SR04) to the ESP32 and then use the sensor’s distance measurement to control the buzzer.
Hardware Setup
Components:
- ESP32 Board
- HC-SR04 Ultrasonic Sensor
- Buzzer
Connections:
- HC-SR04 Ultrasonic Sensor:
- VCC → 5V pin (if using 5V version) or 3.3V pin (if using a 3.3V compatible version)
- GND → GND pin
- TRIG → GPIO 23 (or another GPIO pin)
- ECHO → GPIO 22 (or another GPIO pin)
- Buzzer:
- GND → GND pin
- Positive Pin → GPIO 21 (or another GPIO pin)
Code:
Here’s an example code using the HC-SR04 ultrasonic sensor to measure the distance and trigger a buzzer if the distance is below a certain threshold:
#include <Arduino.h>
#define TRIG_PIN 23 // GPIO Pin for Trigger
#define ECHO_PIN 22 // GPIO Pin for Echo
#define BUZZER_PIN 21 // GPIO Pin for Buzzer
// Constants
const int THRESHOLD = 20; // Threshold distance in cm (for buzzer activation)
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Set up pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Ensure buzzer is off initially
digitalWrite(BUZZER_PIN, LOW);
}
void loop() {
// Trigger pulse to the Ultrasonic Sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the duration of the Echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
long distance = (duration / 2) / 29.1; // Speed of sound = 343 m/s = 29.1 microseconds per cm
// Output the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If the distance is below the threshold, activate the buzzer
if (distance < THRESHOLD) {
digitalWrite(BUZZER_PIN, HIGH); // Turn on buzzer
} else {
digitalWrite(BUZZER_PIN, LOW); // Turn off buzzer
}
// Wait a little before taking the next measurement
delay(500);
}
Explanation:
- TRIG_PIN (GPIO 23): Sends a pulse to the ultrasonic sensor to initiate a measurement.
- ECHO_PIN (GPIO 22): Receives the echo pulse after the sound wave reflects off an object.
- BUZZER_PIN (GPIO 21): Controls the buzzer, which will sound if the object is detected within the specified threshold distance.
- pulseIn(): This function measures the duration of the pulse on the Echo pin, which is then used to calculate the distance.
- Threshold Distance: If the distance measured by the ultrasonic sensor is less than the defined threshold (20 cm in this case), the buzzer will be activated.
Notes:
- Make sure the HC-SR04 sensor’s Echo pin is connected to a GPIO pin that can read the signal level.
- Adjust the
THRESHOLD
value as needed based on your application. - If your buzzer is active-low, you may need to invert the logic for turning it on/off (i.e., use
digitalWrite(BUZZER_PIN, LOW)
to activate it).