PIR sensor code

arduino, tutorial

No Comments

Share this post

After reading a little bit about motion sensing with PIR sensors and arduino, I was able to improve this code a little bit. The idea came up from sensing “strong motion” as opposed to just a random one.

This image shows a previous code based on the buildr link above:

The idea is that it will only turn the led on or send a “motion detected” message if a strong motion is detected, that is if 5 consecutive signals from the infraRed sensor will trigger the actual action. I was trying to debug this sensor trying to understand its behavior correctly. When I built the circuit, I noticed the motion sensing was as not as reliable as I wanted. That was triggering a false or unwanted signal. Based on my observations of how my interactions with the sensor affected the LED and serial messages, I discovered that the sensor sometimes will send a weird “LOW” to the board and trigger the alarm… But what is the probability of 5 signals in a row? That is what this program does… It is very reliable now!  It was just a software solution to the sensor debugging.  In fact the “motion” sensor is actually activated by heat sensing, a variable associated with motion…. Watch out predator, I can sense you now!

int pirPin = 2; //digital 2
int ledPin = 13;
int counter;

void setup(){

pinMode(pirPin, INPUT);pinMode(ledPin, OUTPUT);

void loop(){
int pirVal = digitalRead(pirPin);

if(pirVal == LOW){ //was motion detected
counter ++;
if (counter == 5){ // the sensor has to be triggered at least 5 times to detect strong motion
digitalWrite(ledPin,HIGH);// send the signal put your trigger action here



if(pirVal == HIGH){ //was motion detected

digitalWrite(ledPin,LOW );


0 Responses to this post
Add your comment