Rotary Encoder Module

Rotary Encoder Module

Interface of a Rotary Encoder Module

A rotary encoder module is a small electronic device that converts mechanical rotation into electrical signals. It typically has three or four pins, which are used to output the encoder’s signals. The most common pins are:

  • CLK: The clock pin outputs a square wave signal that is synchronized with the encoder’s rotation.
  • DT: The data pin outputs a square wave signal that is delayed by 90 degrees from the clock signal. This allows the encoder’s direction of rotation to be determined.
  • SW: The switch pin outputs a high signal when the encoder’s switch is pressed.
  • GND: The ground pin provides a common ground reference for the encoder’s signals.

Working Principle of a Rotary Encoder

A rotary encoder works by using a disk with evenly spaced slots. As the disk rotates, the slots pass by a sensor, which generates a series of square wave signals. The number of pulses generated per rotation depends on the number of slots on the disk.

The direction of rotation can be determined by comparing the signals from the clock and data pins. If the data pin is leading the clock pin, then the encoder is rotating in the clockwise direction. If the data pin is lagging the clock pin, then the encoder is rotating in the counter-clockwise direction.

Code Examples

Here is some code that can be used to interface with a rotary encoder module in Arduino:

C++

#include <RotaryEncoder.h>

RotaryEncoder encoder(2, 3); // CLK, DT

void setup() {
  Serial.begin(9600);
}

void loop() {
  int position = encoder.getPosition();
  Serial.println(position);
}

This code will print the current position of the rotary encoder to the serial monitor. The position value will be incremented or decremented depending on the direction of rotation.

Here is another code example that uses the rotary encoder to control a servo motor:

C++

#include <RotaryEncoder.h>
#include <Servo.h>

RotaryEncoder encoder(2, 3); // CLK, DT
Servo servo;

void setup() {
  Serial.begin(9600);
  servo.attach(9);
}

void loop() {
  int position = encoder.getPosition();
  servo.write(position);
}

Use code with caution. Learn morecontent_copy

This code will use the rotary encoder to control a servo motor. The position of the servo motor will be updated depending on the position of the rotary encoder.

Conclusion

Rotary encoders are a versatile and useful input device. They can be used to control a variety of devices, including servo motors, stepper motors, and displays. The code examples above provide a simple introduction to how to interface with a rotary encoder module in Arduino.

x