Using Ultrasonic Sensor HC-SR04 with PIC16F877

This post is about building a basic distance meter with ultrasonic HC-SR04 sensor and PIC micro controller. For Arduino version click here. Raspberry Pi variant is also available at this link The interface is very simple and does 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. A compiled HEX file can be downloaded at this link. You can purchase a source code written in Assembly language to get a full control of this circuit behavior and functionality  . Timer 1 interrupt was used 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 SchematicMax 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.