/* KY-040 Rotary Encoder Counter
Rotate clockwise to count up, counterclockwise to counter done.
Press to reset the counter.
Copyright (C) 2021, Uri Shaked
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
uint8_t ENCODER_CLK[2] = {2,5};
uint8_t ENCODER_DT[2] = {3,6};
uint8_t ENCODER_SW[2] = {4,7};
int counter[2] = {0,0};
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
// Initialize encoder pins
pinMode(ENCODER_CLK[0], INPUT);
pinMode(ENCODER_DT[0], INPUT);
pinMode(ENCODER_SW[0], INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER0_CLK[0]), readEncoder, FALLING);
}
void readEncoder(uint8_t idx) {
int dtValue = digitalRead(ENCODER_DT[idx]);
if (dtValue == HIGH) {
counter[idx]++; // Clockwise
}
if (dtValue == LOW) {
counter[idx]--; // Counterclockwise
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter(uint8_t idx) {
int result;
noInterrupts();
result = counter[idx];
interrupts();
return result;
}
void resetCounter(uint8_t idx) {
noInterrupts();
counter[idx] = 0;
interrupts();
}
void loop() {
lcd.setCursor(3, 0);
lcd.print("Counter:");
lcd.setCursor(7, 1);
lcd.print(getCounter(0));
lcd.print(" ");
if (digitalRead(ENCODER_SW[0]) == LOW) {
resetCounter(0);
}
}