Help with video game controller using rotary encoder on the Arduino Leonardo

would second recommendation by @Grumpy_Mike
running code based on library File>Examples>Encoder>Basic

// Leonardo - File>Examples>Encoder>Basic

/* Encoder Library - Basic Example
 * http://www.pjrc.com/teensy/td_libs_Encoder.html
 *
 * This example code is in the public domain.
 */

#include <Encoder.h>

// Change these two numbers to the pins connected to your encoder.
//   Best Performance: both pins have interrupt capability
//   Good Performance: only the first pin has interrupt capability
//   Low Performance:  neither pin has interrupt capability
//Encoder myEnc(4, 5);   // arduino uno pins 2 and 2
Encoder myEnc(2, 3);   // Leonardo pins 2 and 3
//   avoid using pins with LEDs attached
int switchPin=5;       // switch is pin 5

void setup() {
  Serial.begin(115200);
  Serial.println("Basic Encoder Test:");
    pinMode(switchPin, INPUT_PULLUP);
}

long oldPosition  = -999;

void loop() {
  static int sw=0, offset=0;
  // display switch on press and reset position to 0
  if(!digitalRead(switchPin) != sw) 
  {
    sw=!digitalRead(switchPin);
    if(!digitalRead(switchPin))Serial.println("switch");
    offset=oldPosition;
  }
  long newPosition = myEnc.read();
  if (newPosition != oldPosition) {
    oldPosition = newPosition;
    Serial.println(newPosition-offset);
  }
}

on a Leonardo gives results

1
2
3
4
5
6
7
8
7
8
7
6
5
4
3
2
1
0
-1
-2
-3
-4
-3
-4
-5
-6
-7
-8

photo running on a The Things UNO which is based on the Leonardo

2 Likes