#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
int but = 12;
int buttonState12 = 0;
int triggerPin = 19; // Ultrasonic sensor trigger pin
int echoPin = 18; // Ultrasonic sensor echo pin
int redLedPin = 2; // Red LED pin
int greenLedPin = 4; // Green LED pin
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(but, INPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
}
void loop() {
buttonState12 = digitalRead(but);
if (buttonState12 == HIGH) {
lcd.backlight();
} else {
lcd.noBacklight();
}
long duration;
float distance_cm;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance_cm = duration * 0.034 / 2;
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance_cm);
lcd.print("cm");
if (distance_cm < 100) {
digitalWrite(redLedPin, HIGH);
lcd.setCursor(3, 1);
lcd.print(" RED ");
digitalWrite(greenLedPin, LOW);
} else {
digitalWrite(redLedPin, LOW);
lcd.setCursor(3, 1);
lcd.print(" GREEN ");
digitalWrite(greenLedPin, HIGH);
}
}