#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <NewPing.h>
// Ultrasonic Sensor pins
#define TRIGGER_PIN 5
#define ECHO_PIN 18
#define MAX_DISTANCE 200 // Maximum distance to measure (in cm)
// Buzzer pin
#define BUZZER_PIN 19
// Initialize ultrasonic sensor
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// Initialize I2C LCD display with the I2C address (usually 0x27) and size (16x2)
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
pinMode(BUZZER_PIN, OUTPUT);
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
}
void loop() {
// Measure distance
unsigned int distance = sonar.ping_cm();
// Display on LCD
lcd.setCursor(0, 0);
lcd.print("Water Level:");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Check water level and sound alarm if necessary
if (distance < 10) { // Adjust threshold as needed
digitalWrite(BUZZER_PIN, HIGH);
} else if (distance > 150) { // Adjust threshold as needed
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
delay(1000); // Wait for a second before the next measurement
}