#define echoPin 2
#define triggerPin 3
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);
// set the LCD address to 0x27 for a 16 chars and 2 line display
float dist_cm;
float dist_inches;
long DistanceReader()
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Turn on the USD:Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns
// the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.backlight();
lcd.print(" Distance");
delay(3000);
lcd.clear();
}
void loop()
{
dist_cm = 1.0/58 * DistanceReader();
dist_inches = (dist_cm / 2.54);
// turn on the LED when distance less than 200 cm
bool closeness = dist_cm < 200;
digitalWrite(LED_BUILTIN, closeness); //
// Set up for printing in LCD
lcd.setCursor(0,0);
lcd.print("cm");
lcd.setCursor(2,0);
lcd.print(dist_cm,1);
lcd.setCursor(7,0);
lcd.print(" in");
lcd.setCursor(11,0);
lcd.print(dist_inches, 1);
// display for Distances good or bad
if (dist_cm <= 200)
{
lcd.setCursor(1,1);
lcd.print("D is too short");
}
if (dist_cm >200)
{
lcd.setCursor(3,1);
lcd.print("D is good");
}
delay(2000);
lcd.clear();
}