#define LED LED_BUILTIN // digital pin connected to LED, for testing of switch code only
bool led_status = LOW; // start with LED off, for testing of switch code only
int button_switch = 2; // external interrupt pin
#define SWITCHED true // value if the button switch has been pressed
#define TRIGGERED true // controls interrupt handler
#define INTERRUPT_TRIGGER_TYPE RISING // interrupt triggered on a RISING input
#define DEBOUNCE 20 // time to wait in milliseconds
volatile bool interrupt_process_status = !TRIGGERED; // start with no switch press pending, ie false (!triggered)
bool initialisation_complete = false; // inhibit any interrupts until initialisation is complete
void button_interrupt_handler() {
if (initialisation_complete && interrupt_process_status == !TRIGGERED) {
if (digitalRead(button_switch) == HIGH) {
interrupt_process_status = TRIGGERED;
}
}
}
bool read_button() {
static bool switching_pending = false;
static unsigned long elapse_timer;
if (interrupt_process_status == TRIGGERED) {
int button_reading = digitalRead(button_switch);
if (button_reading == HIGH) {
switching_pending = true;
elapse_timer = millis();
}
if (switching_pending && button_reading == LOW) {
if (millis() - elapse_timer >= DEBOUNCE) {
switching_pending = false;
interrupt_process_status = !TRIGGERED;
return SWITCHED;
}
}
}
return !SWITCHED;
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(7, OUTPUT); // for testing
pinMode(button_switch, INPUT);
attachInterrupt(digitalPinToInterrupt(button_switch), button_interrupt_handler, INTERRUPT_TRIGGER_TYPE);
initialisation_complete = true;
}
void loop() {
if (read_button() == SWITCHED) {
led_status = !led_status;
digitalWrite(LED, led_status);
} else {
digitalWrite(7, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(7, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
}