An ultra-sonic distance measurement module is very popular for electronic hobbyists, especially in vehicle robot. The HC-SR04 module is widely available at very low cost. It use the ultra-sonic sound transmitting/receiving in the air to get the distance of any detected object. It communication interface is very simple.
Program running on breadboard |
In this example, I make a typical distance measurement using the HC-SR04 module with Arduino Uno. I added an I2C to LCD converter module to get a easily circuit wirings. The distance will show in centimeters. The HC-SR04 has only four pins:
- VCC
- Trigger
- Echo
- and GND
HC-SR04 an from Ali-Express store |
Trigger pin is the input pin that keep listening to the controller for triggering the distance finding. Echo pin is the output pin that output a high logic signal to the controller. Its output duration in micro-seconds relate to the detected distance in centimeters. We can see its specification below.
Electric Parameter |
There are only two signal pins - trigger , and echo pin.
Timing diagram |
The Arduino can calculate the distance in centimeter as follow.
distance = duration (in microseconds)/58
or distance = duration * 340 /2
It schematic consists of a little wiring lines.
Wiring diagram |
Source Code:
//Two-Wire #include <Wire.h> #include <LiquidCrystal_I2C.h> //LCD Setting, PCF8574T address is 0x27, 16x2 LiquidCrystal_I2C lcd(0x27,16,2); #define triggerPin A0 #define echoPin A1 void setup(){ //Initialize the LCD lcd.init(); //Turn on the back light lcd.backlight(); //Print some information lcd.print("Arduino Distance"); lcd.setCursor(0,1); lcd.print(" Measurement "); delay(3000); lcd.clear(); lcd.home(); lcd.print("Distance:"); //HC-SR04 Pins Setting pinMode(triggerPin,OUTPUT); pinMode(echoPin,INPUT); } void loop(){ //Activate the distance sensor digitalWrite(triggerPin,HIGH); delayMicroseconds(10); digitalWrite(triggerPin,LOW); //Get the distance, time out is 60ms unsigned int distanceMicro = pulseIn(echoPin,HIGH,60000); //Calculate the distance in cm distanceMicro/=58; lcd.setCursor(0,1); if(distanceMicro>400) lcd.print("Invalid "); else lcd.print(String(distanceMicro,DEC)+"cm "); delay(1500); }
Click here to download this example in zip file format.