ArduinoArduino UnoExact chip

Rotary encoder

A KY-040 counted with an interrupt on CLK; press to reset.

Rotary encoder in Argynix Lab

The code

sketch.inoC++
// KY-040 rotary encoder: an interrupt on CLK counts the detents; press it to reset.
const int CLK = 2;
const int DT = 3;
const int SW = 4;
volatile long count = 0;

void onClk() {
  if (digitalRead(CLK) == LOW) count += digitalRead(DT) == HIGH ? 1 : -1;
}

void setup() {
  pinMode(CLK, INPUT_PULLUP);
  pinMode(DT, INPUT_PULLUP);
  pinMode(SW, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(CLK), onClk, FALLING);
  Serial.begin(9600);
  Serial.println("Turn the knob");
}

void loop() {
  static long shown = 0;
  if (digitalRead(SW) == LOW) count = 0;
  if (count != shown) {
    shown = count;
    Serial.print("count:");
    Serial.println(shown);
  }
  delay(5);
}