Rotary Encoder reading wrong when using buttons

Hey all, I'm having an issue with my rotary encoder. I'm using it to control mouse inputs and works fine alone. The mouse moves accordingly to however fast I move my encoder. However, when I try to also track inputs for push buttons, it doesn't work anymore. Instead, it jitters back and forth and travels the opposite way of the turning direction before it eventually goes the right way. It also works normally at slower speeds, but doesn't at higher spin rates. It's like there is a threshold of how fast it can go until it works normally again. I don't think it is a mechanical problem because of this.

I'm using an arduino pro mirco that acts like an arduino leonardo and only has pins 2-10, 14-16, and A0-A3. I would try to use attachInterrupt, but I'm using 2 enocders.

I am debouncing the buttons and I have also tried to not debounce the buttons, but I still get the jitter. I am also checking button states and encoder states every cycle.

Help would be appreciated, thanks!


#define encA0 A0;
#define encB0 A1;

void setup



//by what factor should the mouse move at?
const int multi = 2;

//variable to track last state of data A pin
int lastState0 = LOW;

//checks the first encoder's direction. Outputs X-axis mouse movement
void encoder0()
  int readA0 = digitalRead (encA0); //read the state of the data A pin
  //if the previous state of the pinA pin is LOW and the new state is HIGH, detect a change and change position of mouse
  if((lastState0 == LOW) && (readA0 == HIGH)) 
    if(digitalRead(encB0) == HIGH) //since the B pin reads after the A pin to detect a change, if it is HIGH by the time A is detected to change, then do this
      Mouse.move(multi,0,0); //left
      Mouse.move(-1*multi,0,0); //right
  lastState0 = readA0;
  1. all pins have pin change interrupts available - indeed only pin 2 and 3 have the "external" interrupts - so you can connect them all to an interrupt if you want.
  2. please post all of your code. No doubt the problem is in the part you didn't post, it always is, such as delay() calls in your debounce functions, for example.

I’m trying a debounce helper called bounce2. these are the files included in my project. I have tried coding the debouncer myself, but it still had the same result. Unfortunately, I don’t have a copy of that code anymore.

ArduinoSDVX.ino (4.4 KB)

Bounce2.cpp (3.68 KB)

Bounce2.h (5.87 KB)

I like the Paull Stoffregen Encoder Library. It works flawlessly under all conditions.

You can help the library out by using at least one interrupt pin on each encoder. On the Micro, this can be pin 0, 1, 2, 3, or 7. Note that 0 and 1 are not used in the USB serial, so they are available if you aren't using hardware serial for any other purpose. They may be labelled TX and RX on your board.

I didn't notice that the micro had pins 0 and 1, I'll have to try it

The libarary works great! Thanks for the help, it's exactly what I needed.