#include <Arduino.h>
// Define the GPIO pins for the ultrasonic sensor
#define TRIG_PIN 4
#define ECHO_PIN 17
// Define the GPIO pin for the relay
#define RELAY_PIN 5
// Define the water level thresholds
#define WATER_LEVEL_LOW 50 // in cm
#define WATER_LEVEL_HIGH 10 // in cm
void setup() {
// Initialize the ultrasonic sensor pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize the relay pin
pinMode(RELAY_PIN, OUTPUT);
// Start the serial communication
Serial.begin(9600);
}
void loop() {
// Measure the water level
long duration, distance;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2; // Calculate the distance
// Check the water level and control the pump accordingly
if (distance <= WATER_LEVEL_HIGH) {
// Water level is high, turn off the pump
digitalWrite(RELAY_PIN, LOW);
Serial.println("Pump OFF - Water level is high");
} else if (distance >= WATER_LEVEL_LOW) {
// Water level is low, turn on the pump
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Pump ON - Water level is low");
}
// Wait for a short period before measuring again
delay(1000);
}