//Libraries:
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
//Define HC-SR04 & other variables!
#define echoPin 2 //attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
long duration; //variable for the duration of sound wave travel
int distance; //variable for the distance measurement
void setup() {
//Task, LCD & distance sensor initialization:
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT); //Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); //Sets the echoPin as an INPUT
}
void loop() {
//Clears the trigPin condition
digitalWrite(trigPin, LOW);
//Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
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; //Speed of sound wave divided by 2 (go and back)
lcd.setCursor(0, 0); lcd.print(distance);
lcd.setCursor(4, 0); lcd.print("cm");
delay(1000);
lcd.clear();
}