#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 20 columns, 4 rows
const int trigPin = 9; // Connect the trigger pin of the ultrasonic sensor to digital pin 9
const int echoPin = 10; // Connect the echo pin of the ultrasonic sensor to digital pin 10
const int buzzerPin = 11; // Connect the positive (longer leg) of the buzzer to digital pin 11
int set_val = 20; // Set your desired water level threshold in centimeters
void setup() {
Serial.begin(9600);
lcd.begin(20, 4); // Initialize the LCD with 20 columns and 4 rows
lcd.print("WATER LEVEL:");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
long duration, inches;
// Send a pulse to the trigger pin to start the measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (divide by 58 because the speed of sound is approximately 343 meters per second)
inches = duration / 58.0;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(inches);
Serial.println(" cm");
// Map the distance to a percentage range
int percentage = map(inches, 0, set_val, 100, 0);
percentage = constrain(percentage, 0, 100); // Ensure the percentage is within 0-100 range
// Display the percentage on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Percentage: ");
lcd.print(percentage);
lcd.print("%");
// Check if the distance is below a certain threshold (adjust as needed)
if (inches < set_val) {
// If the distance is below the threshold, make a sound with the buzzer
tone(buzzerPin, 1000); // Change the frequency as needed
delay(500); // Sound duration (adjust as needed)
noTone(buzzerPin);
}
delay(500); // Wait for a short duration before the next measurement
}