Friday, February 5, 2016

PIR Sensor with Arduino



                           PIR sensors are really simple and easy to use as well as cheap motion detection sensor. The feature that it is easy to interface with any microcontroller makes it widely usable. Here i am providing a simple Arduino sketch to interface it with Arduino.

Circuit Diagram :

** Pin 8 of Arduino is connected to the OUT pin of the sensor.

Sketch :

#define  timeToCaliberate 30   
#define timeToDetectMotionBetween 5000
    
long unsigned int lastMotionTime; 
long unsigned int motionInTime;      
boolean lastMotionFinished = true;
boolean lastMotionDetected;  

int inputPIRPin = 8;    //the digital pin connected to the PIR sensor's output
int LED = 13;

//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(inputPIRPin, INPUT);
  pinMode(LED, OUTPUT);
  digitalWrite(inputPIRPin, LOW);
  
  Serial.println("Providing some time to sensor for caliberation.");
  while(millis()/1000 < timeToCaliberate){
      Serial.print("-");
      delay(1000);
  }
  Serial.println("Caliberation Finished. Your PIR Sensor is now Online");
  delay(50);
}

////////////////////////////
//LOOP
void loop(){
  if(digitalRead(inputPIRPin) == HIGH){
      digitalWrite(LED, HIGH);
      if(lastMotionFinished){  
         lastMotionFinished = false;            
         Serial.println("Motion Detected");
         motionInTime= millis();
         delay(50);
       }         
      lastMotionDetected = true;
  }
  
  if(digitalRead(inputPIRPin) == LOW){  
       if(lastMotionDetected){
          lastMotionTime = millis();          
          lastMotionDetected = false; 
        }
       if(!lastMotionFinished && millis() - lastMotionTime > timeToDetectMotionBetween){  
           lastMotionFinished = true;                        
           Serial.print("Movement was for  ");              
           Serial.print((millis()-motionInTime)/1000);              
           Serial.println(" second."); 
           motionInTime=0;
           delay(50);     
            digitalWrite(LED, LOW);
          }
      }
  }



All file are available on my git repository also. Checkout: here



No comments:

Post a Comment