Motion Sensor Experiments
After completing the Motion Sensor project, test yourself by trying these experiments.
1 | This is a more reliable code for the motion sensor. |
// The output pin on the PIR is active high // i.e. outputs a HIGH value when motion is detected int pirPin = 3; //the digital pin connected to the PIR sensor's output int ledPin = 13; boolean lockLow = true; boolean takeLowTime; // flag to remember when PIR outputs a LOW long unsigned int lowIn; // time when PIR outputs a LOW //the amount of milliseconds the sensor has to be low //before we assume all motion has stopped long unsigned int pause = 2000; void setup(){ Serial.begin(9600); pinMode(pirPin, INPUT); pinMode(ledPin, OUTPUT); digitalWrite(pirPin, LOW); Serial.println("initializing sensor"); delay(20000); // time for sensor to initialize Serial.println("sensor initialized"); } void loop(){ if(digitalRead(pirPin) == HIGH){ digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state if(lockLow){ Serial.println("motion detected"); //makes sure we wait for a transition to LOW before any further output is made: lockLow = false; delay(50); } takeLowTime = true; } if(digitalRead(pirPin) == LOW){ // motion detected digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state if(takeLowTime){ lowIn = millis(); //save the time of the transition from high to LOW takeLowTime = 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(!lockLow && (millis() - lowIn > pause)){ //makes sure this block of code is only executed again after //a new motion sequence has been detected lockLow = true; Serial.println("motion ended"); delay(50); } } } |
2 | Adjustments for the motion sensor. |