// Define ultrasonic sensor pins
const int trigPin = 19;
const int echoPin = 18;
const int maxDistance = 40;
// Define PIR sensor pin
const int pirPin = 13;
// Define servo motor pin
const int servoPin = 15;
// Define servo motor angle range
const int servoMinAngle = 0;
const int servoMaxAngle = 180;
// Define rubbish bin capacity and current fill level
const int rubbishBinCapacity = 40;
int rubbishBinLevel = 0;
// Define person detection status
bool isPersonDetected = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set ultrasonic sensor pins as input/output
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set PIR sensor pin as input
pinMode(pirPin, INPUT);
// Set servo motor pin as output
pinMode(servoPin, OUTPUT);
// Move the servo motor to the initial position
moveServo(servoMinAngle);
}
void loop() {
// Read distance from the ultrasonic sensor
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Limit the distance within the maximum distance range
if (distance > maxDistance) {
distance = maxDistance;
}
// Update the trash can fill level
rubbishBinLevel = map(distance, 0, maxDistance, rubbishBinCapacity, 0);
// Read the status of the PIR sensor
isPersonDetected = digitalRead(pirPin);
// Control the servo motor to open or close the rubbish bin lid based on the PIR sensor status
if (isPersonDetected) {
moveServo(servoMaxAngle);
} else {
moveServo(servoMinAngle);
}
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Calculate the rubbish bin fill level percentage
int fillPercentage = map(distance, 0, maxDistance, 0, 100);
// Output rubbish bin information
Serial.print("Rubbish Bin Fill Level: ");
Serial.print(fillPercentage);
Serial.print("% fill level reached.\n");
// Check the rubbish bin fill level and output the corresponding information
if (fillPercentage >= 100) {
Serial.println("The rubbish bin is full.");
} else if (fillPercentage >= 75) {
Serial.println("The rubbish bin is almost full.");
} else if (fillPercentage >= 50) {
Serial.println("The rubbish bin is half full.");
} else if (fillPercentage >= 25) {
Serial.println("The rubbish bin is partially full.");
} else {
Serial.println("The rubbish bin is not yet filled.");
}
Serial.println("\n");
delay(3000);
}
// Control the servo motor angle
void moveServo(int angle) {
angle = constrain(angle, servoMinAngle, servoMaxAngle);
int pulseWidth = map(angle, 0, 180, 1000, 2000);
digitalWrite(servoPin, HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(servoPin, LOW);
delay(20);
}