Skip to content

Commit 56095b4

Browse files
Merge pull request #1401 from arduino/Hannes7eicher/ESP-NOW-Tutorial
[MNE-27, MKC-1233] ESP-NOW Tutorial
2 parents ea81efd + 952891b commit 56095b4

File tree

6 files changed

+288
-0
lines changed

6 files changed

+288
-0
lines changed

content/hardware/03.nano/boards/nano-esp32/features.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,8 @@ The first Nano board to feature a USB-C® connector!
3131
The Nano ESP32 supports out-of-the-box debugging with no additional hardware required!<FeatureLink variant="secondary" title="Documentation" url="/tutorials/nano-esp32/debugging"/>
3232
</Feature>
3333

34+
<Feature title="ESP-NOW" image="communication">
35+
The Nano ESP32 supports the ESP-NOW protocol develop by Espressif!<FeatureLink variant="secondary" title="Documentation" url="/tutorials/nano-esp32/esp-now"/>
36+
</Feature>
37+
3438
</FeatureList>
Loading
Loading
Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
---
2+
title: Device to Device Communication with ESP-NOW
3+
description: Learn how to use the ESP-NOW protocol to send data between ESP based boards.
4+
author: Hannes Siebeneicher
5+
hardware:
6+
- hardware/03.nano/boards/nano-esp32
7+
tags: [ESP32, Debugging, IDE]
8+
---
9+
10+
## Introduction
11+
12+
ESP-NOW is a wireless communication protocol developed by Espressif, the company behind the ESP32 microcontroller (MCU). Since the Arduino Nano ESP32 is equipped with that MCU it also supports the ESP-NOW protocol out of the box. It's designed for efficient and low-latency communication between devices, capable of sending up to 250 bytes.
13+
14+
## Hardware Requirements
15+
16+
ESP-NOW is supported on the following microcontrollers:
17+
18+
- [Arduino Nano ESP32](https://store.arduino.cc/products/nano-esp32)
19+
- generic ESP8266
20+
- generic ESP32
21+
- generic ESP32-S
22+
- ESP32-C series of SoCs
23+
24+
You need two boards or more to communicate via ESP-NOW. Minimum one sender and one receiver.
25+
26+
## How It Works
27+
28+
### Communication Protocol
29+
ESP-NOW operates as a peer-to-peer (P2P) protocol, meaning it allows direct communication between two ESP8266 or ESP32 devices without the need for a central server or access point, e.g. a Wi-Fi® router. Each ESP device has a unique [MAC address](https://en.wikipedia.org/wiki/MAC_address) which is used to identify the receiving board.
30+
31+
ESP-NOW can be set up in different ways:
32+
33+
**One-way communication**: In one-way communication mode, one device (the sender) can send data to another device (the receiver) without expecting a response. This mode is often used for scenarios where one device provides data or commands to another device, such as remote sensor readings or control commands.
34+
35+
**Two-way communication**: In two-way communication mode, both devices can exchange data bidirectionally. This mode enables a back-and-forth exchange of information between the devices, allowing for more interactive and responsive communication. It's suitable for applications where devices need to send and receive data from each other, such as remote control systems or interactive IoT devices.
36+
37+
![ESP-NOW Communication](./assets/esp-now-communication.png)
38+
39+
### Protocol Stack
40+
41+
ESP-NOW operates primarily at the data-link layer of the [OSI model](https://en.wikipedia.org/wiki/OSI_model). In contrast to traditional networking protocols that involve multiple layers, ESP-NOW condenses the communication stack, streamlining the process. By reducing the protocol stack to a single layer, ESP-NOW eliminates the need for complex [packet headers](https://www.cloudflare.com/en-gb/learning/network-layer/what-is-a-packet/) and unpackers on each layer. This simplicity results in quicker response times, reducing delays caused by packet loss in congested networks.
42+
43+
![TCP/IP and ESP-NOW Protocol Stack](./assets/protocol-stack.png)
44+
45+
### Lightweight Design
46+
The protocol minimizes communication overhead, making it more efficient for resource-constrained devices. It also doesn’t perform [handshakes](https://en.wikipedia.org/wiki/Handshake_(computing)) as devices are preconfigured to allow for faster data transmission and reduced power consumption.
47+
48+
### Limited Data Quantities
49+
ESP-NOW is useful when transmitting smaller amounts of data (max 250 bytes). It utilizes action frames for communication. Action frames are specialized data frames that contain information about the action being performed. These frames allow ESP-NOW devices to efficiently exchange data without the overhead associated with more generic data frames.
50+
51+
![Action Frames](./assets/action-frame.png)
52+
53+
### Low Latency
54+
As a result of the limited data quantities and its lightweight design ESP-NOW introduces a low latency, which means that devices can quickly exchange data making it suitable for remote controlling other devices, e.g. a radio car.
55+
56+
## Limitations
57+
58+
### Limited Range
59+
ESP-NOW has a limited signal range, typically around 220 meters under ideal conditions. The actual range can vary depending on factors like environmental interference, antenna design, and obstacles in the communication path.
60+
61+
### Interference
62+
Like other wireless communication technologies operating in the 2.4 GHz band, ESP-NOW can be susceptible to interference from other devices and Wi-Fi networks. It's essential to choose communication channels carefully to minimize interference and ensure reliable communication.
63+
64+
### No Network Infrastructure
65+
ESP-NOW is designed for point-to-point and point-to-multipoint communication but doesn't provide the infrastructure for building complex network topologies. If your application requires a network with multiple interconnected devices or Internet connectivity, you may need to complement ESP-NOW with additional networking solutions.
66+
67+
### Limited Data Payload
68+
ESP-NOW is optimized for transmitting smaller amounts of data, with a maximum payload of around 250 bytes. If your application requires high-bandwidth data transfer or large file exchanges, other services such as the [Arduino IoT Cloud](https://cloud.arduino.cc/) might be more suitable.
69+
70+
### Security Considerations
71+
While ESP-NOW offers some level of data privacy, it may not be as secure as other communication protocols like HTTPS or MQTT with robust encryption. If your project involves sensitive data, consider implementing additional security measures to protect against eavesdropping and unauthorized access.
72+
73+
### No Message Acknowledgment
74+
ESP-NOW does not provide built-in acknowledgment mechanisms for confirming successful message delivery. If message reliability is crucial for your application, you'll need to implement your own acknowledgment and error-handling mechanisms.
75+
76+
### Compatibility
77+
ESP-NOW is primarily designed for use with ESP8266 and ESP32 microcontrollers. While it can be compatible with other ESP32-based devices, it may not work seamlessly with other non-ESP platforms. Compatibility should be considered when designing a system with multiple types of devices.
78+
79+
## Arduino IoT Cloud
80+
81+
Arduino provides their own service for handling wireless communication called Arduino IoT Cloud. You can read more about it [here](https://docs.arduino.cc/arduino-cloud/).
82+
83+
While the Arduino IoT Cloud offers similar features to the ESP-NOW protocols they are vastly different and should be used for specific use cases. Check the comparison table below for more information.
84+
85+
| | Arduino IoT Cloud | ESP-NOW |
86+
|---------------------|-----------------------------------------------------------------------------|--------------------------------------------------------------------------------|
87+
| Range | Depends on Internet connectivity, suitable for global reach. | Approx. 220 m. |
88+
| Security | Secure communication with encryption and authentication. | Basic security, may need additional measures. |
89+
| Delay | Network-related delays due to Internet communication. | Low latency for local communication. |
90+
| Data Size | Unlimited data (min. Entry plan) | max 250 bytes. |
91+
| Device Compatibility| Compatible with various Arduino boards and IoT devices. | Primarily used with ESP8266 and ESP32 microcontrollers. |
92+
| Protocol | Uses MQTT for communication. | Uses a custom ESP-NOW protocol. |
93+
| Power Consumption | May consume more power, especially when connected to the internet. | Known for low power consumption. |
94+
| Data Processing | Allows for cloud-based data processing and analytics. | Primarily for direct device-to-device communication. |
95+
| Use Cases | IoT projects requiring global connectivity and cloud-based data management. | Applications needing low-latency, local communication. |
96+
97+
***Check out the different Arduino IoT Cloud plans [here](https://cloud.arduino.cc/plans).***
98+
99+
## Code
100+
101+
Below you can find examples for sending and receiving data via the ESP-NOW protocol. You first need to identify the MAC address of your receiving board to let the sender know where to send the data. To identify the MAC address of your board upload the following code:
102+
103+
```arduino
104+
// Complete Instructions to Get and Change ESP MAC Address: https://RandomNerdTutorials.com/get-change-esp32-esp8266-mac-address-arduino/
105+
106+
#include "WiFi.h"
107+
108+
void setup(){
109+
Serial.begin(115200);
110+
WiFi.mode(WIFI_MODE_STA);
111+
Serial.println(WiFi.macAddress());
112+
}
113+
114+
void loop(){
115+
116+
}
117+
```
118+
119+
### Sender Sketch
120+
121+
```arduino
122+
/*
123+
Rui Santos
124+
Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
125+
126+
Permission is hereby granted, free of charge, to any person obtaining a copy
127+
of this software and associated documentation files.
128+
129+
The above copyright notice and this permission notice shall be included in all
130+
copies or substantial portions of the Software.
131+
*/
132+
133+
#include <esp_now.h>
134+
#include <WiFi.h>
135+
136+
// REPLACE WITH YOUR RECEIVER MAC Address
137+
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
138+
139+
// Structure example to send data
140+
// Must match the receiver structure
141+
typedef struct struct_message {
142+
char a[32];
143+
int b;
144+
float c;
145+
bool d;
146+
} struct_message;
147+
148+
// Create a struct_message called myData
149+
struct_message myData;
150+
151+
esp_now_peer_info_t peerInfo;
152+
153+
// callback when data is sent
154+
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
155+
Serial.print("\r\nLast Packet Send Status:\t");
156+
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
157+
}
158+
159+
void setup() {
160+
// Init Serial Monitor
161+
Serial.begin(115200);
162+
163+
// Set device as a Wi-Fi Station
164+
WiFi.mode(WIFI_STA);
165+
166+
// Init ESP-NOW
167+
if (esp_now_init() != ESP_OK) {
168+
Serial.println("Error initializing ESP-NOW");
169+
return;
170+
}
171+
172+
// Once ESPNow is successfully Init, we will register for Send CB to
173+
// get the status of Transmitted packet
174+
esp_now_register_send_cb(OnDataSent);
175+
176+
// Register peer
177+
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
178+
peerInfo.channel = 0;
179+
peerInfo.encrypt = false;
180+
181+
// Add peer
182+
if (esp_now_add_peer(&peerInfo) != ESP_OK){
183+
Serial.println("Failed to add peer");
184+
return;
185+
}
186+
}
187+
188+
void loop() {
189+
// Set values to send
190+
strcpy(myData.a, "THIS IS A CHAR");
191+
myData.b = random(1,20);
192+
myData.c = 1.2;
193+
myData.d = false;
194+
195+
// Send message via ESP-NOW
196+
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
197+
198+
if (result == ESP_OK) {
199+
Serial.println("Sent with success");
200+
}
201+
else {
202+
Serial.println("Error sending the data");
203+
}
204+
delay(2000);
205+
}
206+
```
207+
208+
### Receiver Sketch
209+
210+
```arduino
211+
/*
212+
Rui Santos
213+
Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
214+
215+
Permission is hereby granted, free of charge, to any person obtaining a copy
216+
of this software and associated documentation files.
217+
218+
The above copyright notice and this permission notice shall be included in all
219+
copies or substantial portions of the Software.
220+
*/
221+
222+
#include <esp_now.h>
223+
#include <WiFi.h>
224+
225+
// Structure example to receive data
226+
// Must match the sender structure
227+
typedef struct struct_message {
228+
char a[32];
229+
int b;
230+
float c;
231+
bool d;
232+
} struct_message;
233+
234+
// Create a struct_message called myData
235+
struct_message myData;
236+
237+
// callback function that will be executed when data is received
238+
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
239+
memcpy(&myData, incomingData, sizeof(myData));
240+
Serial.print("Bytes received: ");
241+
Serial.println(len);
242+
Serial.print("Char: ");
243+
Serial.println(myData.a);
244+
Serial.print("Int: ");
245+
Serial.println(myData.b);
246+
Serial.print("Float: ");
247+
Serial.println(myData.c);
248+
Serial.print("Bool: ");
249+
Serial.println(myData.d);
250+
Serial.println();
251+
}
252+
253+
void setup() {
254+
// Initialize Serial Monitor
255+
Serial.begin(115200);
256+
257+
// Set device as a Wi-Fi Station
258+
WiFi.mode(WIFI_STA);
259+
260+
// Init ESP-NOW
261+
if (esp_now_init() != ESP_OK) {
262+
Serial.println("Error initializing ESP-NOW");
263+
return;
264+
}
265+
266+
// Once ESPNow is successfully Init, we will register for recv CB to
267+
// get recv packer info
268+
esp_now_register_recv_cb(OnDataRecv);
269+
}
270+
271+
void loop() {
272+
273+
}
274+
```
275+
276+
## Read More
277+
For a more detailed explanation on how the code works check out the article at [randomnerdtutorials.com](https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/).
278+
279+
You can also read more about the `esp_now` library over at [https://docs.espressif.com/](https://docs.espressif.com/).
280+
281+
## Summary
282+
In this article we covered the basics of the ESP-NOW protocol and how it works. We also provided example code serving as a starting point for your project. Overall, ESP-NOW is a powerful communication protocol for local and low-latency applications, particularly when using ESP8266 and ESP32 microcontrollers.
283+
284+
However, it comes with certain limitations that you should be aware of when designing projects.
Loading

0 commit comments

Comments
 (0)