BeginnerArduino about 45 min
Ultrasonic Distance Meter
Measure distance with an HC-SR04 and show it on a 16x2 I2C LCD. A perfect first sensor project.
Steps
Wire the sensor
HC-SR04: VCC to 5V, GND to GND, Trig to D9, Echo to D10.
Wire the LCD
I2C LCD: VCC to 5V, GND to GND, SDA to A4, SCL to A5 (Nano / UNO).
Install the library
In the Arduino IDE install the LiquidCrystal_I2C library.
Upload
Upload the sketch. If the screen is blank, adjust the contrast screw on the backpack or change the address to 0x3F.
Code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int TRIG = 9, ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
lcd.init(); lcd.backlight();
}
void loop() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000);
lcd.clear();
lcd.setCursor(0, 0); lcd.print("Distance:");
lcd.setCursor(0, 1);
if (us == 0) lcd.print("Out of range");
else { lcd.print(us * 0.0343 / 2, 1); lcd.print(" cm"); }
delay(300);
}