int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
Above is some sensor code from Adafruit's website that basically instructs a PIR Sensor to respond to motion and outputting a signal to an LED once detected. Here is my situation:
I DO understand that a HIGH or LOW value from the PIR Sensor is being inputted into the variable 'val' and if it's HIGH, the LED will light up.
Here are some things that I DON'T understand (This is my understanding of what should be happening):
-
So the program is initially declaring a variable named 'pirState' to store the state of the PIR, correct? So if the program doesn't do anything with 'pirState' until it arrives at its 2nd IF statement checking to see if there is no signal (LOW) while still holding the value LOW (pirState = LOW) , why would the program print "Motion Detected!" when there is no motion because LOW is equal to 0V? To clarify my question even more, why is 'pirState' checking for a LOW input and if it detects a LOW input, why is the program printing "Motion Detected!" Wouldn't it make sense to say that the "Motion Ended!" because isn't LOW = 0V?
-
Same thing for the else statement: Why is 'pirState' checking for a HIGH input and if it does detect a HIGH input, why is it printing that the "Motion Ended!" instead of "Motion Detected!" because isn't HIGH = 5V?
-
Lastly, directly after these statements, why is 'pirState' being assigned HIGH or LOW?