#include <ESP32Servo.h>
Servo drashServo; // create a servo object
int servoPin = 15; // GPIO pin for the servo
int pos = 0;
int trig=18;
int echo = 19;
int relay = 25;
long duration ;
int distance ;
int waterLevelThreshold= 250; // Water level threshold in cm (adjust based on your tank size)
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Set sensor pins as output/input
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(relay, OUTPUT);
// Turn off the relay (pump off) initially
digitalWrite(relay, HIGH);
drashServo.attach(servoPin); // attach the servo on the chosen pin
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Read the echo signal
duration = pulseIn(echo, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance );
Serial.println(" cm");
// Control the relay based on water level
if (distance < waterLevelThreshold) {
// If the water level is low, turn on the relay (pump on)
digitalWrite(relay, LOW);
Serial.println("Pump ON");
} else {
digitalWrite(relay, HIGH);
Serial.println("Pump OFF");
}
if( distance <10){
Serial.println("opening drash bin");
drashServo.write(90);
delay(2000);
drashServo.write(0);
delay(5000);
}
delay(100);
} // Wait for the servo to reach the position
// put your main code here, to run repeatedly:// this speeds up the simulation