// HW Pins required
#define ENCODER_SW A0 // RotaryEncoder SW Pin
#define ENCODER_DT 9 // RotaryEncoder DT Pin
#define ENCODER_CLK 11 // RotaryEncoder CLK Pin
#define DBOUNCE 200
int lastClk = HIGH;
volatile int counter = 0;
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
}
void loop() {
// Encoder routine. Updates counter if they are valid
// and if rotated a full indent
static bool encoder_clicked = false;
static uint8_t old_SW = 0; // old Switch value
static uint8_t new_SW = 0; // new SW Value
static uint8_t old_AB = 3; // Lookup table index
static int8_t encval = 0; // Encoder value
static const int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0}; // Lookup table
static uint32_t last_time=0;
uint32_t ms = millis();
old_AB <<=2; // Remember previous state
if (digitalRead(ENCODER_DT)) old_AB |= 0x02; // Add current state of pin A
if (digitalRead(ENCODER_CLK)) old_AB |= 0x01; // Add current state of pin B
// Encoder SW
new_SW = analogRead(ENCODER_SW);
if((ms-last_time) > DBOUNCE) {
last_time = ms;
if(new_SW != old_SW && new_SW < 100) {
Serial.println("Switch Pressed");
encoder_clicked = true;
}
old_SW = new_SW;
}
//
// Encoder rotation code
encval += enc_states[( old_AB & 0x0f )];
// Update counter if encoder has rotated a full indent, that is at least 4 steps
if( encval > 3 ) { // Four steps forward
counter++; // Increase counter
encval = 0;
Serial.println("Rotated counterclockwise ⏪");
}
else if( encval < -3 ) { // Four steps backwards
counter--; // Decrease counter
encval = 0;
Serial.println("Rotated clockwise ⏩");
}
if(counter > 5) counter = 5;
if(counter < 1) counter = 1;
encoder_clicked = false;
}