Rotary encoders
Alternative rotary encoder
This sketch demonstrates an alternative implementation of a rotary encoder in pull-up configuration.
With this alternative approach you can instantiate all your objects first, while setting the handlers at a later point. This is especially handy in larger projects where you have to access other objects from the handlers. And you can't access an object if it hasn't been instantiated yet. To illustrate this problem further, in the approach described in the basic example you will quickly run into problems as you have to keep track of the order of instantiation, which can become messy very quickly.
The code
#include <CtrlEnc.h>
// Create a rotary encoder with the clk pin number & dt pin number.
CtrlEnc encoder(1, 2);
// Define an onTurnLeft handler.
void onTurnLeft() {
Serial.println("Alternative rotary encoder turn left");
}
// Define an onTurnRight handler.
void onTurnRight() {
Serial.println("Alternative rotary encoder turn right");
}
void setup() {
Serial.begin(9600);
// Register the handlers with the rotary encoder object.
encoder.setOnTurnLeft(onTurnLeft);
encoder.setOnTurnRight(onTurnRight);
// 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();
}