/*
HC-SR501 PIR Motion Sensor
Test and operation outline
This sketch uses a 'state' that is constintly monintored for changes.
This might not be the best solution because you need to constantly poll the state of the pin that
the sensor is connected to. Usually, the best way to detect the precise moment when the state goes
from LOW to HIGH (rising mode) and have a better responsiveness is to use interrupts.
But, there’s nothing wrong with using this previous simplified code, if it works good for your
project application.
*/
int ledPin = 13; // choose the pin for the LED
int sensorPin = 2; // choose the input pin (for PIR sensor)
int state = LOW; // we start, waiting for motion to be detected
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(sensorPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop() {
val = digitalRead(sensorPin); // read input value
/*
This body of code runs when the input from the PIR sensor is HIGH, or anytime the sensor has
detected movement. The time delay for how long the sensor stay HIGH is set on the PIR sensor.
In this code the sensor is set for 5 seconds so this loop keeps the LED on for 5 seconds.
variable 'val' will change to '1' when motion is detected and the second 'if statement' will
change the value of variable 'state' to HIGH.
*/
if (val == 1) { // 'val' changes to 1 and this statement runs
digitalWrite(ledPin, HIGH);
Serial.print("if State: "); Serial.print(state); Serial.print(" val: "); Serial.println(val);
delay(100);
if (state == LOW) { // since 'state' is started as LOW, this code runs
Serial.println("Motion detected!"); // print on the output change, not state
state = HIGH; // set 'state' to HIGH, so if statement runs only once.
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*
This body of code runs when the input from the PIR sensor is LOW, or anytime the sensor is not
detecting movement. Most of the time!
The value of variables 'val' and 'state' will both be 0.
*/
else { // When 'state' = 0 and 'val' = 0 this 'else' statement runs
digitalWrite(ledPin, LOW);
Serial.print("else State: "); Serial.print(state); Serial.print(" val: "); Serial.println(val);
delay(100);
if (state == HIGH) { // 'state' was set to HIGH in previous if statement above
Serial.println("Motion ended!"); // print on the output change, not state
state = LOW;
}
}
}