// Define button GPIO pins
const int buttonPins[9] = {23, 22, 21, 4, 18, 19, 25, 26, 27};
// Define rotary encoder GPIO pins
const int encoderPinCLK = 32; // CLK pin
const int encoderPinDT = 13; // DT pin
const int encoderButtonPin = 33; // SW pin
// Array to store the current and previous state of buttons
bool buttonStates[9];
bool lastButtonStates[9];
// Variables to store rotary encoder state
int lastEncoderCLKState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 5; // Debounce time in milliseconds
int encoderPosition = 0;
bool lastEncoderButtonState = HIGH;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize button pins as inputs with pull-up resistors
for (int i = 0; i < 9; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
buttonStates[i] = HIGH; // Assume button not pressed (HIGH due to pull-up)
lastButtonStates[i] = HIGH;
}
// Initialize rotary encoder pins
pinMode(encoderPinCLK, INPUT_PULLUP);
pinMode(encoderPinDT, INPUT_PULLUP);
pinMode(encoderButtonPin, INPUT_PULLUP);
// Initialize encoder state
lastEncoderCLKState = digitalRead(encoderPinCLK);
lastEncoderButtonState = digitalRead(encoderButtonPin);
}
void loop() {
// Read the state of each button and detect changes
for (int i = 0; i < 9; i++) {
buttonStates[i] = digitalRead(buttonPins[i]);
// Check if the button state has changed
if (buttonStates[i] != lastButtonStates[i]) {
if (buttonStates[i] == LOW) {
Serial.print("Button ");
Serial.print(i + 1);
Serial.println(" Pressed");
}
lastButtonStates[i] = buttonStates[i];
}
}
// Read the rotary encoder
int currentEncoderCLKState = digitalRead(encoderPinCLK);
unsigned long currentTime = millis();
// Check if the encoder CLK pin has changed
if (currentEncoderCLKState != lastEncoderCLKState) {
// Debounce the signal
if ((currentTime - lastDebounceTime) > debounceDelay) {
if (digitalRead(encoderPinDT) != currentEncoderCLKState) {
encoderPosition++;
Serial.println("Rotary Encoder Turned Clockwise");
} else {
encoderPosition--;
Serial.println("Rotary Encoder Turned Counterclockwise");
}
lastDebounceTime = currentTime;
}
lastEncoderCLKState = currentEncoderCLKState;
}
// Read the rotary encoder push button
bool currentEncoderButtonState = digitalRead(encoderButtonPin);
if (currentEncoderButtonState != lastEncoderButtonState) {
if (currentEncoderButtonState == LOW) {
Serial.println("Rotary Encoder Button Pressed");
}
lastEncoderButtonState = currentEncoderButtonState;
}
// Add a small delay to reduce serial output rate
delay(50);
}