Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Using PIR Motion Detector with Arduino

5.00/5 (4 votes)
12 Jan 2014CPOL 17.3K   393  
A library for PIR motion sensor

Introduction

I think cooking-hacks sold me their last PIR motion sensor of this model, they made it 'retired' :) Whatever, I like writing libraries, and also wrote for this one.

In the datasheet, 12v Vcc is advised, but also good with 5v. Therefore, you can connect it directly to your Arduino board without any need for an external power source.

One last point, use Arduino built-in pullup resistor for the digital input pin if you don't have an external resistor.

Using the Code

As always, place the library files in the libraries folder of the Arduino IDE. Then, you have a go.

C++
// include library
#include <PIRMotion.h>
// connected to digital2, use internal pullup
PIRMotion pirm(2,1);

Specify callback function for motion event in the setup.

C++
pirm.setMotionCallback(pirmCallback); 

Implement the callback function.

C++
void pirmCallback(void) {
  Serial.println("motion");
} 

And don't forget to monitor the sensor in the main loop.

C++
void loop() {
  pirm.update();
}

You have motion sensing capability now.

I have included one more function to the library to be able to add a time lag after a motion. For example, one may want to turn the lights on when somebody comes in, hold the lights on for 5 minutes, then start to monitor again to see if anybody wanders.

C++
pirm.setLagAfterMotion(5*60); // stops monitoring for 5 minutes

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)