/*
PIR sensor tester
*/
#include "Servo.h"
Servo myServo;
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
unsigned long waitTime = 750 * 20; // Wait time before checking motion again in milliseconds 20 seconds
const byte closeAngle = 0; // Close angle for food container
const byte openAngle = 90; // Open Angle for food container
unsigned long motionTime; // Variable to store motion time
unsigned long openTime = 1000 * 5; // Set servo for 5 seconds only
bool openLid = LOW; // Variable to close lid after opentime finish
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
myServo.attach(9); // Attach servo at pin 9
myServo.write(closeAngle); // Initially close lid of food container
Serial.begin(9600);
}
void loop() {
if ((openLid) && ((millis() - motionTime) > openTime)) {
myServo.write(closeAngle); // Close servo
}
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
openLid = HIGH; // Set Open Lid flag high
myServo.write(openAngle); // Open servo to servo food
motionTime = millis(); // Store current motion time
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH) {
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
if (openLid) {
unsigned long cTime = millis(); // Note down current time
Serial.println("Wait Time start");
while ((millis() - cTime) < waitTime) {
if ((openLid) && ((millis() - motionTime) > openTime)) {
myServo.write(closeAngle); // Close servo
}
} // Wait time started
openLid = LOW;
Serial.println("Wait time end");
}
}
}
}