/* A simple program to blink the LED every 500 milliseconds.
When the push button is pressed the LED blinking frequency should be double.
(use hardware interrupts).*/
// Pin definitions
#define BUTTON_PIN 3
#define LED_PIN 13
// LED blinking stuff
int blinkDelay; // LED blink delay
bool doubledFrequencyState = false; // whether LED blinking frequency is fast (true = 250ms/doubled) or slow (false = 500ms)
// Debouncing timing
unsigned long debounceDuration = 50; // how long to wait before validating next change in button state (millis)
unsigned long lastInterrupt = 0; // starting point to compare debounce duration to
unsigned long interruptTime; // time program was interrupted
void setup() {
// setup serial
Serial.begin(115200);
// Setup LED pin as output
pinMode(LED_PIN, OUTPUT);
// Setup button pins with internal pull resistors
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Interrupts attached for button - triggered when pin goes from low to high.
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), toggleLEDSpeed, RISING);
}
//ISR - external interupt to toggle the doubled frequency state with debouncing
void toggleLEDSpeed(){
// Set interrupt time to number of ms passed since program started running
interruptTime = millis();
// Only start the button functionality if enough time has past (i.e. update time is greater than debounce duration)
if (interruptTime - lastInterrupt > debounceDuration) {
// Update starting point for the debounce timer
lastInterrupt = interruptTime;
// toggle state
doubledFrequencyState = !doubledFrequencyState;
}
}
void loop() {
// Decide blink frequency depending on button press
if (doubledFrequencyState) {
blinkDelay = 250;
Serial.print("Blink delay is: ");
Serial.println(blinkDelay);
} else {
blinkDelay = 500;
Serial.print("Blink delay is: ");
Serial.println(blinkDelay);
}
// Blink LED depending on delay
digitalWrite(LED_PIN, HIGH);
delay(blinkDelay);
digitalWrite(LED_PIN, LOW);
delay(blinkDelay);
}