Jan Beran

View on GitHub

Assignment 5: ESP-NOW Chat Room


While Wi-Fi is great for connecting to the Internet, it requires an Access Point (router) and has overhead due to the connection process. What if you just want multiple ESP32 boards to talk directly to each other?

What is ESP-NOW, actually?

ESP-NOW is a connectionless, low-overhead wireless protocol that Espressif built on top of the Wi-Fi radio. A few things worth knowing as a tinkerer, before we touch any code:

In this assignment we’ll create a chatroom. You will send messages to other devices via the serial monitor - or control other people’s LED!

Start a fresh project this time. ESP-NOW doesn’t need the Wi-Fi provisioning or OTA code from Assignments 3–4:

idf.py create-project esp_now_chat
cd esp_now_chat
idf.py set-target esp32c5
idf.py add-dependency "espressif/led_strip^3.0.3"
idf.py reconfigure

Copy chatroom.c and chatroom.h into your main/ folder.

Add chatroom.c and the components the chat uses:

idf_component_register(SRCS "esp_now_chat.c" "chatroom.c"
                       INCLUDE_DIRS "."
                       REQUIRES led_strip esp_wifi esp_event esp_netif nvs_flash)

The new main file (esp_now_chat.c) starts as:

#include <stdio.h>

void app_main(void)
{

}

1. Writing the Code

As before, let’s build main/esp_now_chat.c up instead of pasting it all at once. The chat room calls three functions that you provide here: broadcast, send to one MAC, and remember a MAC as a peer. It never calls esp_now_* itself.

1.1 Skeleton

#include <stdio.h>

// (A) Headers and the broadcast address
// (B) Receive callback: hand the packet to the chat room
// (C) espnow_broadcast, espnow_send, espnow_add_peer

void app_main(void)
{
    // (D) Initialize NVS
    // (E) Turn the Wi-Fi radio on (station mode, no router)
    // (F) Initialize ESP-NOW, register the receive callback, add the broadcast peer
    // (G) Start the chat room
}

1.2 Part (A): headers and the broadcast address

#include <stdio.h>
#include <string.h>
#include "esp_event.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "esp_now.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "chatroom.h"

/* Every board names itself: a 4-letter animal picked from its MAC address, then the last two MAC
 * bytes in hex, for example "bear83e8". That is exactly 8 lowercase ASCII characters, and the
 * hex part makes it unique in the room in practice. */
static const char *const s_animals[] = {
    "bear", "wolf", "lynx", "seal", "crab", "frog", "duck", "goat",
    "hawk", "mole", "newt", "swan", "toad", "moth", "deer", "orca",
};

static void make_node_name(char name[CHATROOM_NAME_LEN + 1])
{
    uint8_t mac[6];
    ESP_ERROR_CHECK(esp_read_mac(mac, ESP_MAC_WIFI_STA));
    const char *animal = s_animals[(mac[3] ^ mac[4] ^ mac[5]) % (sizeof(s_animals) / sizeof(s_animals[0]))];
    snprintf(name, CHATROOM_NAME_LEN + 1, "%s%02x%02x", animal, mac[4], mac[5]);
}

static const char *TAG = "espnow";

