Pages

Tuesday, July 12, 2022

Arduino Uno and HC-SR04 Distance Measurement

 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.

Arduino Uno and Distance Measurement
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:

  1. VCC
  2. Trigger
  3. Echo
  4. and GND
Arduino Uno and Distance Measurement
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.

Arduino Uno and Distance Measurement
Electric Parameter

There are only two signal pins - trigger , and echo pin.

Arduino Uno and Distance Measurement
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.

Arduino Uno and Distance Measurement
Wiring diagram

Source Code:

  1. //Two-Wire
  2. #include <Wire.h>
  3. #include <LiquidCrystal_I2C.h>
  4.  
  5. //LCD Setting, PCF8574T address is 0x27, 16x2
  6. LiquidCrystal_I2C lcd(0x27,16,2);
  7.  
  8. #define triggerPin A0
  9. #define echoPin A1
  10.  
  11. void setup(){
  12. //Initialize the LCD
  13. lcd.init();
  14. //Turn on the back light
  15. lcd.backlight();
  16. //Print some information
  17. lcd.print("Arduino Distance");
  18. lcd.setCursor(0,1);
  19. lcd.print(" Measurement ");
  20. delay(3000);
  21. lcd.clear();
  22.  
  23. lcd.home();
  24. lcd.print("Distance:");
  25.  
  26. //HC-SR04 Pins Setting
  27. pinMode(triggerPin,OUTPUT);
  28. pinMode(echoPin,INPUT);
  29. }
  30.  
  31. void loop(){
  32. //Activate the distance sensor
  33. digitalWrite(triggerPin,HIGH);
  34. delayMicroseconds(10);
  35. digitalWrite(triggerPin,LOW);
  36.  
  37. //Get the distance, time out is 60ms
  38. unsigned int distanceMicro = pulseIn(echoPin,HIGH,60000);
  39.  
  40. //Calculate the distance in cm
  41. distanceMicro/=58;
  42.  
  43. lcd.setCursor(0,1);
  44. if(distanceMicro>400) lcd.print("Invalid ");
  45. else lcd.print(String(distanceMicro,DEC)+"cm ");
  46.  
  47. delay(1500);
  48. }
  49.  

Click here to download this example in zip file format.

No comments:

Post a Comment