#include <WiFi.h>
#include <esp_now.h>
// Callback function that will be executed when data is received
void onDataRecv(const esp_now_recv_info_t *recvInfo, const uint8_t *incomingData, int len) {
char message[len + 1];
memcpy(message, incomingData, len);
message[len] = '\0'; // Null-terminate the string
Serial.print("Received message: ");
Serial.println(message);
// Print the sender's MAC address
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X",
recvInfo->src_addr[0], recvInfo->src_addr[1], recvInfo->src_addr[2],
recvInfo->src_addr[3], recvInfo->src_addr[4], recvInfo->src_addr[5]);
Serial.print("From MAC: ");
Serial.println(macStr);
}
void setup() {
Serial.begin(115200);
// Set ESP32 to station mode
WiFi.mode(WIFI_STA);
Serial.println("ESP-NOW Receiver Initialized");
// Initialize ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
while (true) {
delay(1000); // Halt program if ESP-NOW fails
}
}
// Register the receive callback
esp_now_register_recv_cb(onDataRecv);
Serial.println("Ready to receive messages");
}
void loop() {
// Continuously check for connection status
static unsigned long lastCheck = 0;
unsigned long now = millis();
// Check every 5 seconds if ESP-NOW is active
if (now - lastCheck >= 5000) {
lastCheck = now;
if (esp_now_init() != ESP_OK) {
Serial.println("ESP-NOW not active. Reinitializing...");
esp_now_deinit(); // Deinitialize and reinitialize ESP-NOW
if (esp_now_init() == ESP_OK) {
esp_now_register_recv_cb(onDataRecv);
Serial.println("ESP-NOW Reinitialized.");
} else {
Serial.println("Failed to reinitialize ESP-NOW.");
}
}
}
}
/*
#include <WiFi.h>
#include <esp_wifi.h> // Include ESP-IDF WiFi header for low-level WiFi functions
// Custom MAC address (must follow the MAC address format)
uint8_t customMAC[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
void setup() {
Serial.begin(115200);
// Set WiFi to station mode
WiFi.mode(WIFI_STA);
Serial.println("ESP32 MAC Address Assignment");
// Assign the custom MAC address
if (esp_wifi_set_mac(WIFI_IF_STA, customMAC) == ESP_OK) {
Serial.println("Custom MAC Address assigned successfully!");
} else {
Serial.println("Failed to assign Custom MAC Address.");
}
// Print the currently assigned MAC address
uint8_t currentMAC[6];
esp_wifi_get_mac(WIFI_IF_STA, currentMAC);
Serial.print("Current MAC Address: ");
for (int i = 0; i < 6; i++) {
Serial.printf("%02X", currentMAC[i]);
if (i < 5) Serial.print(":");
}
Serial.println();
}
void loop() {
// Nothing to do here
}
*/