Electronics

Ultrasonic Sensor HCSR04: A Guide to Using it with Arduino

Introduction

The HCSR04 Ultrasonic Sensor is a popular choice for distance measurement in various Arduino projects. It uses ultrasonic waves to detect objects and measure their distance accurately. In this blog post, we will guide you through the process of using the HCSR04 sensor with Arduino and provide you with a sample code to test its functionality.

Components Required

  • Arduino board (Uno, Nano, or any other compatible board)
  • HCSR04 Ultrasonic Sensor
  • Jumper wires

Wiring

Connect the HCSR04 sensor to the Arduino as follows:

  • VCC pin of the sensor to the 5V pin of the Arduino
  • GND pin of the sensor to the GND pin of the Arduino
  • Trig pin of the sensor to pin 2 of the Arduino
  • Echo pin of the sensor to pin 3 of the Arduino

Sample Code

// Include the Ultrasonic library
#include <Ultrasonic.h>

// Define the pins
#define TRIG_PIN 2
#define ECHO_PIN 3

// Create an instance of the Ultrasonic sensor
Ultrasonic ultrasonic(TRIG_PIN, ECHO_PIN);

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

void loop() {
  // Measure the distance in centimeters
  float distance = ultrasonic.read();

  // Print the distance
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Delay for 500 milliseconds
  delay(500);
}

Explanation

The sample code starts by including the Ultrasonic library, which provides functions to read the distance from the HCSR04 sensor. The TRIG_PIN and ECHO_PIN are defined as the trigger and echo pins connected to the Arduino. An instance of the Ultrasonic sensor is created using these pins.

In the setup function, the serial communication is initialized with a baud rate of 9600. This allows us to print the distance values to the serial monitor for debugging purposes.

The loop function is where the distance measurement takes place. The read function of the Ultrasonic sensor is called, which returns the distance in centimeters. The distance is then printed to the serial monitor using the Serial.print function.

Testing the Sensor

To test the HCSR04 sensor, upload the sample code to your Arduino board. Open the serial monitor in the Arduino IDE and set the baud rate to 9600. You should see the distance values being printed continuously.

Conclusion

The HCSR04 Ultrasonic Sensor is a versatile component that can be used in a wide range of Arduino projects. By following the wiring instructions and using the provided sample code, you can easily integrate the sensor into your own projects and start measuring distances accurately. Have fun experimenting with the HCSR04 sensor and exploring its potential!

Leave a Reply

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