int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 3;
int ledPin = 13;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
void setup()
{
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
pinMode(pirPin, INPUT);
digitalWrite(pirPin, LOW);
Serial.println(“calibrating sensor “);
for(int i = 0; i < calibrationTime; i++){
Serial.print(“.”);
delay(1000);
}
Serial.println(” done”);
Serial.println(“Sensor Active”);
delay(50);
}
void loop()
{
if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, LOW);
for(pos = 0; pos < 45; pos += 1000) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(30); // waits 15ms for the servo to reach the position
}
for(pos = 45; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(30); // waits 15ms for the servo to reach the position
}
if(lockLow){
//makes sure we wait for a transition to LOW before any further output is made:
lockLow = false;
Serial.println(“—“);
Serial.print(“motion detected at “);
Serial.print(millis()/1000);
Serial.println(” sec”);
delay(50);
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
//if the sensor is low for more than the given pause,
//we assume that no more motion is going to happen
if(!lockLow && millis() – lowIn > pause){
//makes sure this block of code is only executed again after
//a new motion sequence has been detected
lockLow = true;
Serial.print(“motion ended at “); //output
Serial.print((millis() – pause)/1000);
Serial.println(” sec”);
delay(50);
}
}}}