UKHeliBob:
max1994:
Why is it when
if (pirState == low )
{
pirState == HIGH;
}
That looks like an attempt to test pirState and if it is set to LOW then set it to HIGH but someone got it wrong. Look carefully at the number of = in each statement in the code.
No, the actual code is correct with only 1x = in the assignment; OP has mis-quoted.
He's asking about the actual logic, I think, and here's why it's like that:
At startup, the pirState is initialised as low:
int pirState = LOW; // we start, assuming no motion detected
Each time through loop(), the pir is read into val:
val = digitalRead(inputPin); // read input value
Let's take the case of the first ever motion detection since power up: that val will be high, and the pirState will be low, so we're here:
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 <<<<<<<<<<<<<<<<<<<<<<<< we just got here
We are really only concerned with NEW motion, so we set pirState as high:
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
That means, that next time through loop, which is running 150k times a second, val will still likely be high because there is still motion, but it's not NEW motion and since pirState is high because we just made it so, nothing happens.
I'll leave it to you to work through the logic of the reverse, when motion is no longer detected (val is low) but pirState is still high the very first time we detect motion has stopped.
edit: as PaulS pointed out in the mosquito thread, pirState is a crap name for that variable. It's more to do with the state of the motion, not the sensor itself- which is actually val- so a name with "motion" in it might be more apt. (Or is there such a word as "apter"?)
Come to think of it, val's a shit name too, maybe val should be renamed pirState and pirState should be named newMotion or something.