Rotary Encoder

From EWIKI
Jump to navigation Jump to search

How to connect a rotary encoder directly to an Arduino or any other microcontroller.

RotaryEncoder Direct.png


OK, this wastes a pin, but keep is simple.

Example 1: Using Interrupts

#define ENC_PIN_BT 2
#define ENC_PIN_CL 3 
#define ENC_PIN_DT 4
// ---------------------------------------------------------------------
void setup() {
  pinMode( ENC_PIN_CL, INPUT_PULLUP );
  pinMode( ENC_PIN_DT, INPUT_PULLUP );
  pinMode( ENC_PIN_BT, INPUT_PULLUP );
  attachInterrupt( 0, checkEncoder, RISING );  
  attachInterrupt( 1, buttonPress, FALLING ); 
}
// ---------------------------------------------------------------------
void checkEncoder() {
  byte dta = digitalRead( ENC_PIN_DT );
  if ( dta ) {  
    // rotate right
    ...
  } else { 
    // rotate left 
    ...
  }
}
// ---------------------------------------------------------------------
void buttonPress() {
  ...
}

Caution: Interrupt functions are limited, e.g. can't use delay()

Example 2: Using Loop

#define ENCODER0_GND 2
#define ENCODER0_CLK 3
#define ENCODER0_DTA 4
#define ENCODER0_BTN 5
// ---------------------------------------------------------------------
boolean encoder0btnOK = true;
byte encoder0dta      = LOW;
byte encoder0dtaLast  = LOW;
// ---------------------------------------------------------------------
void setup(void) {
   pinMode( ENCODER0_GND, OUTPUT );
   pinMode( ENCODER0_CLK, INPUT_PULLUP );
   pinMode( ENCODER0_DTA, INPUT_PULLUP );
   pinMode( ENCODER0_BTN, INPUT_PULLUP );
   digitalWrite( ENCODER0_GND, LOW );
}
// ---------------------------------------------------------------------
void loop() {
  // check encoder button
  if ( digitalRead( ENCODER0_BTN ) == LOW ) { encoder0btnOK = true; }
  if ( ( encoder0btnOK ) && ( digitalRead( ENCODER0_BTN ) == HIGH ) ) {
    encoder0btnOK = false;
    encoder0buttonAction();
  }
  // check for rotation
  encoder0dta = digitalRead( ENCODER0_DTA );
  if ( ( encoder0dtaLast == LOW ) && ( encoder0dta == HIGH ) ) {
    if ( digitalRead( ENCODER0_CLK ) == LOW ) { /
      encoder0rotateRight();
    } else { 
      encoder0rotateLeft();
    }
  } 
  encoder0dtaLast = encoder0dta;
}
// ---------------------------------------------------------------------
void encoder0buttonAction() {
   // do something
}
void encoder0rotateRight() {
   // do something
}
void encoder0rotateLeft() {
   // do something
}