Ultrasonic Sensor HC-SR04 with Arduino


The HC-SR04 ultrasonic sensor is a popular choice among hobbyists and professionals alike for distance measurement applications. When combined with an Arduino microcontroller, it becomes a versatile tool for various projects, such as robotics, security systems, and smart devices.

Materials Needed

  1. Arduino Mega 2560 R3 (or any other Arduino board)
  2. Breadboard
  3. HC-SR04 ultrasonic sensor
  4. Jumper wires
  5. USB cable to connect Arduino to computer
  6. Arduino Web Editor (online) or Arduino IDE software (offline)

Ultrasonic Sensor HC-SR04 with Arduino Circuit

The HC-SR04 sensor works on the principle of ultrasonic sound waves. It emits an ultrasonic pulse and then listens for its reflection. By measuring the time taken for the pulse to travel to an object and back, it can calculate the distance. The fundamental of this sensor can be referred through this link: How does the HC-SR04 Ultrasonic Sensor work?

Ultrasonic Sensor HC-SR04 Pinout

Wiring Connections: Connect the pins to the Arduino as follows:

  • Connect VCC to 5V on Arduino.
  • Connect GND to GND on Arduino.
  • Connect Trig to a digital pin (e.g., pin 10) on Arduino.
  • Connect Echo to another digital pin (e.g., pin 9) on Arduino.
Ultrasonic Sensor HC-SR04 with Arduino Breadboard Diagram

Ultrasonic Sensor HC-SR04 with Arduino Programming

const int trigPin = 10;
const int echoPin = 9;

void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
int distance_cm = duration * 0.034 / 2;
Serial.print(“Distance: “);
Serial.print(distance_cm);
Serial.println(” cm”);
delay(1000);
}

Upload the code to your Arduino board. Open the serial monitor in the Arduino IDE (Tools -> Serial Monitor). You should see distance measurements in centimeters displayed in the serial monitor.

Coding with Serial Monitor

You can refine the code by adding error checking and filtering to improve measurement accuracy. Experiment with different triggering and sampling techniques for specific application requirements. Remember to handle the sensor carefully, as it’s sensitive to physical damage. With this setup, you can create a wide range of projects that involve distance sensing and automation.

Similar Posts

Leave a Reply

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