PIR Sensor (image from Adafruit) |
Rear of PIR Sensor (image from Adafruit) |
Using the WiringPi library, it was pretty easy to get it up and running. Here is a picture of it mounted on top of the Prototyping Pi Plate from Adafruit with double-sided tape.
Raspberry Pi Plate with PIR and LED |
I connected it to GPIO 18 or pin 1 in the WiringPi library. Here is the code I used that blinks the LED when there is motion. I used the same technique as the blinking LED test so that I can check the status from the web interface. I made one program that monitors for motion which blinks the LED (runs in the background continuously). The second program runs when the webpage requests the status of the PIR sensor. Now I am trying to figure the best way to keep the status updated on the webpage instead of only when you click the check button. I am thinking either AJAX or a frame that refreshes.
Here is the code for monitoring motion and blinking the LED. This is running in the background using:
sudo ./pir &
/*
* pir.c:
* Simple test program to read pir and blink LED on pin 1/18
*/
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int ledPin = 0;
int pirPin = 1;
if (wiringPiSetup() == -1)
exit (1);
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
while(1){
if (digitalRead(pirPin) == HIGH)
{
//printf("LED Onn");
digitalWrite(ledPin, 1);
delay(250);
//printf("LED Offn");
digitalWrite(ledPin, 0);
delay(150);
}
}
return 0;
}
Here is the code for return the PIR status. Remember to add this program to the visudo file to allow the web service to run it with root. See this post
/*
* pir_status.c:
* Return logic level of PIR on pin 1/18
*/
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int pirPin = 1;
int readPir = 0;
if (wiringPiSetup() == -1)
exit (1);
pinMode(pirPin, INPUT);
readPir = digitalRead(pirPin);
if (readPir == 1) { printf("Yesn");}
else { printf("Non");}
return 0;
}
Comments 1
how to control servo motor into PIR MOTION IF DETECT A MOTION