#define TRIG_PIN 9
#define ECHO_PIN 10
#define RELAY_PIN 7 //pin to control the relay
#define BUZZER_PIN 6
const int tankHeight = 20; // tank height in cm
const int startLevelDistance =19; //25% of tank height =20-5=15cm(distance to water)
const int stopLevelDistance =4; //95% of tank height =20-19=1cm
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN,OUTPUT);
pinMode(ECHO_PIN,INPUT);
pinMode(RELAY_PIN,OUTPUT);
pinMode(BUZZER_PIN,OUTPUT);
digitalWrite(RELAY_PIN,LOW); //initially turn off relay(pump off)
digitalWrite(BUZZER_PIN,LOW);
void loop() {
// send a pulse to TRIG_PIN
digitalWrite(TRIG_PIN,LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN,HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN,LOW);
// read the echo time
long duration = pulseIn(ECHO_PIN,HIGH);
//Calculate distance from sensor to water surface in cm
int distance = duration * 0.034/2;
// print distance to water
Serial.print("Distance to water:");
Serial.print(distance);
Serial.println("cm");
// start pump if distance to water is greater than 15cm(below 25% water level)
if (distance > startLevelDistance){
Serial.println("Water level below 25%,turning on the pump");
digitalWrite(RELAY_PIN,LOW);// turn on the relay(pump on)
// stop pump if distance to water is less than or equal to 1cm(above 95% water level)
if (distance <= stopLevelDistance){
Serial.println("Water level at 95%,turning off the pump.");
digitalWrite(RELAY_PIN,HIGH);//turn off tyhe relay(pump off)
digitalWrite(BUZZER_PIN,HIGH);
delay(2000);
digitalWrite(BUZZER_PIN,LOW);
delay(1000);