Rudraksh Sharma
Published

Interface Ultrasonic Sound sensor with Arduino UNO R3/R4

This Guide demonstrates how you can interface your HC-SR04 Ultrasonic Sound sensor with arduino UNO R3/R4. Code Explained as well!

BeginnerFull instructions provided3,366
Interface Ultrasonic Sound sensor with Arduino UNO R3/R4

Things used in this project

Hardware components

Male to female wires
×1
Arduino UNO
Arduino UNO
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
I2C LCD display
×1

Software apps and online services

Arduino IDE

Story

Read more

Schematics

I2C LCD with Arduino Connection

You can see this picture and can connect LCD with Arduino and also connect ultrasonic sensor as given in the image

By this you can connect Ultrasonic sensor with arduino and also connect LCD with Arduino!

Connect your sensor with Arduino and you can see the layout on your I2C LCD screen

Code

Here comes the hero of our project! THE CODE!

C/C++
Each Line is explained with comments on side. Go through it.
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 20 column and 4 rows

int trigPin = 9;    // Sensor Trigger pin, The sensor activates its Ultrasonic sound transmitter as soon as it receives pulse on this pin.
int echoPin = 8;    // Sensor Echo pin, The sensor continuously sends back a pulse to arduino as long as it receives back the ultrasonic sound wave. 

float duration, distance_cm; //Two variables To store duration for which we receive the pulse of echo pin, and distance we calculate based on sound speed and that duration.

void setup() {
  lcd.init();               // initialize the lcd
  lcd.backlight();
  pinMode(trigPin, OUTPUT); // config trigger pin to output mode
  pinMode(echoPin, INPUT); // config echo pin to input mode
}

void loop() {
  // generate 10-microseconds "pulse" to TRIG pin
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // measure duration of pulse from ECHO pin (In microseconds!!)
  duration = pulseIn(echoPin, HIGH);

  // calculate the distance
  distance_cm = 0.01732 * duration; //This 0.01732 is a constant calculated using this: distance = (speed of sound X time)/2, for 25 celcius room temperature. For temperature 35 celcius, its 0.01762, for 45 celcius surrounding temp, its 0.01792
  

  lcd.setCursor(0, 0);
  lcd.print("DISTANCE IN CM-");
  lcd.setCursor(0, 1);
  lcd.print(distance_cm);

  delay(10); //refresh rate

}
//Got a doubt or recommendation?? ask in comments...
  

Credits

Rudraksh Sharma
4 projects • 1 follower

Comments