Distance meter using PIC16F887 and HC-SR04 ultrasonic sensor

This topic shows how to make a simple distance meter using PIC16F887 microcontroller and HC-SR04 ultrasonic sensor.
The HC-SR04 ultrasonic sensor can measure distances form 2cm to 400cm with an accuracy of 3mm. This sensor module includes ultrasonic transmitter, ultrasonic receiver and control circuit.
The HC-SR04 ultrasonic sensor has 4 pins as shown below where:
VCC : Positive power supply (+5V)
Trig : Trigger input pin
Echo : Echo output pin
GND : Ground (0V)HC-SR04 Ultrasonic sensorHC-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 (340M/S) / 2.

HC-SR04 Ultrasonic sensor signals

Hardware Required:

  • PIC16F887 microcontroller
  • HC-SR04 ultrasonic sensor
  • 16×2 LCD screen
  • 10K variable resistor
  • +5V source
  • Breadboard
  • Jumper Wires

Distance meter using PIC16F887 and HC-SR04 ultrasonic sensor circuit: 

PIC16F887 HC-SR04 distance meter circuit

In this project the PIC16F887 MCU runs with its internal oscillator and MCLR pin function is disabled.

Distance meter using PIC16F887 and HC-SR04 ultrasonic sensor C code:
The C code below was tested with CCS C compiler version 5.051.
The PIC16F887 runs with its internal oscillator @ 8MHz.
Basically I used Timer1 module to measure the pulse widths which comes from the Echo pin of the HC-SR04 sensor, the width of the pulse is related to the distance. Timer1 is configured to increment every 1us (prescaler = 2):
SETUP_TIMER_1(T1_INTERNAL | T1_DIV_BY_2);

First of all the MCU sends a pulse of 10 us to the sensor via pin RB1 which is the trigger pin of the sensor, then the MCU waits until the sensor raises its Echo pin (function wait_sensor() ). If the waiting time is higher than 990 us ==> time out and the function wait_sensor() returns 0.
if the function wait_sensor() returned 1, the microcontroller starts measuring the width of the Echo pin pulse (in us) using the function get_distance(), if the time > 24990 (distance > 400 cm) ==> out of range, otherwise the measured time will be converted to distance (in cm) by dividing it by 58.
No interrupt is used in this example.
The complete C code is below.

PIC16F887 and HC-SR04 ultrasonic sensor circuit

Leave a Reply

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