Lesson 9 Ultrasonic Distance Measurement

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp


In this lesson, we will use an ultrasonic module to measure the distance from an obstacle.


– 1*Raspberry Pi

– 1*Breadboard

– 1*Network cable (or USB wireless network adapter)

– 2*Resistor (220Ω)

– 1*Resistor (1kΩ)

– 1*Ultrasonic module

– Several jumper wires

Experimental Principle

This sensor works by sending a sound wave out and calculating the time it takes for the sound wave to get back to the ultrasonic sensor. By doing this, it can tell us how far away an obstacle is to the ultrasonic.

Experimental Procedures

Step 1: Connect the circuit

Step 2: Edit and save the code(see path/Rpi_ultraKit /09_ultra/ultra.c)

Step 3: Compile the code

gcc  ultra.c  -lwiringPi

Step 4: Run the program


Place some obstacles like a booklet over the sensor and then you will see the distance between the obstacle and the ultrasonic display on the screen.


#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>

#define Trig    4
#define Echo    5

void ultraInit(void)
 pinMode(Echo, INPUT);
 pinMode(Trig, OUTPUT);

float disMeasure(void)
 struct timeval tv1;
 struct timeval tv2;
 long start, stop;
    float dis;

 digitalWrite(Trig, LOW);

 digitalWrite(Trig, HIGH);
 digitalWrite(Trig, LOW);
 while(!(digitalRead(Echo) == 1));
 gettimeofday(&tv1, NULL);

 while(!(digitalRead(Echo) == 0));
 gettimeofday(&tv2, NULL);

 start = tv1.tv_sec * 1000000 + tv1.tv_usec;
 stop  = tv2.tv_sec * 1000000 + tv2.tv_usec;

 dis = (float)(stop - start) / 1000000 * 34000 / 2;
 //dis = (stop - start) * 34000 / 1000000 / 2;

 return dis;

int main(void)
 float dis;

 if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
  printf("setup wiringPi failed !");
  return 1;

  dis = disMeasure();
  printf("distance = %0.2f cm\n",dis);

 return 0;