#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the pins used for the ultrasonic sensor
const int trigPin = 4;
const int echoPin = 5;
// Define the pins used for the LEDs
const int redPin = 13;
const int yellowPin = 12;
const int greenPin = 14;
// Define the pin used for the buzzer
const int buzzerPin = 27;
// Create a LiquidCrystal_I2C object for the LCD
LiquidCrystal_I2C lcd(0x27,16,2);
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the LED pins
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
// Initialize the buzzer pin
pinMode(buzzerPin, OUTPUT);
// Initialize the I2C LCD
lcd.init();
lcd.backlight();
// Display a welcome message on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Flood Monitoring");
lcd.setCursor(0, 1);
lcd.print("Depth: ");
lcd.setCursor(11,1);
lcd.print("cm");
}
void loop() {
// Trigger the ultrasonic sensor by sending a 10 microsecond pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the ultrasonic sensor
long duration = pulseIn(echoPin, HIGH);
// Convert the duration to distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.println(" cm");
Serial.print(distance);
// Display the distance on the LCD
lcd.setCursor(7, 1);
lcd.print(distance);
// Blink the LED colors based on the distance
if (distance < 30) {
digitalWrite(redPin, HIGH);
delay(300);
digitalWrite(redPin, LOW);
delay(300);
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, LOW);
} else if (distance < 60) {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, HIGH);
delay(300);
digitalWrite(yellowPin, LOW);
delay(300);
} else {
digitalWrite(greenPin, HIGH);
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, LOW);
}
// If the distance is less than 59 centimeters, sound the buzzer
if (distance < 30) {
// Turn on the buzzer
digitalWrite(buzzerPin, HIGH);
tone(buzzerPin, 1000);
} else if (distance < 60) {
// Turn off the buzzer
digitalWrite(buzzerPin, HIGH);
tone(buzzerPin, 1000, 250);
} else {
digitalWrite(buzzerPin, LOW);
tone(buzzerPin, 0);
}
}