static const uint8_t s_broadcast_mac[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

Broadcast MAC address is FF:FF:FF:FF:FF:FF in ESP-NOW protocol. Every other ESP-NOW device listens to messages sent for this address.

The chat room needs a name for every board: exactly 8 ASCII characters, unique in the room. Nobody has to pick one, because make_node_name() builds it from the board’s own MAC address: a 4-letter animal plus the last two MAC bytes in hex, like bear83e8 or wolf1f42. Two boards in one room can end up with the same animal, but the hex part makes a clash very unlikely. Your board prints its name when it starts, and list shows the names of the others.

1.3 Part (B): the receive callback

ESP-NOW calls this from the Wi-Fi task whenever a packet arrives. The payload is a raw buffer with a length, not a C string. We don’t interpret it here — chatroom_on_recv does that, and it also reads src_addr, the MAC of whoever sent the packet.

static void on_data_recv(const esp_now_recv_info_t *recv_info, const uint8_t *data, int data_len)
{
    if (recv_info == NULL || recv_info->src_addr == NULL) {
        return;
    }
    /* Runs in the Wi-Fi task: hand over fast and return. */
    chatroom_on_recv(recv_info->src_addr, data, data_len);
}

1.4 Part (C): send, and add a peer

esp_now_send() hands len bytes to the radio and returns. It does not wait for anyone to receive them — there is no connection to wait on. The same call is a broadcast or a direct message depending only on which MAC you pass.

A direct send works only for a MAC that was registered with esp_now_add_peer(). The chat room does that the first time it hears a new board. channel = 0 means “whatever channel the radio is already on”. Broadcast peers cannot set encrypt.

esp_err_t espnow_broadcast(const uint8_t *data, size_t len)
{
    return espnow_send(s_broadcast_mac, data, len);
}

esp_err_t espnow_send(const uint8_t mac[6], const uint8_t *data, size_t len)
{
    return esp_now_send(mac, data, len);
}

esp_err_t espnow_add_peer(const uint8_t mac[6])
{
    /* Adding twice fails; skip known boards. */
    if (esp_now_is_peer_exist(mac)) {
        return ESP_OK;
    }

    esp_now_peer_info_t peer = { 0 };
    memcpy(peer.peer_addr, mac, 6);
    peer.channel = 0;   /* current channel */
    peer.encrypt = false; /* no encryption in this workshop */
    return esp_now_add_peer(&peer);
}

1.5 Parts (D)–(G): app_main

ESP-NOW needs the Wi-Fi peripheral on, in station mode, even though we never join a router. esp_wifi_start() turns the radio on. NVS comes first, same as in the Wi-Fi assignments, because the Wi-Fi driver stores calibration data there.

The broadcast peer has to be added before the first send, or esp_now_send() to FF:FF:FF:FF:FF:FF fails with “peer not found”. chatroom_start() is the keyboard and the code that prints received lines; everything it transmits goes back through part (C).

void app_main(void)
{
    // (D) Initialize NVS
    esp_err_t ret = nvs_flash_init();
    /* Flash was erased or the layout changed; start NVS fresh. */
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // (E) Turn the Wi-Fi radio on (station mode, no router)
    ESP_ERROR_CHECK(esp_netif_init()); /* TCP/IP stack */
    ESP_ERROR_CHECK(esp_event_loop_create_default()); /* the loop Wi-Fi posts events to */
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); /* station mode, but we never join a router */
    ESP_ERROR_CHECK(esp_wifi_start()); /* radio on; no connection yet */

    // (F) Initialize ESP-NOW, register the receive callback, add the broadcast peer
    ESP_ERROR_CHECK(esp_now_init());
    /* Every packet lands in part (B). */
    ESP_ERROR_CHECK(esp_now_register_recv_cb(on_data_recv));

    esp_now_peer_info_t broadcast = { 0 };
    memcpy(broadcast.peer_addr, s_broadcast_mac, 6);
    broadcast.channel = 0;
    broadcast.encrypt = false; /* broadcast traffic cannot be encrypted */
    ESP_ERROR_CHECK(esp_now_add_peer(&broadcast));

    // (G) Start the chat room: keyboard in, chat lines out; sends go through part (C)
    char node_name[CHATROOM_NAME_LEN + 1];
    make_node_name(node_name);
    chatroom_start(node_name);
    ESP_LOGI(TAG, "ESP-NOW is up. Type in this monitor.");
}

1.6 Complete code

examples/C5/assignment-05-esp-now has this program in main/esp_now_chat.c, plus the chatroom.c / chatroom.h pair.

2. Build, Flash, and Monitor

idf.py build flash monitor

idf.py monitor is a serial terminal in both directions. Lines the board prints show up here, and keys you press are sent to the board (except Ctrl-], which quits, and Ctrl-T, which opens the monitor menu). The board echoes what you type. A message from someone else can print in the middle of that line; the board still receives only your keystrokes, and Enter sends the line you typed.

Flash a second board (or your neighbour’s). Each board names itself from its MAC address, so there is nothing to edit. In the examples below, yours is bear83e8 and theirs is wolf1f42; look at the line This board is "..." in your own monitor for the real names.

A line that is not ASCII is refused. A packet longer than 250 bytes is cut to fit before it is sent. A board does not receive its own broadcast.

Next step

Let’s look at one final feature of the ESP32-C5: The Low-Power core!

Assignment 6: LP-core