#define blueLed 3 //Police light A
#define greenLed 2 //Police light B
#define buttonPin 4 // You had this ALSO defined as 2 on a previous post
#define flashInterval 150 // sets the LED toggle interval (so 150ms mean lights will flash on every 300ms)
#define debounceLength 10 // defines the length of debounce needed for the button
uint32_t currentTime; // a global 'shared' variable for holding the current time
static bool lightsOn = false; // a bool for holding if the lights are currently on or off.
void setup() {
pinMode(blueLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
currentTime = millis(); // update the current time
toggleLights(); // checks for button presses and toggles if the lights are on / off
if (lightsOn)
flashLights(); // if the toggle for lights is on, this will flash them at the flashInterval defined above.
}
void toggleLights() {
// a variable to capture the current time when a button is pressed. Used in debouncing.
static uint32_t capturedTimeButton;
// a variable to store the last previous state of the button, last time through loop.
static bool lastButtonState = HIGH;
bool currentButtonState = digitalRead(buttonPin); // read the button pin
if (currentButtonState != lastButtonState) { // if the button state has changed...
if (!currentButtonState) // and the current state is 'low/false' (i.e the button pin is being grounded)
capturedTimeButton = currentTime; // then we capture last time we recorded a grounding on the button pin
// if it's at least 10ms (defined as debounceLength above) after the last time we recorded a button pin grounding
if (currentTime - capturedTimeButton >= debounceLength) {
if (!lightsOn) // if the lights are currently NOT active...
lightsOn = true; // we make them active
else { // if they ARE currently active
lightsOn = false; // we turn the lights toggle off
digitalWrite(blueLed, LOW); // and actually turns the LED pins off
digitalWrite(greenLed, LOW);
}
}
}
// then we update the 'lastButtonsState' to match the current state so we can check 'if the button state has changed'
// on the next iteration through the loop.
lastButtonState = currentButtonState;
}
void flashLights() {
// a variable for storing the last time the LEDs were toggled
static uint32_t capturedTimeLights;
// if it's at least 150ms (defined above as flashInterval) after the last time we captured the time for the lights
if ((currentTime - capturedTimeLights) >= flashInterval) {
// then we get a new time capture for the lights
capturedTimeLights = currentTime;
// if blueLed is off, we set it on, If it is on, we set it off.
digitalWrite(blueLed, !digitalRead(blueLed));
// what ever blueLed is doing, we want greenLed to do the opposite
digitalWrite(greenLed, !digitalRead(blueLed));
}
}