Rotary Encoder Interface Experiment

Rotary Encoder Interface Experiment

Introduction

A rotary encoder is an input device that detects rotational motion and converts it into electrical signals. These signals can determine the direction and amount of rotation. This experiment demonstrates how to interface a rotary encoder with an Arduino to read and display its position and direction.

Components Needed

Circuit Setup

Connect the rotary encoder to the Arduino as follows:

  1. Connect the CLK pin of the encoder to Arduino pin 2.
  2. Connect the DT pin of the encoder to Arduino pin 3.
  3. Connect the SW (switch) pin of the encoder to Arduino pin 4.
  4. Connect the VCC pin to the Arduino 5V pin.
  5. Connect the GND pin to the Arduino GND pin.

Code for Rotary Encoder

Upload the following code to your Arduino to interface with the rotary encoder:


// Rotary Encoder Example Code

#define CLK 2  // Clock pin
#define DT 3   // Data pin
#define SW 4   // Switch pin

int counter = 0;      // Counter to track rotation
int currentStateCLK;  // Current state of CLK
int lastStateCLK;     // Previous state of CLK
int buttonState;      // Current state of the button
int lastButtonState;  // Previous state of the button

void setup() {
    pinMode(CLK, INPUT);
    pinMode(DT, INPUT);
    pinMode(SW, INPUT_PULLUP); // Enable pull-up resistor for the switch pin
    Serial.begin(9600);

    // Read the initial state of CLK
    lastStateCLK = digitalRead(CLK);
}

void loop() {
    // Read the current state of CLK
    currentStateCLK = digitalRead(CLK);

    // Check if the state of CLK has changed
    if (currentStateCLK != lastStateCLK) {
        // If DT state is different from CLK, the encoder is rotating clockwise
        if (digitalRead(DT) != currentStateCLK) {
            counter++;
        } else {
            counter--;
        }
        Serial.print("Counter: ");
        Serial.println(counter);
    }

    // Update the previous state of CLK
    lastStateCLK = currentStateCLK;

    // Read the state of the button
    buttonState = digitalRead(SW);

    // Check if the button has been pressed
    if (buttonState == LOW && lastButtonState == HIGH) {
        Serial.println("Button Pressed!");
        delay(50); // Debounce delay
    }

    // Update the previous button state
    lastButtonState = buttonState;

    delay(5); // Short delay to improve stability
}
            

Explanation

Applications of Rotary Encoders

Rotary encoders are widely used in various applications, such as:

Troubleshooting