Following previous discussion concerning use of delay to blink one or more LEDs, I thought of an original "doing two things at once" sketch to test my understanding. The concept I came up with is a PIR sensor which causes one LED to blink. My idea is that blink-with-delay will not work, because it interferes with the sensor's continuous changing input. Indeed, using blink-with-delay, the sensor triggers the LED, but the LED continues blinking without regard to changing sensor state. My "doing two things at once" sketch (copied below) responds to motion, and again when motion stops. But there is a problem. When motion stops, sometimes the LED returns to the off state, and sometimes it remains on -not blinking- just a steady on state. It then blinks again when motion is detected, and again at random goes dark or remains lit. I think I know what the problem is, but before I complicate matters, can I ask for expert evaluation of my sketch so far? Thanks.
const int pirPin = 3;
const int ledPin = 13;
int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
if (digitalRead(pirPin) == HIGH) {
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
}