#include <TM1637.h> // Grove 4-Digit Display
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Pantalla I2C
const int CLK = 19;
const int DIO = 18;
TM1637 tm(CLK, DIO); // TM1637 display
#define I2C_ADDR 0x27
LiquidCrystal_I2C lcd(I2C_ADDR, 20, 4); // LCD I2C 20x4
// Estructura para botón
struct Button {
const uint8_t PIN;
bool pressed;
uint32_t lastDebounceTime;
};
Button button_up = {17, false, 0};
Button button_down = {16, false, 0};
volatile int counter = 0;
const uint32_t debounceDelay = 50; // ms para antirrebote
// ISR para botón UP
void IRAM_ATTR isr_button_up() {
uint32_t currentTime = millis();
if ((currentTime - button_up.lastDebounceTime) > debounceDelay) {
button_up.lastDebounceTime = currentTime;
button_up.pressed = true;
counter++;
}
}
// ISR para botón DOWN
void IRAM_ATTR isr_button_down() {
uint32_t currentTime = millis();
if ((currentTime - button_down.lastDebounceTime) > debounceDelay) {
button_down.lastDebounceTime = currentTime;
button_down.pressed = true;
counter--;
}
}
void setup() {
Serial.begin(115200);
Serial.println("Iniciando...");
// Configurar botones
pinMode(button_up.PIN, INPUT_PULLUP);
pinMode(button_down.PIN, INPUT_PULLUP);
attachInterrupt(button_up.PIN, isr_button_up, FALLING);
attachInterrupt(button_down.PIN, isr_button_down, FALLING);
// Inicializar TM1637
tm.init();
tm.set(BRIGHT_TYPICAL);
// Inicializar LCD
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Motor:");
delay(200);
}
void loop() {
static int lastValue = -999;
// Si hubo cambio
if (button_up.pressed || button_down.pressed) {
button_up.pressed = false;
button_down.pressed = false;
Serial.printf("Contador: %d\n", counter);
// Mostrar en LCD
lcd.setCursor(0, 1);
lcd.print("Contador: ");
lcd.setCursor(10, 1);
lcd.print(counter);
// Mostrar en display 7 seg (máx. 4 dígitos)
int val = constrain(counter, -999, 9999); // prevenir overflow
tm.displayNum(val, true); // true: padding con ceros si necesario
lastValue = counter;
}
// Después de 1 minuto: desactiva interrupciones (solo para prueba)
static uint32_t lastMillis = 0;
if (millis() - lastMillis > 60000) {
lastMillis = millis();
detachInterrupt(button_up.PIN);
detachInterrupt(button_down.PIN);
Serial.println("Interrupciones deshabilitadas.");
}
}