# Lesson 17 Rotary Encoder

##### Share for us

Introduction

A rotary encoder is an electro-mechanical device that converts the angular position or motion of a shaft or axle to analog or digital code. Rotary encoders are usually placed at the side which is perpendicular to the shaft. They act as sensors for detecting angle, speed, length, position, and acceleration in automation field.

Components

– 1 * SunFounder Uno board

– 1 * USB cable

– 1 * Rotary encoder module

– 1 * 5-Pin anti-reverse cable

Principle

A rotary encoder is an electronic switch with a set of regular pulses with strictly timing sequence. When used with IC, it can achieve increment, decrement, page turning and other operations such as mouse scrolling, menu selection, and so on. There are mainly two types of rotary encoders: absolute and incremental (relative) encoders. An incremental one is used in this experiment.

Most rotary encoders have 5 pins with three functions of turning left & right and pressing down. Pin 1 and pin 2 are switch wiring terminals used to press. Pin 4 is generally connected to ground. Pin 3 and pin 5 are first connected to a pull-up resistor and then to VCC and they can generate two-phase square waves whose phase difference is 90°. Usually these waves are called channel A and channel B as shown below:

As shown above, when channel A changes from high level to low level, if channel B is high level, it indicates the rotary encoder spins clockwise (CW); if at that moment channel B is low level, it means spins counterclockwise (CCW). So if we read the value of channel B when channel A is low level, we can know in which direction the rotary encoder rotates.

PrincipleSee the schematic diagram of the Rotary Encoder module below. From it we can see that pin 3 of the rotary encoder, namely CLK on the module, is channel B. Pin 5, which is DT, is channel A. To know the rotational direction of the recorder, just read the value of CLK and DT.

This method is concluded by observing the output waveforms of the CLK and DT pin with an oscilloscope by rotating the rotary encoder. You can have a try.

Experimental Procedures

Step 1: Build the circuit

Step 2: Open the code file

Step 3: Select correct Board and Port

Step 4: Upload the sketch to the SunFounder Uno board

Open Serial Monitor and you will see the angular displacement of the rotary encoder printed on the window. Spin the shaft of the rotary encoder clockwise, and the angular displacement will decrease; spin it counterclockwise, the value increase. Press it down, and the value will be reset and restore to the initial state.

Code