Rotary Encoder KY40 with Interrupt

enjoyneering:
you are doing it wrong:

  • The encoder uses the Manchester code. You must read A & B at the same time, otherwise you will have wrong counts due to noise, debounce...
  • pins and ports are hardcoded and can only be used with atmega328 / 168

The only reason you get a decent result with your code is because the atmega328 & arduino framework is so slow and cannot catch the noise yet. :slight_smile: But the encoder is aging & debounce will increase....

Try your code on fast Cortex MCU, for example, STM32F103xxxx or ESP8266 - you will be surprised. Ohh but you can't - pins and ports are hardcoded

So how long of a delay between the interrupt triggering (pin2) and the Reading of Pin3?
(this should be almost instantaneous.)
We know the Clock pin Just went HIGH (Pin2). the callback immediately reads the Data Pin 3 which is either HIGH or LOW. Now we know that the direction of rotation. and can make a count.
You could add some sort of debounce timer on the interrupt maybe turn off interrupts for a short period of time. the Data pin is in the middle of its pulse and shouldn't be bouncing by now.
What do you think?
Z
Z