HC-SR04 Ultrasonic Sensor on PIC

Hcsr04 Banner
HC-SR04 is a very common ultrasonic sensor and it is normally found in Arduino kits or projects. The library for this sensor is widely available for the Arduino platform but not for PIC.

IMG_1546copy

I’ve been asked to help to write a simple PIC code to interface with the ultrasonic sensor.

IMG_1543copy

It’s actually very simple by referring to the timing diagram.

hc-sr04-timing-diagram

Connect the Trigger pin to an output and the Echo pin to an input. Just output a 10us pulse on the trigger pin and wait for the feedback on the echo pin.

The pulse width of the echo pin will determine the distance. The longer the pulse width, the further the object is. I’m using the PIC’s built-in timer to time the duration of the pulse width.

The code is written for the Hi-Tech C Lite compiler on MPLAB X.

mplabx_code

The schematic.

PIC_Ultrasonic_schemcopy

Here is a video demo 🙂

Download