In this Arduino tutorial I will show you how to use the HC-SR04 ultrasonic sensor and integrate it with an LCD display, so that it can display the distance between the sensor and certain objects.
Materials Needed:
The HC-SR04 ultrasonic sensor has 4 pins... The VCC pin, trig pin, echo pin, and GND pin. Like the diagram above shows, the VCC pin connects to +5V on the breadboard, the GND pin connects to GND on the breadboard, the trig pin connects to digital pin 11 of the Arduino, and the echo pin connects to digital pin 10 of the Arduino.
In order to connect the the LCD to the breadboard, I recommend that you solder a pin header strip to the connectors on the display. The connections for the LCD display are as follows:
- LCD VSS pin to Arduino GND on breadboard
- LCD VDD pin to Arduino 5V on breadboard
- LCD VO pin to 10k Potentiometer center pin
- LCD RS pin to digital pin 1
- LCD RW pin to Arduino GND on breadboard
- LCD Enable pin to digital pin 2
- LCD D4 pin to digital pin 4
- LCD D5 pin to digital pin 5
- LCD D6 pin to digital pin 6
- LCD D7 pin to digital pin 7
- LCD A pin to +5V on breadboard
- LCD K pin to GND on breadboard
The remaining pins of the 10K potentiometer connect to +5V on the breadboard and GND.
For this project, we can supply power to the Arduino through any +5V power source. You can use a USB port from your computer to power the Arduino, but in this project I will be using a portable battery. Before you connect a power source to your Arduino, make sure that the +5V port on the Arduino is connected to the +5V on the breadboard. Do the same and connect the GND port on the Arduino to the GND of the breadboard.
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
// defines pins numbers
const int trigPin = 11;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin digitalWrite
(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on LCD
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distance); // Prints the distance value from the sensor
lcd.print(" cm");
delay(10);
}