// Define encoder pins
const int encoderA_CLK = A0;
const int encoderA_DT = A1;
const int encoderB_CLK = A2;
const int encoderB_DT = A3;
// Define output pins
const int outputPins[6] = {2, 3, 4, 5, 6, 7};
// Variables to store encoder values
volatile int encoderA_value = 0;
volatile int encoderB_value = 0;
// Variables to store the last state of encoder pins
volatile int lastEncoderA_CLK;
volatile int lastEncoderA_DT;
volatile int lastEncoderB_CLK;
volatile int lastEncoderB_DT;
// Variable to store the last changed encoder
volatile bool lastChangedEncoderA = true;
void setup() {
// Set encoder pins as inputs
pinMode(encoderA_CLK, INPUT);
pinMode(encoderA_DT, INPUT);
pinMode(encoderB_CLK, INPUT);
pinMode(encoderB_DT, INPUT);
// Set output pins as outputs
for (int i = 0; i < 6; i++) {
pinMode(outputPins[i], OUTPUT);
}
// Initialize encoder states
lastEncoderA_CLK = digitalRead(encoderA_CLK);
lastEncoderA_DT = digitalRead(encoderA_DT);
lastEncoderB_CLK = digitalRead(encoderB_CLK);
lastEncoderB_DT = digitalRead(encoderB_DT);
}
void loop() {
// Read encoders and update values if changed
readEncoderA();
readEncoderB();
// Update output pins based on encoder values and last changed encoder
updateOutputPins();
}
void readEncoderA() {
int currentEncoderA_CLK = digitalRead(encoderA_CLK);
int currentEncoderA_DT = digitalRead(encoderA_DT);
if (currentEncoderA_CLK != lastEncoderA_CLK || currentEncoderA_DT != lastEncoderA_DT) {
if (currentEncoderA_CLK == LOW && lastEncoderA_CLK == HIGH) {
if (currentEncoderA_DT == LOW) {
encoderA_value--;
} else {
encoderA_value++;
}
}
lastEncoderA_CLK = currentEncoderA_CLK;
lastEncoderA_DT = currentEncoderA_DT;
lastChangedEncoderA = true;
}
}
void readEncoderB() {
int currentEncoderB_CLK = digitalRead(encoderB_CLK);
int currentEncoderB_DT = digitalRead(encoderB_DT);
if (currentEncoderB_CLK != lastEncoderB_CLK || currentEncoderB_DT != lastEncoderB_DT) {
if (currentEncoderB_CLK == LOW && lastEncoderB_CLK == HIGH) {
if (currentEncoderB_DT == LOW) {
encoderB_value--;
} else {
encoderB_value++;
}
}
lastEncoderB_CLK = currentEncoderB_CLK;
lastEncoderB_DT = currentEncoderB_DT;
lastChangedEncoderA = false;
}
}
void updateOutputPins() {
int valueToDisplay;
if (lastChangedEncoderA) {
valueToDisplay = encoderA_value;
} else {
valueToDisplay = encoderB_value;
}
for (int i = 0; i < 5; i++) {
digitalWrite(outputPins[i], bitRead(valueToDisplay, i));
}
digitalWrite(outputPins[5], lastChangedEncoderA ? LOW : HIGH);
}