Difficulty Level: Beginner
In this project, we will measure the distance of an object using an HC-SR04 ultrasonic sensor connected to an Arduino. The measured distance will be displayed on the serial monitor and an optional LCD display.
Connect the HC-SR04 sensor to the Arduino as follows:
The HC-SR04 sensor sends out ultrasonic pulses and listens for their echo. The time it takes for the echo to return is used to calculate the distance to an object. The Arduino will send out the trigger signal to the sensor, and the sensor will return the echo signal. The time taken for the echo to be received is converted into distance using the formula:
Distance = (Time * Speed of Sound) / 2
In this project, we will display the calculated distance in centimeters on the serial monitor.
Here is the Arduino code for measuring distance with the HC-SR04 sensor:
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance;
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and get the duration
duration = pulseIn(echoPin, HIGH);
// Calculate distance (speed of sound is 343 meters per second)
distance = (duration * 0.034) / 2;
// Display the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait before the next measurement
delay(500);
}
If you want to display the distance on an LCD, you can use the LiquidCrystal_I2C
library. The following additional code will allow you to display the distance on a 16x2 I2C LCD:
#include
#include
LiquidCrystal_I2C lcd(0x27, 16, 2); // Define the LCD
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lcd.begin();
lcd.backlight();
}
void loop() {
long duration, distance;
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and get the duration
duration = pulseIn(echoPin, HIGH);
// Calculate distance
distance = (duration * 0.034) / 2;
// Display the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Wait before the next measurement
delay(500);
}
Using the HC-SR04 sensor, you can measure distances with accuracy and display the data either on the serial monitor or an optional LCD display. This project introduces the basics of ultrasonic distance measurement and can be further expanded for more complex applications like obstacle detection in robotics.