// importing the neccassary library for code servo
#include <ESP32Servo.h>
// create a servo object
Servo myservo;
// config the trig and echo pins
const int trigPin = 2;
const int echoPin = 4;
// config the LED bulbs
const int redLED = 5;
const int greenLED = 14;
// create two vars to store duration and distance
long duration;
int distance;
// config the PIR sensor and create a var to store the bool expression of PIR sensor
const int sensor = 12;
int val = 0;
// config the servo motor and create a var to store the position of the servo
const int servo = 32;
int pos = 20;
// config the buzzer
const int buzzer = 33;
// create a func to handle when the bin is full
void handleFill(){
digitalWrite(greenLED,LOW);
digitalWrite(redLED,HIGH);
tone(buzzer, 349);
}
// create a func to handle when the bin is not full
void clearHandleFill(){
digitalWrite(greenLED,HIGH);
digitalWrite(redLED, LOW);
noTone(buzzer);
}
// create a func to open the bin
void openTheBin(){
for (pos = 20; pos <= 180; pos += 1) {
myservo.write(pos);
delay(15);
}
delay(5000);
}
// create a func to close the bin
void closeTheBin(){
for (pos = 180; pos >= 20; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
void setup() {
// initialize the pins of the components
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLED,OUTPUT);
pinMode(sensor, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(greenLED, OUTPUT);
myservo.attach(servo);
// keep the servo motor at 20 position
myservo.write(20);
}
void loop() {
// control the trigPin to get ultrasonic sensor input
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// get the duration
duration = pulseIn(echoPin, HIGH);
// calculate the distance according to distance
distance = duration * 0.034 / 2;
// get the PIR sensor input
val = digitalRead(sensor);
// if PIR detect someone infront of the sensor, then open the bin for some time and close it
if (val == HIGH) {
openTheBin();
delay(1000);
closeTheBin();
}
// check whether the bin is full and if not run the clearHandleFill() and otherwise run the handleFill()
if(distance <= 5){
handleFill();
}else{
clearHandleFill();
}
}