Interfacing HC-SR04 Ultrasonic Sensor with ESP32

Interfacing an HC-SR04 ultrasonic sensor with an ESP32 microcontroller opens up a world of possibilities for projects ranging from distance measurement to object detection. In this tutorial, I’ll guide you through the process step by step.

Required Components:

    1. ESP32 development board
    2. HC-SR04 ultrasonic sensor
    3. Breadboard
    4. Jumper wires
    5. USB cable for programming

Wiring Connections:

Connect the HC-SR04 sensor to the ESP32 as follows:

    • VCC pin of HC-SR04 to 5V pin on ESP32
    • GND pin of HC-SR04 to GND pin on ESP32
    • Trig pin of HC-SR04 to any GPIO pin on ESP32 (e.g., GPIO 19)
    • Echo pin of HC-SR04 to any GPIO pin on ESP32 (e.g., GPIO 18)

Installing ESP32 Board in Arduino IDE:

    1. Open Arduino IDE 2.
    2. Connect your ESP32 board to your computer via USB.
    3. Select the correct board (ESP32 Dev Module) and port in IDE.
    4. Copy and paste the code into the Arduino IDE.

Code:

// Define pins
const int trigPin = 19;
const int echoPin = 18;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Configure pins
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // Send a short pulse to trigger the sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the duration of the echo pulse
  long duration = pulseIn(echoPin, HIGH);

  // Calculate distance in centimeters
  float distance_cm = duration * 0.034 / 2;

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

  // Delay before next measurement
  delay(1000);
}

Uploading and Testing:

    1. Click on the Upload button to upload the code to your ESP32.
    2. Open the Serial Monitor (Tools > Serial Monitor) to view the distance measurements.

 

With this tutorial, you should now be able to successfully interface an HC-SR04 ultrasonic sensor with an ESP32 microcontroller and start building your own projects!

Leave a Reply

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