#include <Servo.h>
const int pirPin = 2; // PIR motion sensor pin
const int servoPin = 9; // Pin to which the servo motor is connected
const int trigPin = 12; // Trig pin of the HC-SR04 (UDS)
const int echoPin = 11; // Echo pin of the HC-SR04 (UDS)
const int greenLedPin = 7; // Green LED pin
const int redLedPin = 6; // Red LED pin
const int thresholdDistance = 20; // Threshold distance to trigger red LED (in cm)
const int maxDistance = 50; // Maximum distance considered for green LED (in cm)
Servo lidServo;
void setup() {
pinMode(pirPin, INPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
lidServo.attach(servoPin);
Serial.begin(9600);
}
void loop() {
bool motionDetected = digitalRead(pirPin) == HIGH;
if (motionDetected) { // If motion is detected
digitalWrite(greenLedPin, HIGH); // Turn on green LED
openLid(); // Open the lid
delay(5000); // Wait for 5 seconds
closeLid(); // Close the lid
digitalWrite(greenLedPin, LOW); // Turn off green LED
} else { // If no motion is detected
long duration, distance;
// Triggering the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reading the echo pin to calculate distance
duration = pulseIn(echoPin, HIGH);
// Calculating distance in cm
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Checking if garbage is detected
if (distance < thresholdDistance) {
digitalWrite(redLedPin, HIGH); // Turn on red LED
} else {
digitalWrite(redLedPin, LOW); // Turn off red LED
// Checking if bin has more space
if (distance < maxDistance) {
digitalWrite(greenLedPin, HIGH); // Turn on green LED
} else {
digitalWrite(greenLedPin, LOW); // Turn off green LED
}
}
}
}
void openLid() {
lidServo.write(90); // Rotate servo to open the lid
}
void closeLid() {
lidServo.write(0); // Rotate servo to close the lid
}