// multiple encoders
// https://forum.arduino.cc/t/need-help-using-multiple-5-pin-rotary-encoders/1442587/
byte clockpin[] = { 2, 5, 8, 11, 14, 17 }; // "clock" pin array
byte datapin[] = { 3, 6, 9, 12, 15, 18 }; // "data" pin array
byte pushpin[] = { 4, 7, 10, 13, 16, 19 }; // "push" pin array
const byte arraysize = sizeof(clockpin) / sizeof(clockpin[0]); // number of encoders
byte pushstate[arraysize]; // state of each button
byte clockstate[arraysize], lastclockstate[arraysize], datastate[arraysize]; // states
byte encocount[arraysize]; // encoders count 0 to 255
byte pushcount[arraysize]; // pushbuttons count 0 to 255
unsigned long pushtimer[arraysize], timeout = 90; // adjust timeout for lowest value
#define BAUD 115200
void setup() {
Serial.begin(BAUD); // initialize Serial Monitor
for (byte i = 0; i < arraysize; i++) { // configure DIO pins
pinMode(clockpin[i], INPUT_PULLUP); //
pinMode(datapin[i], INPUT_PULLUP); //
pinMode(pushpin[i], INPUT_PULLUP); //
lastclockstate[i] = digitalRead(clockpin[i]); // first state reading
}
}
void loop() {
for (byte i = 0; i < arraysize; i++) {
// pushbutton
pushstate[i] = digitalRead(pushpin[i]); // read each pushbotton
if ((pushstate[i] == LOW) && (millis() - pushtimer[i] > timeout)) { // debounce pushbutton
pushtimer[i] = millis(); // set new timer
++pushcount[i]; // increment pushbutton count
showstates("Button : ", i, " | Presscount: ", pushcount[i]); // send data to formatter
}
// clockstate
clockstate[i] = digitalRead(clockpin[i]); // read clock state for each encoder
if (clockstate[i] != lastclockstate[i]) { // if clock state changed
lastclockstate[i] = clockstate[i]; // store state
// datastate
datastate[i] = digitalRead(datapin[i]); // datastate for each encoder
if (datastate[i] == 1 && clockstate[i] == 0) { // states for CC rotation
encocount[i]++; // increment counter
showstates("Encoder: ", i, " | CW | Count: ", encocount[i]); // send data to formatter
}
if (datastate[i] == 0 && clockstate[i] == 0) { // states for CW rotation
encocount[i]--; // decrement counter
showstates("Encoder: ", i, " | CC | Count: ", encocount[i]); // send data to formatter
}
}
}
}
void showstates(char *name, int number, char *action, int count) { // Serial Monitor formatting
Serial.print(name);
Serial.print(number);
Serial.print(action);
Serial.print(count);
Serial.println();
}