// Librería para control LCD 16x2
#include <LiquidCrystal.h>
// Asignación de pines, control LCD: [ RS, EN, D4, D5, D6, D7 ]////////
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
int led = 8;
//Encoder rotatorio////////////////////////////////////////////////////
//Define entradas de encoder rotatorio
const int ENCODER_CLK = 2;
const int ENCODER_DT = 3;
const int ENCODER_SW = 4;
int counter = 0;
////////////////////////////////////////////////////////////////////////
void setup(void) {
Serial.begin(9600);
// Inicialización LCD con 16 columnas y 2 líneas////////////////////////
lcd.begin(16, 2); //Define configuracion LCD
// pinMode(led,OUTPUT); //Configura salida
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}
void loop() {
lcd.setCursor(0, 0);
lcd.print("Contador:");
lcd.setCursor(12, 0);
lcd.print(getCounter());
lcd.print(" ");
if (digitalRead(ENCODER_SW) == LOW) {
resetCounter();
}
}
//Encoder rotatorio////////////////////////////////////////////////////
void readEncoder() {
int dtValue = digitalRead(ENCODER_DT);
if (dtValue == HIGH) {
counter++;
}
if (dtValue == LOW) {
counter--;
}
}
// Obtiene el valor del contador, deshabilitando las interrupciones.
// Esto asegura que readEncoder() no cambie el valor mientras lo leemos.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
void resetCounter() {
noInterrupts();
counter = 0;
interrupts();
}