Rotary encoders
Advanced rotary encoder
This sketch demonstrates a more advanced implementation of a rotary encoder in pull-up configuration.
With this approach you can extend the base class (CtrlEnc) into your own class, and expand on the base functionality as you please. The sky is the limit here. The inheriting class overrides the onTurnLeft & onTurnRight methods. Within these methods you can add your desired actions.
The code
#include <CtrlEnc.h>
// Extend the CtrlEnc class into a CustomEncoder class.
class CustomEncoder : public CtrlEnc
{
public:
CustomEncoder(uint8_t clk, uint8_t dt) : CtrlEnc(clk, dt) { }
protected:
void onTurnLeft() override
{
Serial.println("Advanced rotary encoder turn left");
}
void onTurnRight() override
{
Serial.println("Advanced rotary encoder turn right");
}
};
// Create a rotary encoder with the clk pin number & dt pin number.
CustomEncoder encoder(1, 2);
void setup() {
Serial.begin(9600);
// If you use external pull-up resistors, uncomment the following line:
// encoder.setPinMode(INPUT, PULL_UP);
// If you use external pull-down resistors, uncomment the following line:
// encoder.setPinMode(INPUT, PULL_DOWN);
// If you have a board that has internal pull-down resistors, and want to
// use those instead, you can uncomment the following line:
// encoder.setPinMode(INPUT_PULLDOWN);
// If you have a board that has internal pull-up resistors, and want to use those instead, you
// don't need to call the setPinMode() method, as the encoder is set to 'INPUT_PULLUP' by default.
}
void loop() {
// The process method will poll the rotary encoder object and handle all it's functionality.
encoder.process();
}