// #CONSTANTES
// El puslador se cambia de 11 a 2, ya que 2 tiene posibilidad a interrupciones
#define PULSADOR 2
#define ZUMBADOR 10
// #VARIABLES
// Se inicializa con 200ms
int tiempo_espera = 200;
int contador_led = 5;
unsigned long previousMillis = 0;
// Variable para usarse en la interrupción
volatile bool estado_interrupcion = {false};
// #FUNCIONES
// Interrupcion del botón
void interrupcionPulsador()
{
if (estado_interrupcion == false) {
if (digitalRead(PULSADOR) == HIGH) {
estado_interrupcion = true;
}
}
}
//Función para saber si el botón fue pulsado
bool pulsadorIO() {
int button_reading;
static bool switching_pending = false;
static long int elapse_timer;
if (estado_interrupcion == true) {
button_reading = digitalRead(PULSADOR);
if (button_reading == HIGH) {
switching_pending = true;
elapse_timer = millis();
}
if (switching_pending && button_reading == LOW) {
// El pulsador se configuró de manera que si se mantiene pulsado durante 10ms, es una pulsación
// si se pulsa más tiempo está haciendo trampa y se evita.
if (millis() - elapse_timer >= 10) {
switching_pending = false;
estado_interrupcion = false;
return true;
}
}
}
return false;
}
void setup() {
Serial.begin(9600); // Para debuguear el arduino y que salgan bien los println
// Se inicializan los 5 leds
for(int i = 5; i <= 9; i++) {
pinMode(i, OUTPUT);
}
// Se inicializa el pulsador como entrada para saber si el botón fue apachado
//pinMode(PULSADOR, INPUT);
pinMode(ZUMBADOR, OUTPUT);
pinMode(PULSADOR, INPUT);
// Es necesario utilizar interrupciones para verificar si el botón fue pulsado.
attachInterrupt(digitalPinToInterrupt(PULSADOR), interrupcionPulsador, RISING);
}
void loop() {
//En caso de que el tiempo llegue a 10ms, se resetea a 200ms nuevamente.
if (tiempo_espera <= 10) {
tiempo_espera = 200;
}
unsigned long currentMillis = millis();
// En cada vuelta apagamos todos los leds
for(int j = 5; j <= 9; j++) {
digitalWrite(j, LOW);
}
if (currentMillis - previousMillis >= tiempo_espera) {
previousMillis = currentMillis;
// Encendemos el led actual
digitalWrite(contador_led, HIGH);
if (contador_led >= 9) {
contador_led = 5;
} else {
contador_led = contador_led + 1;
}
}
// Si se encuentra en el LED del medio (pin 7), el botón fue pulsado, y la pulsación duró menos de
// 10ms, entonces asertó.
if (contador_led == 8 && pulsadorIO()) {
analogWrite(ZUMBADOR, 700);
delay(20);
previousMillis = currentMillis;
analogWrite(ZUMBADOR, 0);
// Por cada acierto, se resta 20
tiempo_espera = tiempo_espera - 20;
}
}