Raspberry Pi & Ultrasonic Module - Calculating Distance in C

In this brief article I will be posting the C code I used to measure the distance between the Raspberry Pi and any object in front of the HC-SR04 module. I used this article to show me how to wire up the ultrasonic module using a breadboard. You will also need to download and install wiringPi from the wiringPi website, full details here.

The code is based on the Python script from this article written by Matt Hawkins.

Measures the distance between the Pi and an object using an ultrasonic module
Original source by Matt Hawkins (09/01/2013, http://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-1/) in Python
Written in C by Lewis Dale (09/04/2014, http://blog.lewisdale.co.uk)

WiringPi Library by Gordon Henderson (http://wiringpi.com)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <wiringPi.h>
/*Define the GPIO pins using WiringPi Pin Numbers*/
#define GPIO_TRIGGER 4
#define GPIO_ECHO 5

int main()
/*Set up the Pi for GIPO*/
wiringPiSetup ();
printf("Ultrasonic Measurement ");
double distance;
int i;
distance = 0;

/*Loop 5 times for greater accuracy*/
unsigned int start, end;
double total;

/*Set the trig pin to output, and the echo pin to input*/

/*Make sure the module is not outputting*/
digitalWrite(GPIO_TRIGGER, LOW);
/*500ms delay to allow the module to settle*/
/*Send a 10us pulse to trigger*/
delayMicroseconds (10);

start = millis();

while(digitalRead(GPIO_ECHO) == 0)
start = millis();
while(digitalRead(GPIO_ECHO) == 1)
end = millis();

/*Calculate pulse length and convert to seconds*/
total = (double) (end-start) / 1000;

/*Distance travelled is time * speed of sound (cm/s)
Halved as we only want distance to object*/

total = total * 34300;
total = total / 2;
/*Append to total distance*/
distance += (double) total;

/*Calculate mean distance*/
distance = distance/5;
printf("Distance: %f ",distance);

Compilation instructions

To compile the script, save it as usonic.c and compile using gcc, including the wiringPi library:

gcc -Wall -o usonic usonic.c -lwiringPi