Advertisement
m3k_p

Sensor PIR

Mar 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //the time we give the sensor to calibrate (10-60 secs according to the datasheet)
  2. int calibrationTime = 30;      
  3.  
  4. //the time when the sensor outputs a low impulse
  5. long unsigned int lowIn;        
  6.  
  7. //the amount of milliseconds the sensor has to be low
  8. //before we assume all motion has stopped
  9. long unsigned int pause = 5000;
  10.  
  11. boolean lockLow = true;
  12. boolean takeLowTime;
  13.  
  14. int pirPin = 3;    //the digital pin connected to the PIR sensor's output
  15. int ledPin = 13;
  16.  
  17.  
  18. /////////////////////////////
  19. //SETUP
  20. void setup(){
  21.   Serial.begin(9600);
  22.   pinMode(pirPin, INPUT);
  23.   pinMode(ledPin, OUTPUT);
  24.   digitalWrite(pirPin, LOW);
  25.  
  26.   //give the sensor some time to calibrate
  27.   Serial.print("calibrating sensor ");
  28.     for(int i = 0; i < calibrationTime; i++){
  29.       Serial.print(".");
  30.       delay(1000);
  31.       }
  32.     Serial.println(" done");
  33.     Serial.println("SENSOR ACTIVE");
  34.     delay(50);
  35.   }
  36.  
  37. ////////////////////////////
  38. //LOOP
  39. void loop(){
  40.  
  41.      if(digitalRead(pirPin) == HIGH){
  42.        digitalWrite(ledPin, HIGH);   //the led visualizes the sensors output pin state
  43.        if(lockLow){
  44.          //makes sure we wait for a transition to LOW before any further output is made:
  45.          lockLow = false;          
  46.          Serial.println("---");
  47.          Serial.print("motion detected at ");
  48.          Serial.print(millis()/1000);
  49.          Serial.println(" sec");
  50.          delay(50);
  51.          }        
  52.          takeLowTime = true;
  53.        }
  54.  
  55.      if(digitalRead(pirPin) == LOW){      
  56.        digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state
  57.  
  58.        if(takeLowTime){
  59.         lowIn = millis();          //save the time of the transition from high to LOW
  60.         takeLowTime = false;       //make sure this is only done at the start of a LOW phase
  61.         }
  62.        //if the sensor is low for more than the given pause,
  63.        //we assume that no more motion is going to happen
  64.        if(!lockLow && millis() - lowIn > pause){
  65.            //makes sure this block of code is only executed again after
  66.            //a new motion sequence has been detected
  67.            lockLow = true;                      
  68.            Serial.print("motion ended at ");      //output
  69.            Serial.print((millis() - pause)/1000);
  70.            Serial.println(" sec");
  71.            delay(50);
  72.            }
  73.        }
  74.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement