Example Code for Arduino-Rotary Encoder and Button Control

Last revision 2025/12/29

This article offers a comprehensive guide on using Arduino to control a rotary encoder and button, featuring sample code and setup instructions. It's perfect for hobbyists looking to enhance their projects with precise input handling.

Hardware Preparation

  • DFRduino UNO (or similar) x 1
  • EC11 Rotary Encoder Module x 1
  • M-M/F-M/F-F Jumper wires

Software Preparation

Wiring Diagram

EC11 Arduino Connection

Sample Code

int encoderPinA = 2;
int encoderPinB = 3;
int buttonPin = 4;

volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

long readEncoderValue(void){
    return encoderValue/4;
}

boolean isButtonPushDown(void){
  if(!digitalRead(buttonPin)){
    delay(5);
    if(!digitalRead(buttonPin))
      return true;
  }
  return false;
}

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

  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  pinMode(buttonPin, INPUT);

  digitalWrite(encoderPinA, HIGH); //turn pullup resistor on
  digitalWrite(encoderPinB, HIGH); //turn pullup resistor on

  //call updateEncoder() when any high/low changed seen
  //on interrupt 0 (pin 2), or interrupt 1 (pin 3)
  attachInterrupt(0, updateEncoder, CHANGE);
  attachInterrupt(1, updateEncoder, CHANGE);

}

void loop(){
  //Do stuff here

  if(isButtonPushDown()){
    Serial.println("you push button down!!!");
  }
  Serial.println(readEncoderValue());
  delay(50); //just here to slow down the output, and show it will work  even during a delay
}


void updateEncoder(){
  int MSB = digitalRead(encoderPinA); //MSB = most significant bit
  int LSB = digitalRead(encoderPinB); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue   ;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time
}

Result

  • Clockwise Rotation: 1
  • Anticlockwise Rotation: -1
  • Press the Button: you push button down

Printing Info

Was this article helpful?

TOP