Getting started with Ultrasonic Proximity Sensor HC–SR04

Getting started with Ultrasonic Proximity Sensor HC–SR04

In this article I will be showing you how to interface Ultrasonic Proximity sensor (also know as distance sensor) HC-SR04 with Arduino and will be discussing the working of the sensor and how to write program for that.

Gather the components

  • Ultrasonic Proximity Sensor HC-SR04
  • Arduino compatible Board
  • Breadboard and Some jumper cable

What is Proximity Sensor and How does it work 🙄?

The HC-SR04 sensor uses SONAR (SOund Navigation And Ranging) to find objects in front of it. Like the bat emits ultrasonic waves. The emitted sound waves travel through the air and bounce back if they come in contact with any object. and the receiver captures the sound wave.

The time between the transmission and reception is used to calculate the distance to the object. and we know the speed of sound is around 343 m/s or 0.034 cm/µs at 20°C

Speed = Distance/ Time

Distance = Speed x Time

Here the duration is the time interval between sending and receiving the sound waves. But if we multiple that duration we won’t get the correct distance because the distance sound travelled will be twice. (from the transmitter to object + from object to receiver. ) So we need to divide the result by 2.
So the final equation will be,

Distances = Speed of sound in air (cm/µs) x [Time(µs) / 2]

Distance = 0.034 x Time / 2

Pin Description

  • VCC : +5v
  • TRIG : Trigger, Receiver []INPUT]
  • ECHO : Echo Transmitter [OUTPUT]
  • GND : Ground

Specifications and features

  • Input Voltage: 5v
  • Quiescent Current: 2mA
  • Working Current: 15mA
  • Max Range: 400cm.
  • Min Range: 2cm.
  • Working Frequency: 40Hz.
  • Sensing Angle: 30°
  • Angle of Effect: 15°

Interfacing with Arduino

Follow the below schematic to wire up the HC-SR04 with Arduino

  • VCC to 5v of Arduino
  • GND to GND
  • TRIG to Digital Pin 2
  • ECHO to Digital Pin 3

Programming

You can write program for this sensor in two ways 1. Without using any additional libraries 2. Using pre-existing Library.
I will be discussing both methods.

Method 1 : Without using Library

/*
  Example code for HC-SR04 ultrasonic Proximity (distance)
  sensor with Arduino without using library required
  Blog : https://www.mgprojecthub.com

  Circuit
   Connect TRIG pin to digital pin 2 of Arduino
   Connect ECHO pin to digital pin 3
   VCC to 5v
   Gnd to Gnd
*/

#define TrigPin 2    // Trigger Pin to Digital pin 2
#define EchoPin 3    // Echo Pin to Digital pin 3

long duration, distance_cm;

void setup() {
  //Serial Port begin
  Serial.begin (9600);
  pinMode(EchoPin, INPUT);      //Setting EchoPin as INPUT pin
  pinMode(TrigPin, OUTPUT);     //Setting TrigPin as OUTPUT pin
}

void loop() {
  // A LOW pulse is given at first to ensure a clean HIGH pulse:
  digitalWrite(TrigPin, LOW);
  delayMicroseconds(5);
  // The TrigPin is set to HIGH pulse for 10us (microseconds.)
  digitalWrite(TrigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin, LOW);

  // Read the EchoPin
  // PulseIn return the length of pulse in microsecond.
  duration = pulseIn(EchoPin, HIGH);

  // Convert the time into a distance
  distance_cm = duration * 0.034 / 2;

  Serial.print(distance_cm);
  Serial.print("cm ");
  Serial.println();

  delay(100)

How does the code work?

#define TrigPin 2    // Trigger Pin to Digital pin 2
#define EchoPin 3    // Echo Pin to Digital pin 3

Here the two pins TrigPin , EchoPin are defined and the digital pin is assigned. #define is used to give a name to a constant value before the program is compiled.

long duration, distance_cm;

Define 2 variable duration,<strong> </strong>distance_cm.<strong> </strong>duration<strong> </strong>stores the time interval between sending and receiving the ultrasonic wave.
distance_cm stores calculated distance in cm.

void setup() {
  //Serial Port begin
  Serial.begin (9600);
  pinMode(EchoPin, INPUT);      //Setting EchoPin as INPUT pin
  pinMode(TrigPin, OUTPUT);     //Setting TrigPin as OUTPUT pin
}

This part of the code executes only once. First, we Initialize serial communication at a baud rate of 9600 and assign EchoPin as INPUT pin and TrigPin as OUTPUT pin.

void loop() {
  // A LOW pulse is given at first to ensure a clean HIGH pulse:
  digitalWrite(TrigPin, LOW);
  delayMicroseconds(5);
  // The TrigPin is set to HIGH pulse for 10us (microseconds.)
  digitalWrite(TrigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin, LOW);

Inside loop(), Initially TrigPin is made LOW for just 5 µs just to get clear the trigPin and get rid of junk values
Then TrigPin is made HIGH for 10µs.

  // Read the EchoPin
  // PulseIn return the length of pulse in microsecond. 
  duration = pulseIn(EchoPin, HIGH);

The length of pulse sent by EchoPin is found by using pulseIn() function .It returns the length of pulse.

  // Convert the time into a distance
  distance_cm = duration*0.034/2;

Distance in cm is calculated using the equation. we discussed earlier.

  Serial.print(distance_cm);
  Serial.print("cm ");
  Serial.println();
  
  delay(100);
}

Here the stored distance in cm and Inch are printed in the serial monitor .

Method 1 : Without using Library

To make coding more ease we will be using Libraries. You can see the difference by looking at the number of lines, between the two codes. The code using the library is small compared to other one right?
For the HC-SR04 sensor, there is a great library written by Tim Eckel called NewPing. You can download the latest version from here. or from the Arduino library manager.

Sketch > Include Library > Manage Libraries or press Ctrl+Shift+I

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

Leave a Reply

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