You can download the library here: https://github.com/frodofski/Encoder_Polling_V2
Here is the example sketch:
The library is super easy to use, as it has only four functions:
- encoder_begin() starts the library by setting up timer2 (note: this may conflict with the tone library)
- attach_encoder(encNum, pin_A, pin_B) attaches an encoder to pin_A and pin_B, and sets these pins as inputs. encNum can equal 0, 1, 2, 3, or 4, allowing for up to five rotary encoders. The library will now start polling those two input pins.
- detach_encoder(encNum) will detach the input pins corresponding to that encoder, and it will stop polling those two input pins. The pins can now be used as regular io again.
- encoder_data(encNum) returns the state of the specified encoder. It returns a 1 or -1 if the encoder has turned, depending on the direction of rotation. It will return a 0 if the encoder has not turned, or if there is no encoder attached to that particular encNum.
The library will store that last known direction of the rotary encoder, until the encoder_data() function has been called for that encoder. This allows you to run the main sketch at any speed, without having to worry about missing a step.
Finally, you may need to use a hardware debouncer for each of the input pins if your're not using an optical encoder, or if your mechanical rotary encoder is particularly bouncy.