#include <esp_now.h>
#include <WiFi.h>
#define NUM_BUTTONS 6
#define DEBOUNCE_DELAY 50 // milliseconds
// Define button pins
const int buttonPins[NUM_BUTTONS] = {14, 27, 26, 25, 33, 32};
// Debounce and state variables
bool buttonState[NUM_BUTTONS] = {false};
bool lastButtonState[NUM_BUTTONS] = {false};
unsigned long lastDebounceTime[NUM_BUTTONS] = {0};
// Define a struct to hold the button number
typedef struct struct_message {
int buttonNumber;
} struct_message;
struct_message myData;
uint8_t receiverMacAddress[] = {0x24, 0x6F, 0x28, 0xAB, 0xCD, 0xEF}; // Replace with actual MAC
void setup() {
Serial.begin(115200);
// Initialize button pins
for (int i = 0; i < NUM_BUTTONS; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Set WiFi to station mode and initialize ESP-NOW
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register peer
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, receiverMacAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
}
void loop() {
for (int i = 0; i < NUM_BUTTONS; i++) {
int reading = digitalRead(buttonPins[i]);
// Check if button state has changed
if (reading != lastButtonState[i]) {
lastDebounceTime[i] = millis(); // Reset debounce timer
}
if ((millis() - lastDebounceTime[i]) > DEBOUNCE_DELAY) {
// If the button state has changed and stabilized
if (reading != buttonState[i]) {
buttonState[i] = reading;
// Send toggle message if button is pressed (LOW state due to INPUT_PULLUP)
if (buttonState[i] == LOW) {
myData.buttonNumber = i + 1; // Send button number (1 to 6)
// Send the data
esp_err_t result = esp_now_send(receiverMacAddress, (uint8_t *) &myData, sizeof(myData));
if (result == ESP_OK) {
Serial.println("Sent button press");
} else {
Serial.println("Error sending data");
}
}
}
}
lastButtonState[i] = reading;
}
}