Potentiometers
Alternative potentiometer
This sketch demonstrates an alternative implementation of a potentiometer.
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 <CtrlPot.h>
// Create a potentiometer with the pin number, max. output value & sensitivity margin (can be 0.01 to 100).
CtrlPot potentiometer(A0, 100, 0.05);
// Define an onValueChange handler
void onValueChange(int value) {
Serial.print("Alternative pot value: ");
Serial.println(value);
}
void setup() {
Serial.begin(9600);
// Register the handler with the potentiometer object.
potentiometer.setOnValueChange(onValueChange);
}
void loop() {
// The process method will keep polling our potentiometer object and handle all it's functionality.
potentiometer.process();
}