/*
https://playground.arduino.cc/Code/Timer1/
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
https://www.arduino.cc/reference/pt/language/functions/external-interrupts/detachinterrupt/
Tratamento de interrupção por borda em pino de entrada
O Arduino uno possui duas entradas de interrupção externa, que estão nos pinos 2 (INT0) e
no pino 3 (INT1)
Nesse exemplo vamos simular um sistema que liga e desliga um alarme utilizando
a interrupção associada a entrada digital, sem uso da função Loop().
Esse botão deve armar e desarmar o alarme
Alarme acionado led Azul piscando
Alarme desacionado led Azul apagado
*/
#include <TimerOne.h>
// 1º Desafio
#define LedAlarme 13
#define LedArmado 12
#define LedAmarelo 11
#define LedLaranja 6 //
#define Botao1 2 // Interrupção 0
#define debounceDelay 10 // milliseconds to wait until button input stable *
int ledAlarmeStatus = LOW;
int ledArmadoStatus = LOW;
bool alarmeArmado = false;
void setup() {
pinMode(LedAlarme, OUTPUT);
pinMode(LedArmado, OUTPUT);
pinMode(LedLaranja, OUTPUT);
pinMode(LedAmarelo, OUTPUT);
pinMode(Botao1, INPUT_PULLUP);
digitalWrite(LedLaranja, LOW);
attachInterrupt(digitalPinToInterrupt(Botao1), toogle_Alarme, LOW);
}
void loop() {
digitalWrite(LedAmarelo, !digitalRead(LedAmarelo));
delay(500);
}
void alarme_Acao() {
digitalWrite(LedAlarme, !digitalRead(LedAlarme));
digitalWrite(LedArmado, !digitalRead(LedArmado));
}
boolean debounce(int pin)
{
boolean state;
boolean previousState;
previousState = digitalRead(pin); // Armazena o estado da entrada digital
for (int counter = 0; counter < debounceDelay; counter++)
{
delay(1); // Aguarda 1 milisegundo
state = digitalRead(pin); // Leitura da entrada digital
if ( state != previousState)
{
counter = 0; // Zera o contador de mudanças de estado da entrada digital
previousState = state; // Salva o estado atual da entrada digital
}
}
// Só virá aqui quando o estado da entrada digital estiver estável por mais tempo que o período de debounce
return state;
}
void toogle_Alarme() {
if (debounce(Botao1)) {
if (alarmeArmado) {
alarmeArmado = false;
digitalWrite(LedLaranja, LOW);
Timer1.detachInterrupt();
digitalWrite(LedAlarme, LOW);
digitalWrite(LedArmado, LOW);
} else {
alarmeArmado = true;
digitalWrite(LedArmado, HIGH);
digitalWrite(LedLaranja, HIGH);
Timer1.initialize(1000000); // Ajuste em microsegundos
Timer1.attachInterrupt(alarme_Acao);
}
}
}