arduino + 2 PIR sensors

Hi,
I've been working with arduino and 2 PIR sensors to control the lights in my room. So basically when i enter the room , the lights should go on automatically and after the exit , the lights should go off.. Im using 2 sensors so i can handle multiple entries and exits incase more than 1 person is in the room. So basically im using a variable ctr to keep track of the number of people in the room at one point of time.
Ive placed 2 PIR sensors side by side with a small gap say PIR1 and PIR2. While entering PIR1 triggers first and then PIR2 this increments ctr by1 . While exiting PIR2 triggers first then PIR1 this decrements ctr by 1. Therefore if ctr is 0 then i can switch off the light(using relay).else the light will remain on.
The best part is that the code works fine.. the whole setup works awesome but only for a while. After about 2 hours or so ( and sometimes in random in between ) for some reason when i exit instead of PIR2 triggering before PIR1 , the opposite occurs which then increments ctr by 1 instead of decrementing. THis keeps happening for exits therefore ctr never goes to 0. But if i then restart the arduino everything works fine again for a couple of hours and then the problem starts. The code is fine , the sensors are placed right , its just that it acts weird after a while , although restarting fixes it but thats not reliable.

Here is the code

/* 
 * //////////////////////////////////////////////////
 * //making sense of the Parallax PIR sensor's output
 * //////////////////////////////////////////////////
 *
 * Switches a LED according to the state of the sensors output pin.
 * Determines the beginning and end of continuous motion sequences.
 *
 * @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at
 * @date:   3. September 2006 
 *
 * kr1 (cleft) 2006 
 * released under a creative commons "Attribution-NonCommercial-ShareAlike 2.0" license
 * http://creativecommons.org/licenses/by-nc-sa/2.0/de/
 *
 *
 * The Parallax PIR Sensor is an easy to use digital infrared motion sensor module. 
 * (http://www.parallax.com/detail.asp?product_id=555-28027)
 *
 * The sensor's output pin goes to HIGH if motion is present.
 * However, even if motion is present it goes to LOW from time to time, 
 * which might give the impression no motion is present. 
 * This program deals with this issue by ignoring LOW-phases shorter than a given time, 
 * assuming continuous motion is present during these phases.
 *  
 */

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;        

//the time when the sensor outputs a low impulse
long unsigned int lowIn1;      
long unsigned int lowIn2;            

//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 100;  

boolean lockLow1 = true;
boolean takeLowTime1;  
boolean lockLow2 = true;
boolean takeLowTime2; 

int pirPin2 = 10;
int pirPin1 = 3;    //the digital pin connected to the PIR sensor's output
int ledPin = 7;
int flag1=0;
int flag2=0;
int ctr=0;

/////////////////////////////
//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(pirPin1, INPUT);
  pinMode(pirPin2, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin1, LOW);
  digitalWrite(pirPin2, LOW);
  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }

