#include <LiquidCrystal_I2C.h>
#define ECHO_PIN 8
#define TRIG_PIN 7
#define ledGreen 11
#define ledYellow 12
#define ledRed 13
LiquidCrystal_I2C lcd(0x27, 16, 2);
float X=400/397.63;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(ledGreen, OUTPUT);
pinMode(ledYellow, OUTPUT);
pinMode(ledRed, OUTPUT);
lcd.init();
lcd.backlight();
}
void loop() {
//Generate ultrasonic signal
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
//Read ultrasonic signal
float duration = pulseIn(ECHO_PIN, HIGH);
float distance = (duration * 0.034 * X) / 2;
lcd.setCursor(4,0);
lcd.print("DISTANCE");
lcd.setCursor(4,1);
lcd.print(distance);
lcd.setCursor(10,1);
lcd.print("cm");
if (distance > 15.00){
digitalWrite(ledGreen, HIGH);
digitalWrite(ledYellow, LOW);
digitalWrite(ledRed, LOW);
} else if (distance >= 5.00 && distance <= 15.00){
digitalWrite(ledGreen, LOW);
digitalWrite(ledYellow, HIGH);
digitalWrite(ledRed, LOW);
} else {
digitalWrite(ledGreen, LOW);
digitalWrite(ledYellow, LOW);
digitalWrite(ledRed, HIGH);
}
delay(100);
}