Measure Distance using Ultrasonic Sensor HC – SR04 | Pi4J | JAVA | Raspberry Pi


HC - SR04This is a simple tutorial showing how to interface HC – SR04  ultrasonic ranging module with Raspberry Pi to measure distance using JAVA. Ultrasonic ranging module HC – SR04 provides 2cm – 400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules include ultrasonic transmitters, receiver and control circuit. The basic principle of work:

(1) Using IO trigger for at least 10us high-level signal,
(2) The Module automatically sends eight 40 kHz and detect whether there is a
pulse signal back.
(3) IF the signal back, through high level, time of high output IO duration is the time from sending ultrasonic to returning.

Links :
Java Application on Pi Playlist:

Github Repository :
Schematic :
Pi4J GPIO Numbering :
Download Pi4J Library :
Code :


public class Main {
  //GPIO Pins
  private static GpioPinDigitalOutput sensorTriggerPin ;
  private static GpioPinDigitalInput sensorEchoPin ;
  final static GpioController gpio = GpioFactory.getInstance();
  public static void main(String [] args) throws InterruptedException{
    new Main().run();
  public void run() throws InterruptedException{
    sensorTriggerPin =  gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00); // Trigger pin as OUTPUT
    sensorEchoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02,PinPullResistance.PULL_DOWN); // Echo pin as INPUT

      try {
      sensorTriggerPin.high(); // Make trigger pin HIGH
      Thread.sleep((long) 0.01);// Delay for 10 microseconds
      sensorTriggerPin.low(); //Make trigger pin LOW
      while(sensorEchoPin.isLow()){ //Wait until the ECHO pin gets HIGH
      long startTime= System.nanoTime(); // Store the surrent time to calculate ECHO pin HIGH time.
      while(sensorEchoPin.isHigh()){ //Wait until the ECHO pin gets LOW
      long endTime= System.nanoTime(); // Store the echo pin HIGH end time to calculate ECHO pin HIGH time.
      System.out.println("Distance :"+((((endTime-startTime)/1e3)/2) / 29.1) +" cm"); //Printing out the distance in cm  
    } catch (InterruptedException e) {


Buy Sensor: (India)
Buy Raspberry Pi: (India)

Subscribe YouTube :

Guys Subscribe to my channel for latest contents into your inbox.
Support me to keep going.

Support me on Patreon :

Website :
Twitter :
YouTube :
Instagram :

Related posts

Leave a Comment