Table of Contents
Here’s a simple example to demonstrate how to use ESP-NOW for communication between two ESP32 devices.
ESP32 Sender Code (Transmitter)
This code will send data (e.g., a message) to another ESP32 device using ESP-NOW.
#include <esp_now.h>
#include <WiFi.h>
// Define the MAC address of the receiving device
uint8_t remoteMacAddr[] = {0x30, 0xAE, 0xA4, 0x1F, 0xD1, 0xB0}; // Replace with your receiver's MAC address
// uint8_t broadcastMacAddr[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // Broadcast address
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Initialize Wi-Fi in Station mode
WiFi.mode(WIFI_STA);
// Initialize ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("ESPNow initialization failed!");
return;
}
// Add the peer (receiver) MAC address
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, remoteMacAddr, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
// Send data
const char *message = "Hello Lonely Binary!";
esp_now_send(remoteMacAddr, (uint8_t *)message, strlen(message));
Serial.println("Message sent!");
}
void loop() {
// Nothing to do in loop
}
ESP32 Receiver Code (Receiver)
This code listens for incoming messages using ESP-NOW.
#include <esp_now.h>
#include <WiFi.h>
// Callback function for receiving data
void onDataReceive(const uint8_t * mac, const uint8_t *incomingData, int len) {
Serial.print("Received message: ");
Serial.println((char *)incomingData);
}
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Initialize Wi-Fi in Station mode
WiFi.mode(WIFI_STA);
// Initialize ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("ESPNow initialization failed!");
return;
}
// Register the callback function to handle incoming data
esp_now_register_recv_cb(onDataReceive);
Serial.println("Receiver is ready to receive messages.");
}
void loop() {
// Nothing to do in loop
}
Steps to test:
- Upload the Sender Code to one ESP32 device.
- Upload the Receiver Code to the other ESP32 device.
- Connect the devices to a power source.
- Check the Serial Monitor of both devices:
- The sender will print “Message sent!”.
- The receiver will print “Received message: Hello Hello Lonely Binary!”.
Key Points:
- MAC Address: In the sender code, you need to replace the remoteMacAddr with the MAC address of the receiving ESP32 device. You can find this address using Serial.println(WiFi.macAddress()); on the receiver.
or you can use the broadcast MAC address (ff:ff:ff:ff:ff:ff) to broadcase this message which will make the message sent to all ESP32 devices in the range (that are set up to listen for ESP-NOW messages).
- Data: You can modify the data being sent, which in this example is a string message.