#include <LiquidCrystal_I2C.h> // Library to Run I2C LCD LiquidCrystal I2C Library by Frank de Barbander 1.1.2
// We are using I2C 16x2 alphanumeric LCD with HD44780 controller
LiquidCrystal_I2C lcd(0x27, 16, 2); // Format -> (Address,Columns,Rows )
// define trigger and Echo pin for Ultrasonic sensor
const int TriggerPin = 3;
const int EchoPin = 2;
long distance = 0;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Distance =");
pinMode(TriggerPin, OUTPUT);
pinMode(EchoPin, INPUT);
digitalWrite(TriggerPin, LOW); // set trigger pin to LOW
delay(500);
}
void MeasureDistance(void) {
long TimeinMicroseconds;
// send a trigger pulse to the sensor of 10 us
digitalWrite(TriggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(TriggerPin, LOW);
TimeinMicroseconds = pulseIn(EchoPin, HIGH);
// speed of sound = 340 m/sec = 0.034 cm/microseconds
distance = ((0.034) * (TimeinMicroseconds));
// Here time duration is calculated forward + back time hence to get object distance from sensor divide by 2
distance = distance / 2;
}
void loop() {
MeasureDistance(); // This function is used to measure Distance
// Below Lines are used to Display Data on LCD
// write column, row and counting starts from zero so 0th Colum and 1st row
lcd.setCursor(0, 1);
lcd.print(" ");
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0)
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// provide some time between readings
delay(100);
}