65.9K
CodeProject is changing. Read more.
Home

Using PIR Motion Detector with Arduino

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jan 12, 2014

CPOL
viewsIcon

17260

downloadIcon

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.

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

Specify callback function for motion event in the setup.

pirm.setMotionCallback(pirmCallback); 

Implement the callback function.

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

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

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.

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