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. This post is a simple one around how to interface any PIR sensor having digital output to the arduino board.
There are many kinds of PIR sensors available having stuff like onboard relay etc. but the one I am using gives digital output whenever it detects motion. Due to that, it is easy to interface with any microcontroller.
Pin 8 of Arduino is connected to the OUT pin of the sensor.
#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); } 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