Interfacing with Rotary Encoder

Rotary Banner
Rotary encoder or rotary switch are mechanical sensors that can track the direction and distance of a rotation movement.

It is commonly used as digital volume knobs (where the rotation is endless, unlike a potentiometer).

volumek_600x350[1]

More advance types of rotary encoders are used on robots to track the distance of its’ movement.

I got this rotary switch breakout board from Cytron to test it out.

IMG_1348

It has two outputs, the A and B channel. When the knob is being rotated, pulses will appear at the outputs A and B.

Depending on the phase difference of these pulses, we can determine the direction of the rotation. Also, we can calculate how much the knob has been rotated by calculating the output pulses.

I’ve drawn out a diagram to explain it further.

rotary_explanation1

In short, when the knob is being rotated clockwise, A leads B by 90 degress. When the knob is being rotated counter-clockwise, A lags B by 90 degrees.

With this characteristics in mind, we can program the microcontroller as such.

rotary_flowchart

To detect every rising edge of signal A, we have to use interrupts. The pseudocode in the flowchart above will be located in the ISR. Interrupt Service Routine (ISR) is a block of code that the microcontroller will jump to when an interrupt is triggered.

In Arduino, we can use the attachInterrupt function to declare an interrupt.

rotary_code

In my example code, I’ve written attachInterrupt(0, count, RISING).

0 means Interrupt number 0, which is located on Digital Pin 2 of the Arduino Uno. “count” is the name of a function that contains the ISR code and “RISING” is the interrupt mode.

There are four modes available, RISING (triggers on rising edge), FALLING (triggers on falling edge), CHANGE (triggers on both rising and falling edge) and LOW (triggers when the pin is low).

To demonstrate the output of the rotary encoder, I’ve used 8 LEDs. Think of it like a volume level.

IMG_1350

Here’s a video of the circuit in action.

The code can be downloaded below.

Download Code

Leave a Reply