Skip to content

Example 04: Rotary encoder

Alexander Spiridonov edited this page Dec 27, 2023 · 4 revisions

Additional documentation for an example supplied with the KeyDetector library that demonstrates how to get readings of rotary encoder with built-in button using library (since version 1.2.0).

About

This example shows how KeyDetector can be used to detect rotation of a knob of a rotary encoder and its built-in push-button presses. Rotating the knob and pressing button at the same time will print corresponding messages.

Parts List

  • Arduino UNO or compatible
  • Rotary encoder with built-in button (e.g.)

Schematic

Schematic is simple. Three signal terminals of rotary encoder (two for rotation direction, one for button) are connected to the input pins of Arduino initilized with INPUT_PULLUP mode with internal pullup resistors activated (alternatively it is possible to connect terminals using external pullup 10kOhm resistors and INPUT mode). You may wish to implement additional debounce filtering to minify chances of false readings at the moment of button press (or try to increase value of the debounceDelay parameter during library initialization).

Breadboard

Connect channel A output (also called channel 1, CLK, etc.) of encoder to Arduino input pin 2, channel B output (also called channel 2, DT, etc.) to pin 3, first button output (usually called SW) to pin 4. Connect second button output (if present) and ground terminals of encoder to ground. Connect power terminal (if present) to 5V or 3.3V (depending on Arduino board being used).

Note that it may be required to swap channel terminals of encoder if direction of rotation is determined incorrectly.

Sketch

Annotated sketch is supplied with the library and can be found at "examples/Example-04_Encoder/Example-04_Encoder.ino".

Simulator

Simulation of this example is available on Wokwi. It is possible to interact with the simulation using mouse or keyboard with arrow keys and a spacebar (make sure to focus the encoder by clicking on it first).

Run

After compiling and uploading sketch to Arduino, open Serial Monitor and start rotating knob of the encoder and pressing its button. Message with direction of rotation will be printed (e.g. Rotation CW or Rotation CCW) for each step of rotation. Pressing button in combination with rotation will result in a message Rotation CW with button pressed (or Rotation CCW with button pressed) being printed. Additional messages will appear on release events (i.e. when button being released or on conclusion of each step of rotation).