Arduino with HC-SR04 ultrasonic sensor

Distance meter using Arduino and HC-SR04

This post shows a simple interfacing of an Arduino UNO board with HC-SR04 ultrasonic sensor in order to build a distance meter with a range up to 4 meters.

The HC-SR04 ultrasonic sensor module can measure distances form 2 cm to 400 cm (4 m) with an accuracy of 3 mm. The HC-SR04 module includes ultrasonic transmitter, ultrasonic receiver and control circuit.
The HC-SR04 ultrasonic sensor module has 4 pins as shown in the image below where:
VCC : Positive power supply (+5V)
Trig : Trigger input pin
Echo : Echo output pin
GND : Ground (0V)

HC-SR04 Ultrasonic sensor

HC-SR04 ultrasonic sensor timing diagram:
The timing diagram of the HC-SR04 ultrasonic sensor is shown below.
First we have to supply the sensor trigger pin with a pulse of 10µs and the sensor will automatically send 8 cycles burst of ultrasound at 40 kHz and raise its echo pin. The Echo is a distance object that is pulse width and the range in proportion. We can calculate the range through the time interval between sending trigger signal and receiving echo signal. Formula: uS / 58 = centimeters or uS / 148 =inch; or:
the range = high level time * sound velocity / 2 . Sound velocity = 340M/S.

HC-SR04 Ultrasonic sensor signals

Hardware Required: 

  • Arduino board
  • HC-SR04 ultrasonic sensor module
  • 16×2 LCD screen
  • 10K variable resistor
  • 330 ohm resistor
  • Breadboard
  • Jumper Wires

The circuit:
Example circuit schematic diagram is shown below.

Arduino HC-SR04 ultrasonic sensor circuit

The Arduino code:
First of all the Arduino sends a pulse of 10 us to the sensor via trigger_pin which is the trigger pin of the sensor, then the Arduino waits until the sensor raises its Echo pin. For this I used the function        duration = pulseIn(echo_pin, HIGH). The pulsIn() function waits for the echo_pin to go high, starts timing, then waits for the pin to go low and stops timing. Returns the length of the pulse in microseconds. Gives up and returns 0 if no pulse starts within default timeout which is 1 second.

So, if duration is equal to zero the LCD will print Time Out
and if duration is not zero the distance will be calculated using the function distance = duration / 58.
Now if the distance is greater than 400 cm the LCD will print Out of Range. Otherwise the LCD will print the measured distance in cm.
The full code is below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.