PIC16F84A with HC-SR04 ultrasonic sensor example – CCS C

Interfacing PIC16F84A with HC-SR04 Ultrasonic Sensor

This post shows how to interface PIC16F84A microcontroller with HC-SR04 ultrasonic sensor and make a distance meter.
The ultrasonic sensor HC-SR04 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 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. You 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 * velocity (340M/S) / 2.

HC-SR04 Ultrasonic sensor signals

PIC16F84A with HC-SR04 ultrasonic sensor example circuit:
The following circuit schematic show he connection between the microcontroller PIC16F84A and the HC-SR04 sensor.

PIC16F84A HC-SR04 ultrasonic sensor circuit

The 1602 LCD is used to display the measured distance in cm.

PIC16F84A with HC-SR04 ultrasonic sensor example CCS C code:
Here is the C code used for this project.
Timer0 is configured to increment by 1 every 1 us ( with mcu frequency of 8MHz). Timer0 is used the measure the pulse widths come from Echo pin of the HC-SR04 sensor.
Because of the Timer0 is an 8-bit timer only I used its interrupt (Timer0 interrupt) to count times more than 256us, and for that purpose I added a variable called count. So the pulse time of the Echo pin equals to :
count * 256 + get_timer0()

Example Video:

Leave a Reply

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