#include <Wire.h>
const int BTN_HANDSET_PINS[] = {PA0, PA1, PA2, PA3, PA4, PA5, PA6, PA7, PA8, PA9, PA10, PA11, PA12, PB13, PB14, PA15, PB0, PB1};
const int NUM_BUTTONS = 18;
bool buttonStates[NUM_BUTTONS];
#define DEBOUNCE_DELAY 50 // Define debounce delay in milliseconds
unsigned long lastDebounceTime[NUM_BUTTONS]; // Store the last debounce time for each button
bool lastButtonState[NUM_BUTTONS]; // Store the last button state
void setup() {
Wire.begin(8); // Join I2C bus with address #8
Wire.onRequest(requestEvent); // Register the request event
for (int i = 0; i < NUM_BUTTONS; i++) {
pinMode(BTN_HANDSET_PINS[i], INPUT_PULLUP);
lastButtonState[i] = digitalRead(BTN_HANDSET_PINS[i]);
buttonStates[i] = false;
lastDebounceTime[i] = 0;
}
}
void loop() {
for (int i = 0; i < NUM_BUTTONS; i++) {
bool currentState = digitalRead(BTN_HANDSET_PINS[i]);
if (currentState != lastButtonState[i]) {
lastDebounceTime[i] = millis(); // Reset the debounce timer
}
if ((millis() - lastDebounceTime[i]) > DEBOUNCE_DELAY) {
if (currentState != buttonStates[i]) {
buttonStates[i] = currentState;
}
}
lastButtonState[i] = currentState;
}
}
void requestEvent() {
uint32_t buttonStateBits = 0;
for (int i = 0; i < NUM_BUTTONS; i++) {
if (buttonStates[i] == LOW) { // Button is pressed when state is LOW
buttonStateBits |= (1 << i);
}
}
Wire.write((uint8_t*)&buttonStateBits, sizeof(buttonStateBits)); // Send the button states over I2C
}