// Arduino Smart Trash Can - ozandamci.com
#include <Servo.h>
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 6;
const int openAngle = 100; // lid open position
const int closedAngle = 0; // lid closed position
const int detectDistance = 20; // open if a hand is closer than this (cm)
Servo lid;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lid.attach(servoPin);
lid.write(closedAngle);
Serial.begin(9600);
}
int measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) return -1; // nothing in front of the sensor
return duration * 0.034 / 2; // centimetres
}
void loop() {
int distance = measureDistance();
Serial.print("Distance: ");
Serial.println(distance);
if (distance > 0 && distance < detectDistance) {
lid.write(openAngle);
delay(3000); // keep the lid open for 3 seconds
// Don't close the lid while the hand is still there
while (true) {
int newDistance = measureDistance();
if (newDistance <= 0 || newDistance >= detectDistance) break;
delay(500);
}
// Close the lid slowly
for (int angle = openAngle; angle >= closedAngle; angle--) {
lid.write(angle);
delay(10);
}
}
delay(100);
}