Rotary Encoder is a cool component

Rotary Encoder is a cool component

I found this little rotary encoder. At first i didn't know what that is, it looks like a potentiometer, but pins are weird. The pins are: GND, VCC, MS, DT, CLK It turns out it's a mechanical rotary encoder.

What's rotary encoder used for?
First thing that comes to mind is volume button in my car. It can turn in any direction indefinitely. It's a cool thing, and I'm planning to pair it with stepper motor so that stepper motor follows my input in the encoder. In other words where i turn encoder, the motor should follow it 1 to 1.

To the wiring and code:

Usually encoders will have a button integrated in them, so that when knob is pressed it acts as a button. That's why there is one extra pin that i did not connect, i don't need that button currently.

Arduino code:

#define CLK 2
#define DT  3

volatile int position = 0;

void setup() {
  pinMode(CLK, INPUT);
  pinMode(DT, INPUT);

  Serial.begin(9600);

  // Trigger interrupt when CLK changes
  attachInterrupt(digitalPinToInterrupt(CLK), readEncoder, CHANGE);
}

void loop() {
  static int lastPosition = 0;

  if (position != lastPosition) {
    Serial.print("Position: ");
    Serial.println(position);
    lastPosition = position;
  }
}

// Interrupt function
void readEncoder() {
  int clkState = digitalRead(CLK);
  int dtState  = digitalRead(DT);

  if (clkState == dtState) {
    position++;   // clockwise
  } else {
    position--;   // counterclockwise
  }
}

The code uses interrupts. I don't like interrupts in the code, because I'm bad at it, but for this they are crucial. It's possible to make code work without interrupts, but it's less accurate, and sometimes it misses input, or just skips the input.

The serial monitor will display current position of the encoder.

That's all. Thanks for reading!