Build a system that detects water level in a tank using an ultrasonic sensor and alerts you with a buzzer and LED when the tank is full or empty.
The ultrasonic sensor is placed at the top of the water tank, facing downward. It measures the distance from the sensor to the water surface.
Based on the distance, we light up different LEDs and sound the buzzer to alert the user.
// Water Level Alert - NKDevSpace Tutorial
const int trigPin = 9;
const int echoPin = 10;
const int greenLED = 4;
const int redLED = 5;
const int buzzerPin = 8;
// Adjust these based on your tank height (in cm)
const int fullLevel = 5; // Tank is FULL when distance < 5 cm
const int emptyLevel = 25; // Tank is EMPTY when distance > 25 cm
long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
long distance = getDistance();
Serial.print("Distance to water: ");
Serial.print(distance);
Serial.println(" cm");
if (distance <= fullLevel) {
// Tank is FULL - Red alert
Serial.println("ALERT: Tank is FULL!");
digitalWrite(greenLED, LOW);
digitalWrite(redLED, HIGH);
tone(buzzerPin, 1000); // Buzzer ON at 1000 Hz
}
else if (distance >= emptyLevel) {
// Tank is EMPTY - Red alert
Serial.println("ALERT: Tank is EMPTY!");
digitalWrite(greenLED, LOW);
digitalWrite(redLED, HIGH);
tone(buzzerPin, 500); // Buzzer ON at 500 Hz
}
else {
// Water level is NORMAL - Green light
Serial.println("Water level: Normal");
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, LOW);
noTone(buzzerPin); // Buzzer OFF
}
delay(1000);
}
fullLevel = 5, emptyLevel = 25tone(buzzerPin, 1000)distance <= fullLevel