#include <LiquidCrystal.h> // includes the LiquidCrystal Library
// Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int trigPin = 9; // Pin for the trigger of the ultrasonic sensor
const int echoPin = 8; // Pin for the echo of the ultrasonic sensor
long duration; // Duration variable for pulse timing
int distanceCm, distanceInch; // Variables for distance in cm and inches
void setup() {
lcd.begin(16, 2); // Initializes the interface to the LCD screen and specifies the dimensions (width and height) of the display
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT); // Set the trigPin as an output
pinMode(echoPin, INPUT); // Set the echoPin as an input
}
void loop() {
digitalWrite(trigPin, LOW); // Ensure the trigger pin is low
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(trigPin, HIGH); // Send a high pulse for 10 microseconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Ensure the trigger pin is low again
// Measure the duration of the pulse received at echoPin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters and inches
distanceCm = duration * 0.034 / 2; // Speed of sound is 0.034 cm per microsecond
distanceInch = duration * 0.0133 / 2; // Convert to inches
// Display the distance in cm on the LCD
lcd.setCursor(0, 0); // Set the cursor to the first row
lcd.print("Distance: "); // Print the string "Distance"
lcd.print(distanceCm); // Print the distance in cm
lcd.print(" cm");
delay(10); // Small delay for screen refresh
// Display the distance in inches on the second row of the LCD
lcd.setCursor(0, 1); // Set the cursor to the second row
lcd.print("Distance: ");
lcd.print(distanceInch); // Print the distance in inches
lcd.print(" inch");
delay(10); // Small delay for screen refresh
}