#include <Encoder.h> // https://www.pjrc.com/teensy/td_libs_Encoder.html
#include <Toggle.h> // https://github.com/Dlloydev/Toggle
const byte encoderCLKPin = 6;
const byte encoderDTPin = 3;
Encoder encoder(encoderDTPin, encoderCLKPin);
long encoderPosition;
class Buttons {
public:
const char * name;
const byte pin;
Toggle button;
Buttons(const char *n, const byte p) : name(n), pin(p), button(p) {};
};
Buttons buttons[] = {{"green", 2}, {"white", 5}, {"yellow", 11}, {"blue", 7}, {"red", 8}};
bool encoderChanged() {
long newPos = encoder.read() >> 2; // 4 ticks par click, divide by 4
if (newPos != encoderPosition) {
encoderPosition = newPos;
return true;
}
return false;
}
void setup() {
for (Buttons& b : buttons) b.button.begin(b.pin);
Serial.begin(115200);
}
void loop() {
if (encoderChanged()) Serial.println(-encoderPosition); // negative as it turns the "wrong" way
for (Buttons& b : buttons) {
b.button.poll();
if (b.button.onPress()) {
Serial.print(b.name);
Serial.println(" pressed");
}
if (b.button.onRelease()) {
Serial.print(b.name);
Serial.println(" released");
}
}
}