/* 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 <TM1637.h>
#define ENCODER_CLK 32
#define ENCODER_DT 33
#define ENCODER_SW 25
TM1637 tm;
// Nilai counter
volatile int number = 0;
void setup() {
tm.begin(2, 4, 4); // clockpin, datapin, jumlah digit
tm.displayClear();
tm.setBrightness(7); // 1 s/d 7 | 1=mati, 7=paling terang
tm.displayInt(number);
// Initialize encoder pins
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}
void readEncoder() {
int dtValue = digitalRead(ENCODER_DT);
if (dtValue == HIGH) {
number++; // Clockwise
} else {
number--; // Counterclockwise
}
if (number < 0) number = 0;
if (number > 9999) number = 9999;
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = number;
interrupts();
return result;
}
void loop() {
tm.displayInt(getCounter());
delay(50);
}