/** * Copyright 2015, Matthijs Kooijman * * Permission is hereby granted, free of charge, to anyone * obtaining a copy of this document and accompanying files, to do * whatever they want with them without any restriction, including, but * not limited to, copying, modification and redistribution. * * NO WARRANTY OF ANY KIND IS PROVIDED. * * * This example shows a simple interrupt-based button-controlled blinky * led. * * When you press a button, the internal led will light up. After four * seconds, it turns off again. Everytime you press the button, this * timeout will reset and the led stays on for four more seconds. * * To use this, connect a button between GND and pin 2. This pin needs * to support an external interrupt, but most Arduinos seem to do so * (see the documentation for attachInterrupt or your Arduino). * * This example does not do any debouncing of the button, so be sure to * add that if you expand on this example and bouncing becomes a * problem. * * This example is identical to ButtonBlinky.ino, but disabled * interrupts in the loop() function to fix a race condition. */ // Be careful: Only some pins support interrupts. const uint8_t BUTTON_PIN = 2; const uint8_t BUTTON_INT = digitalPinToInterrupt(BUTTON_PIN); #if __cplusplus >= 201103L // Requires Arduino 1.6.6 static_assert(BUTTON_INT != (uint8_t)NOT_AN_INTERRUPT, "Interrupt not supported on selected pin"); #endif // Keep the led on for this long after each button press uint16_t TIMEOUT = 4000; // Time of the last buttonpress volatile uint32_t last_press = 0; // On a buttonpress: turn on led and record time void buttonPress() { digitalWrite(LED_BUILTIN, HIGH); last_press = millis(); } void setup () { // Set up button pinMode(BUTTON_PIN, INPUT_PULLUP); attachInterrupt(BUTTON_INT, buttonPress, FALLING); // Set up led pinMode(LED_BUILTIN, OUTPUT); } // If the led is on, but TIMEOUT ms has passed since the last press, // turn off the led void loop () { // Disable interrupts to prevent race conditions noInterrupts(); if (millis() - last_press >= TIMEOUT) digitalWrite(LED_BUILTIN, LOW); interrupts(); }