deckle studioOpen in the editor

Arduino Uno: rotary encoder counter with 7-segment display

Rotary encoder counts, TM1637 displays.

  • Arduino Uno
  • KY-040
  • TM1637
Open in the simulatorNo account needed: press Simulate and it runs.

How it works

Operate the KY-040 rotary encoder in the schematic: clicking the left half turns it one detent left, the right half one detent right, and the middle presses the button (counter to 0). The sketch decodes the quadrature signals on CLK/DT, and the four-digit TM1637 display shows the value (TM1637Display library). The logic analyzer shows CLK and DT out of phase.

Wiring

Each line is one connection (net) and the pins it joins.

NetPins
GNDA1 GNDDS1 GNDSW1 GNDV1 −
5VA1 5VDS1 VCCSW1 +V1 +
CLKA1 D2SW1 CLK
DTA1 ~D3SW1 DT
SWA1 D4SW1 SW
TCLKA1 ~D5DS1 CLK
TDIOA1 ~D6DS1 DIO

Parts

Firmware

sketch.ino · 26 lines

// Rotary encoder KY-040 (CLK D2, DT D3, SW D4) sets a number, the TM1637 display (CLK D5, DIO D6)
// shows it; pressing resets it to 0
#include <TM1637Display.h>
const int CLK = 2, DT = 3, SW = 4;
TM1637Display display(5, 6);
int value = 0, lastClk;

void setup() {
  Serial.begin(115200);
  pinMode(CLK, INPUT); pinMode(DT, INPUT); pinMode(SW, INPUT_PULLUP);
  display.setBrightness(5);
  display.showNumberDec(value);
  lastClk = digitalRead(CLK);
}

void loop() {
  int clk = digitalRead(CLK);
  if (clk != lastClk && clk == LOW) {                 // one detent: CLK falls, DT gives the direction
    value += digitalRead(DT) != clk ? 1 : -1;
    value = constrain(value, -999, 9999);
    display.showNumberDec(value);
    Serial.println(value);
  }
  lastClk = clk;
  if (digitalRead(SW) == LOW) { value = 0; display.showNumberDec(value); Serial.println(F("Reset")); delay(250); }
}
Open in the simulator

More examples: Arduino