Using Ultrasonic Sensor HC-SR04 with PIC16F877

Using Ultrasonic Sensor HC-SR04 with PIC16F877 Featured Image

This post is about building a simple distance meter with ultrasonic HC-SR04 sensor and PIC micro controller. The interface is very simple and doesn’t not require too many commands or complex software. In order to measure the distance you’ll need to execute the following tasks: 1-Send 10 us pulse on Trigger line. 2-Wait for returned Echo and start the timer as soon as the echo line goes High. 3-Count the duration of the Echo pulse. Each increment of the timer equals 1 cm. The code was written in Assembly language and uses Timer 1 interrupt to measure the length of the echo pulse from the object and to show it on 2×16 LCD Display. The distance is measured in centimeter but can be easily converted to any other units. The design schematic is shown next.

Using Ultrasonic Sensor with PIC16F877 Schematic


Max range is 4 meters as specified by ultrasonic module datasheet. 20Mhz oscillator was used and all of the timing functions are derived from this clock according to the following equation: Td = 200ns*(2^16-TMR1H:TMR1L)*PS. Where Td is a duty cycle of every Timer 1 count and PS is a prescaller value. Using different OSC will require a new instruction cycle calculation instead of 200ns = (1/Fosc) * 4. Smaller microcontrollers like PIC16F88 or PIC16F876 should also support this simple design as only 12 I/O were used. Also using 4 bit LCD interface instead of current 8 will further decrease the pin count. Source code can be downloaded here.

Posted in PIC16F87X Projects
Make a Donation Button