////////////////////////////
//LOOP
void loop(){
  static int relayVal = 0;

     if(digitalRead(pirPin1) == HIGH){
     //the led visualizes the sensors output pin state
       if(lockLow1){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow1 = false;            
         Serial.println("---");
         Serial.print("motion detected at1 ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
        
         delay(50);
         flag1=1;
         if(flag2==1)
         {
          ctr=ctr+1;
          Serial.println("ctr  at 1= ");
          Serial.println(ctr);
          flag1=0;
          flag2=0;
          if(ctr<=0)
                  digitalWrite(ledPin, LOW);
                    if(ctr>0)
                  digitalWrite(ledPin, HIGH);
         }
      
         }         
         takeLowTime1 = true;
       }

//*************8

     if(digitalRead(pirPin2) == HIGH){
        //the led visualizes the sensors output pin state
       if(lockLow2){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow2 = false;            
         Serial.println("---");
         Serial.print("motion detected at2 ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
           //Serial.println(flag1);
          //Serial.println(flag2);
         delay(50);
          flag2=1;
         if(flag1==1)
         {
          ctr=ctr-1;
          Serial.println("ctr at 2 = ");
          Serial.println(ctr);
          flag1=0;
          flag2=0;
          if(ctr<=0)
                  digitalWrite(ledPin, LOW);
                    if(ctr>0)
                  digitalWrite(ledPin, HIGH);
         }
       
         }         
         takeLowTime2 = true;
       }
//************

     if(digitalRead(pirPin1) == LOW){       
       //digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime1){
        lowIn1 = millis();          //save the time of the transition from high to LOW
        takeLowTime1 = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow1 && millis() - lowIn1 > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow1 = true;                        
           Serial.print("motion ended at1 ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
//#####
 if(digitalRead(pirPin2) == LOW){       
       //digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime2){
        lowIn2 = millis();          //save the time of the transition from high to LOW
        takeLowTime2 = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow2 && millis() - lowIn2 > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow2 = true;                        
           Serial.print("motion ended at2 ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
//#####
  }

would really appreciate some help..Thanks a lot ..

You should not be making any assumption about the order that the two PIRs fire in. One might be slightly more effective than the other, thus detecting the presence of infrared for slightly longer.

It sounds like you are trying to use the sensors in a way that they are not intended to be used.

oh ok..thanks for the reply..what else can be used in this case?

Typically, one would use a pair of light beams at each entrance. As long as only one person enters or exits at time, the order that the beams are broken indicates whether someone is entering or leaving the room.

The PIR sensor generally detects whether there is anyone in the room. Of course, this requires careful positioning of the sensors (so they can see the whole room), and some movement on the part of the person(s) in the room.

If there are multiple sensors, HIGH output from ANY sensor means that there is someone in the room.

I thought of the PIR to detect motion but it can get irritating at times if there isnt any motion at all to wave your hand.. also it could also waste energy as the code will check - if no motion for more than 5 min switch off , but there is definitely a lot of energy waste during that time..
ABout the light beams , do you mean IR detector which detect IR LED light?http://www.me.umn.edu/courses/me2011/arduino/technotes/irbeam/irbeam.html

Thank you so much..

PaulS is right, basically the system you propose will never work to any degree of satisfaction. The PIR's track motion through changes in temperature from body heat, the PIR's will never lock onto a person and be able to 'track' that person in a room, watch the sensor light on an alarm PIR when you are in a room, it will go on and off as you move around.

The only way your system will work is for the PIR(s) to send a signal to the Arduino, and the Arduino to act as a simple timer, but saying that, there are many simple light sensors, that cost less then an Arduino, and do the job well, so why tie up something complex to do a simple job.

PaulS's solution with the light beam beams is probably the most reliable way of doing the job, and one light sensor used to detect the light level when lighting is required.

Maybe augment the "count people past the doors" data with data from a PIR.... If the "count" data thinks the room is empty, but the PIR "sees" someone, make "count" equal 1.

This sort of "mixed" system, while not coldly logical, scientific, exact, often actually WORKS (in the real world!) quite well!

thanks a lot for the replies everyone..Could anyone provide a link to those light sensors maybe on sparkfun..Thanks..

From....

... (where you can buy the core parts) follow the link "IR Schematic"

For a better solution, one with more range and greater resistance to environmental distractions, set up something based on the sort of IR communications between the ubiquitous remote control and TVs, etc. For more on this, see....

That is couched in "Nuelectronics shield" terms, but doesn't need the shield. What it WOULD need is a little more than an IR ELD JUST "on". It has to be "on", but actually flashing on and off very rapidly. Not hard. A little 555 should do the job, or just "hack" a remote control.

thanks a lot everyone for the replies.. really appreciate it.. will try looking for this..thanks again..

You could do something like I did with a motion sensor. I use it to detect when someone comes into a room, in this case, the bathroom. Each time it detects motion, it resets a counter and keeps PWM to an LED at maximum. If the counter expires--the sensor sees no motion for that length of time--it lowers the PWM to a minimum level.

I use this for a night light. Walk in the bathroom at night, the night light brightens so you can do your business without switching on the overhead light and blinding yourself. About 20 seconds after your leave, it dims.

Code and pictures are here: http://www.instructables.com/id/Repurposing-a-115-VAC-airwick-motion-sensor/

thanks a lot for the replies everyone..Could anyone provide a link to those light sensors maybe on sparkfun..Thanks..

well though getting something form sparkfun would be eeasy you could use a laser and ldr setup which will be eeven lesser than the shipping costs ! :slight_smile:

thanks for the replies.. i just wanted a sparkfun link to know what it looks like and its approx cost before i go to a local store and purchase it.. For the application mentioned above in the first post...Which of the following you think makes sense?

  1. http://www.tenettech.com/product.php?id_product=959
  2. http://www.tenettech.com/product.php?id_product=955
  3. http://www.tenettech.com/product.php?id_product=965 with a laser

i'm not really sure what the difference in those 3 are?? i think any of those 3 can be used for this application..although im not too sure..any clarification would be helpful..
Thanks..

would really appreciate some help..thanks :slight_smile:

well all those three are different

http://www.tenettech.com/product.php?id_product=959

This sensor uses an infrared emitted diode combined with an infrared phototransistor to detect the reflected infrared signal. Ideal for sensing black-to-white transitions or can be used to detect nearby objects (.5-1cm( YOU DIDNT LOOK AROUND )

  1. http://www.tenettech.com/product.php?id_product=955

it is a phototransistor sensitiver to IR at 980 nm generally used in remotes stc

  1. http://www.tenettech.com/product.php?id_product=965 with a laser

this is a ldr i.e light dependant resistor it gives out analog values in propotion to the light falling it i would consider this as the best opeion as using it withga laser you wouldnt be having any problems with normal light interfering with your readings :slight_smile:

P.S are you going to Buy at tenentech ? they charge a LOT! a Photodectedtor would cost you about 15 Rs ! not 94 update your profile so that i could suggessst something better here in hyderabad i get those for Rs 15 ! where do you Live in india ? (for those who aare curious i figured it out bassed on the name and shop )

-Hope This Helps

thanks a lot for the info.. No i dont buy from there , that is just to know what it is and how it looks.. thanks again...

You really must forget the idea of using a PIR,it just simply WONT WORK!!!

PIR's will look for body objects in the room, all around them, even if you arranged to narrow the range down,they will still pick up movement nearby, so if someone came into the room and the PIR sensed that person, it would count "1 person" in the room. That person then goes out of range, after a while he moves around the room, and the PIR senses him again, the Arduino will then think there is a "2nd person" in the room.

PIR's WONT work in this application.

What you need to do is have 2 light beams, laser etc, set up across the doorway, one just before the other. As a person enters the room,light beam 'A' will break before light beam 'B' the Arduino knows because of the sequence, that a person has entered the room, beam a was broken before beam b. The person count is now '1' when another comes into the room,the person count is now '2' and so on. Now if a person LEAVES the room, beam 'B' will break before beam 'A' and the Arduino will subtract from the person count.

Probably the cheapest way of setting up the light beams,is to use the lasers from a cheap laser pointer,the sort that cost $1 and a photo diode, or even a red LED.

Now if you wanted to use your PIR,you could integrate it with your system as an alarm. If the person count = 0, the room is empty,and so if the PIR is triggered,someone has entered the room via another route, such as a window, thus triggering the alarm system,adding a keypad allows you to set it as you leave or enter.