Read Ultrasonic Sensor [HC-SR04] using Java — Raspberry Pi

Chandima Samarasinghe
2 min readApr 16, 2018

I am working on developing a Telepresence Robot Project these days which the core program is written using Java. I have used Raspberry Pi 3 Model B as the mainboard with Raspbian OS.

We have connected few ultrasonic sensors to the robot and had to write a Java class to interface the HC-SR04 ultrasonic sensor with the raspberry pi using the pi4j library to controll the GPIO pins of the raspberry pi. (Read http://pi4j.com/ to learn how to setup that library)

For the following test program, I have used GPIO pin 0 as the ECHO PIN and GPIO pin 1 as the TRIG PIN.

Test Program

public class Test_Ultrasonic{
public static void main(String[] args) throws Exception{
PiJavaUltrasonic sonic=new PiJavaUltrasonic(
0,//ECO PIN (physical 11)
1,//TRIG PIN (pysical 22)
1000,//REJECTION_START ; long (nano seconds)
23529411 //REJECTION_TIME ; long (nano seconds)
);
System.out.println("Start");
while(true){
System.out.println("distance "+sonic.getDistance()+"mm");
Thread.sleep(1000); //1s
}
}

}

The third argument is REJECTION_START (long). To explain you what is the purpose of this argument, let me breifly explain you how we measure a distance from the HC-SR04 module. In order to get a distance reading from the ultrasonic sensor we need to keep the TRIG pin high state for 10us. If the TRIG pin kept high state for 10us, the sensor generate 8 cycle ultrasonic burst and put the ECHO pin state to high. The ECHO pin state change to low state once the echo reaches the sensor. Some times for various reasons eventhough we give signal to tigger the sensor it may not trigger that properly. In that case we would trigger that and wait so long and read incorrect reading. That is way i introduced the REJECTION_START parameter. What it will do is, after sending the trigger signal it will wait for REJECTION_START number of nano seconds and see whether the sensor identified that as a real trigger. If not, reading return you a negative value.

The fourth arugument is the REJECTION_TIME (long). Practically HC-SR04 has a maximum distance limit. In order to get accurate results we need to make sure our sensor reads and returns the mesurement if only whithin that range. So looking at the datasheets of your sensor, and considering about your need calculate a maximum allowable time for the echoed signal and put that value in nano seconds here.

See The GitHub For the Codes :)

--

--