/*
Arduino Forum
Topics: Delay() in main loop preventing ISR button detection
Sub-Category: Programming Questions
Category: Using Arduino
Link: https://forum.arduino.cc/t/delay-in-main-loop-preventing-isr-button-detection/1148422/14
*/
const byte buttonPin = 2;
const byte pressed = LOW;
const byte unPressed = HIGH;
const byte ledPin = 5;
unsigned long myBlinkTimer;
unsigned long myDebounceTimer;
boolean myLedState = LOW;
boolean ledpinActive = true;
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start");
digitalWrite(ledPin, LOW);
digitalWrite(LED_BUILTIN, LOW);
pinMode(buttonPin, INPUT_PULLUP); // Button Pin Mode
pinMode(ledPin, OUTPUT); // LED Pin Mode
pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN Pin Mode
}
void loop() {
ledpinActive = GetToggleSwitchState(buttonPin);
// check if 1005 milliseconds have passed by
if ( TimePeriodIsOver(myBlinkTimer,1005) ) {
// when REALLY 1005 milliseconds HAVE passed by
if (myLedState == LOW) {
myLedState = HIGH; // invert from LOW to HIGH
}
else {
myLedState = LOW; // invert from HIGH to LOW
}
}
digitalWrite(LED_BUILTIN, myLedState); // switch LED On/Off
// check if ledpin shall be switched on/off
if (ledpinActive == true) {
// only in case ledpinActive
digitalWrite(ledPin, myLedState); // switch LED on/off
}
else {
digitalWrite(ledPin, LOW); // keep LED off
}
}
// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - startOfPeriod >= TimePeriod ) {
// more time than TimePeriod has elapsed since last time if-condition was true
startOfPeriod = currentMillis; // a new period starts right here so set new starttime
return true;
}
else return false; // actual TimePeriod is NOT yet over
}
bool GetToggleSwitchState(byte pinNumber) {
// "static" makes variables persistant over function calls
static bool toggleState = false;
static bool lastToggleState = false;
static byte buttonStateOld = unPressed;
static unsigned long buttonScanStarted = 0;
unsigned long buttonDebounceTime = 50;
static unsigned long buttonDebounceTimer;
byte buttonStateNew;
if ( TimePeriodIsOver(buttonDebounceTimer, buttonDebounceTime) ) {
// if more time than buttonDebounceTime has passed by
// this means let pass by some time until
// bouncing of the button is over
buttonStateNew = digitalRead(pinNumber);
if (buttonStateNew != buttonStateOld) {
// if button-state has changed
buttonStateOld = buttonStateNew;
if (buttonStateNew == unPressed) {
// if button is released
toggleState = !toggleState; // toggle state-variable
} // the attention-mark is the NOT operator
} // which simply inverts the boolean state
} // !true = false NOT true is false
// !false = true NOT false is true
return toggleState;
}