🛠 Communication inter-cartes avec ESP-NOW
Objectives
Make two Nano ESP32 boards communicate via ESP-NOW: peer-to-peer radio without a router or pairing, with frames up to 250 bytes. One transmitter broadcasts a counter, and a receiver displays it — the foundation of an autonomous sensor network.
Hardware
- 2 × Arduino Nano ESP32 + 2 USB-C cables
- Both boards on the same Wi-Fi channel (channel 0 = current channel)
Complete Code
// Émetteur (diffusion). Côté récepteur, décommenter la callback et son
// enregistrement dans setup.
#include <WiFi.h>
#include <esp_now.h>
uint8_t broadcast[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint32_t n = 0;
// void onRecu(const uint8_t* src, esp_now_recv_info_t* info,
// const uint8_t* data, int8_t len) {
// Serial.printf("reçu %.*s\n", len, data);
// }
void setup {
Serial.begin(115200);
WiFi.mode(WIFI_STA); // ESP-NOW exige STA, sans connexion AP
if (esp_now_init != ESP_OK) { Serial.println("ESP-NOW KO"); while (1); }
// Récepteur : esp_now_register_recv_cb(onRecu);
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, broadcast, 6);
peer.channel = 0; // 0 = canal courant
peer.encrypt = false;
esp_now_add_peer(&peer);
}
void loop {
char msg[32];
int len = snprintf(msg, sizeof msg, "hello #%lu", (unsigned long)n++);
esp_now_send(broadcast, (uint8_t*)msg, len);
Serial.println(msg);
delay(1000);
}
Expected Verification
The receiver's serial monitor displays "hello #0", "hello #1"… every second, without any router. The exchange is direct between the two boards, with a range significantly greater than that of a distant access point.
Common Errors
- Missing
WiFi.mode(WIFI_STA), or connecting to an AP on a different channel: frames are not sent. - Payload larger than 250 bytes:
esp_now_sendfails silently. - Receive callback not registered: the transmitter sends, but the receiver displays nothing.
- Mixing cores: the "Arduino ESP32 Boards" package documents ESP-NOW; with the Espressif core, callback signatures differ.
Other tutorials for this board
Code examples for this board
connexion-wifi.inoArduinopoint-acces.inoArduinoble-capteur.inoArduinoneoled-rgb.inoArduinoadc-12bits.inoArduinopreferences.inoArduino