STM32 ESP32 WiFi

From Stm32World Wiki
Jump to navigation Jump to search
ESP32 Hooked up to Streamline using Dupond Wires

An STM32 has no radio, but an ESP32 makes a cheap Wi-Fi co-processor. This page describes two ways of connecting an ESP32-C3 to a Streamline MCU STM32F407 over SPI. Both examples do the same job: join a Wi-Fi network, serve a status page on port 80 and keep UTC time from NIST's daytime service. The difference is where the TCP/IP stack runs:

  • ESP-Hosted: the ESP32 is a Wi-Fi network interface. Ethernet frames go over SPI and lwIP runs on the STM32.
  • ESP-AT: the ESP32 keeps the TCP/IP stack. The STM32 sends AT commands and only sees socket data.

Neither STM32 example uses an RTOS. Both are a HAL superloop with small, interrupt-driven drivers.

The source code is on GitHub: lbthomsen/stm32-esp32-wifi.

Comparison

ESP-Hosted ESP-AT
STM32 example sl_mcu_stm32f407_hosted sl_mcu_stm32f407_at
ESP firmware ESP-Hosted v3.1.0, ESP-IDF v6.2 ESP-AT v5.0.1.0, ESP-IDF v5.4
TCP/IP runs on STM32 (lwIP 2.2.1) ESP32
SPI protocol Full duplex, mode 3, fixed 1600 byte frames Half duplex, mode 0, command/address/data transactions
SPI clock 10.5 MHz 10.5 MHz
Extra lines Handshake, data ready, EN Handshake, EN
STM32 flash 82.7 KB 27.7 KB
STM32 RAM (static) 74 KB 26 KB
ESP32 firmware image 1.1 MB 1.8 MB
Ping round trip about 7 ms (5 to 30 ms) about 4 ms (3 to 9 ms)
Parallel HTTP clients 8, all answered at once 1 to 2 of a burst accepted at a time
Full control of the network stack Yes (raw lwIP, any protocol) Only what the AT command set offers

Sizes are the Debug builds (-Og). The STM32 HAL accounts for about 27 KB in both. Our own code is about 13 KB in the ESP-Hosted example and 11 KB in the ESP-AT example; the rest of the difference is lwIP (about 55 KB).

Which one to use

ESP-Hosted makes the STM32 a real network node: lwIP gives full control (raw TCP and UDP, any protocol, any number of connections the RAM allows), and the ESP is just a network card. The price is about 55 KB of flash and 50 KB of RAM on the STM32.

ESP-AT is the small option: the STM32 code is a third of the size and the ESP does all the networking. It is limited to what the AT command set offers (for example one TCP server and a handful of links), and every operation is a round trip of text commands.

Hardware

  • Streamline MCU STM32F407 and Streamline Connect in a Streamline Backplane 5. The STM32 signals are taken from the Streamline Connect header.
  • An ESP32-C3 board, wired to the header with short Dupont wires. The ESP32-C3 has its own USB power.
  • Both examples use the same wiring (see the connection tables below), so nothing moves when switching between them.
  • SPI1 on the STM32, with SCK, MISO and MOSI at GPIO_SPEED_FREQ_LOW. With the CubeMX default (very high) the edges ring on jumper wires and the ESP sees extra clock edges.
  • Handshake and data ready have pull-downs on the STM32 side.
  • The STM32 resets the ESP through EN at start-up and whenever the link stops responding.
  • The console of both examples is USART1 (PA9/PA10) at 921600 baud.

ESP-Hosted

ESP-Hosted turns the ESP32 into a Wi-Fi network interface. Espressif's own host stack needs an RTOS and ESP-IDF APIs, so the STM32 side is a small implementation of the wire protocol of its own:

  • esp_spi.c: the SPI transport. Every transaction is a full duplex 1600 byte frame. The handshake and data ready interrupts, a one-shot timer (TIM7) and the SPI DMA completions start every transfer; received frames are queued and handed on in the main loop.
  • esp_host.c: the frame layer and the init handshake with the co-processor.
  • esp_rpc.c, pb.c: RPC to the co-processor (protobuf, encoded by hand).
  • wifi_sta.c: Wi-Fi bring-up over RPC: mode, start, scan, connect, events, RSSI.
  • wifi_netif.c: the lwIP network interface: Ethernet frames to and from the ESP.
  • http_server.c, daytime.c: the two services, using lwIP's raw API.

Connections

Signal STM32F407 STM32 function ESP32-C3 ESP-Hosted function
SCK PA5 SPI1_SCK GPIO6 SPI clock (mode 3)
MOSI PA7 SPI1_MOSI GPIO7 SPI data in
MISO PA6 SPI1_MISO GPIO2 SPI data out
CS PA4 GPIO output GPIO10 SPI chip select
Handshake PC4 EXTI, pull-down GPIO3 Slave ready for a transaction
Data ready PC5 EXTI, pull-down GPIO4 Slave has data to send
Reset PA3 GPIO output, open drain EN Reset
GND GND GND

Frames

Every SPI transaction carries one frame with a 12 byte header. The interface type says what the payload is: Ethernet frames for the station interface, RPC on the serial interface, or the init event.

typedef struct __attribute__((packed)) {
    uint8_t if_type :4;     // ESP_IF_* (STA, SERIAL for RPC, PRIV for init, ...)
    uint8_t if_num :4;
    uint8_t flags;
    uint16_t len;           // payload length
    uint16_t offset;        // payload offset from the start of the frame (12)
    uint16_t checksum;      // byte sum of header + payload, this field zeroed
    uint16_t seq_num;
    uint8_t throttle_cmd :2;
    uint8_t rx_credit :6;
    uint8_t pkt_type;
} esp_hdr_v1_t;

Start-up and main loop

    esp_rpc_init(wifi_sta_rpc_event);
    wifi_sta_init(WIFI_SSID, WIFI_PASSWORD);
    wifi_netif_init();
    http_server_init();
    esp_host_init(&hspi1);      // resets the co-processor through EN

    while (1) {
        esp_host_poll();        // received frames to RPC/lwIP; the SPI transfers run from interrupts
        wifi_sta_poll();        // Wi-Fi bring-up over RPC, liveness, RSSI
        wifi_netif_poll();      // lwIP input and timers; the HTTP server runs in its callbacks
        daytime_poll();         // NIST time every 10 minutes
    }

Connecting to a network

Wi-Fi is configured with RPC calls. This is the set-config request, encoded with a minimal protobuf writer:

    // Rpc_Req_WifiSetConfig { iface = 1; wifi_config cfg = 2 { wifi_sta_config sta = 2 { ssid = 1; password = 2; } } }
    pb_writer_init(&w, buf, sizeof(buf));
    pb_write_int32_field(&w, 1, WIFI_IF_STA);
    size_t cfg = pb_write_nested_start(&w, 2);
    size_t sta = pb_write_nested_start(&w, 2);
    pb_write_bytes_field(&w, 1, sta_ssid, strlen(sta_ssid));
    pb_write_bytes_field(&w, 2, sta_password, strlen(sta_password));
    pb_write_nested_end(&w, sta);
    pb_write_nested_end(&w, cfg);
    send(RPC_ID_WIFI_SET_CONFIG, buf, w.pos, on_simple_resp);

Sending a packet

lwIP hands the network interface an Ethernet frame, which goes into the transport's TX queue:

static err_t linkoutput(struct netif *n, struct pbuf *p) {
    uint16_t len = pbuf_copy_partial(p, tx_frame, p->tot_len, 0);
    // (waits briefly if the TX queue is full)
    return esp_spi_send(ESP_IF_STA, 0, 0, 0, tx_frame, len) == 0 ? ERR_OK : ERR_IF;
}

Web server

The web server is plain lwIP raw API: lwIP calls back on a new connection, on data and when sent data is acknowledged.

void http_server_init(void) {
    struct tcp_pcb *pcb = tcp_new();
    tcp_bind(pcb, IP_ANY_TYPE, HTTP_SERVER_PORT);
    pcb = tcp_listen(pcb);
    tcp_accept(pcb, on_accept);
}

// (shortened: error handling and the slot search left out)
static err_t on_accept(void *arg, struct tcp_pcb *pcb, err_t err) {
    conn_t *c = find_free_slot();       // up to 8 connections
    c->pcb = pcb;
    tcp_arg(pcb, c);
    tcp_recv(pcb, on_recv);             // collects the request, then tcp_write() the reply
    tcp_sent(pcb, on_sent);             // closes once the reply is acknowledged
    tcp_err(pcb, on_err);
    return ERR_OK;
}

Performance

Measured over an 11 minute run:

  • 11,772 SPI transactions, 0 checksum, header or SPI errors
  • Ping: about 7 ms average (5 to 30 ms). The host turns the ESP's Wi-Fi power save off; with the default modem sleep the round trip is 30 to 230 ms.
  • HTTP: 40 of 40 requests answered; 8 simultaneous requests are all served at once
  • NIST time synced every 10 minutes, 1 s off at the resync

ESP-AT

ESP-AT runs the whole network stack on the ESP32. The STM32 talks to it with text commands (AT+CWJAP, AT+CIPSTART, ...) over SPI, and gets socket data back.

  • at_spi.c: the SPI transport (ESP-AT's half duplex SPI protocol), interrupt and DMA driven.
  • at_client.c: sends commands, matches replies (OK, ERROR), handles unsolicited lines and +IPD socket data.
  • wifi_at.c: Wi-Fi join, the TCP server and outgoing links.
  • http_server.c, daytime.c: the two services, on top of wifi_at's links.

Connections

Signal STM32F407 STM32 function ESP32-C3 ESP-AT function
SCK PA5 SPI1_SCK GPIO6 SPI clock (mode 0)
MOSI PA7 SPI1_MOSI GPIO7 SPI data in
MISO PA6 SPI1_MISO GPIO2 SPI data out
CS PA4 GPIO output GPIO10 SPI chip select
Handshake PC4 EXTI, pull-down GPIO3 Handshake (the ESP wants the host to read its status)
(Data ready) PC5 not used GPIO4 not used by ESP-AT
Reset PA3 GPIO output, open drain EN Reset
GND GND GND

SPI protocol

Every transaction is [command][address][dummy][data...]. The handshake line tells the host to look:

  • The ESP raises handshake. The host reads the slave status (command 0x02, 4 bytes).
    • Direction 1: the ESP has len bytes. The host reads them (command 0x04) and says so (command 0x08).
    • Direction 2: the ESP is ready for data the host asked to send. The host writes them (command 0x03) and says so (command 0x07).
  • To send, the host first requests a write (command 0x01) and waits for direction 2.
#define CMD_WRBUF       0x01    // write the slave's shared buffer (write request)
#define CMD_RDBUF       0x02    // read the slave's shared buffer (status)
#define CMD_WRDMA       0x03    // write data
#define CMD_RDDMA       0x04    // read data
#define CMD_WR_DONE     0x07
#define CMD_RD_DONE     0x08

Start-up and main loop

    wifi_at_init(WIFI_SSID, WIFI_PASSWORD, HTTP_SERVER_PORT, &http_server_handler);
    at_spi_init(&hspi1);        // resets the ESP through EN

    while (1) {
        at_spi_poll();          // safety net; the SPI transfers run from interrupts
        at_client_poll();       // AT lines and socket data from the ESP
        wifi_at_poll();         // Wi-Fi join, server, liveness
        http_server_poll();     // replies to requests that have come in
        daytime_poll();         // NIST time every 10 minutes
    }

Connecting to a network

The bring-up is a sequence of AT commands, one step per reply:

    at_client_command("AT+CWMODE=1", CMD_TIMEOUT_MS, NULL, on_step_done);
    at_client_command("AT+SLEEP=0", CMD_TIMEOUT_MS, NULL, on_step_done);
    snprintf(cmd, sizeof(cmd), "AT+CWHOSTNAME=\"%s\"", hostname);
    snprintf(cmd, sizeof(cmd), "AT+CWJAP=\"%s\",\"%s\"", sta_ssid, sta_password);
    at_client_command("AT+CIPSTA?", CMD_TIMEOUT_MS, on_ip_line, on_step_done);
    at_client_command("AT+CIPMUX=1", CMD_TIMEOUT_MS, NULL, on_step_done);
    snprintf(cmd, sizeof(cmd), "AT+CIPSERVER=1,%u", server_port);

Web server

The TCP server runs on the ESP. The STM32 registers a handler for its links and gets called when a client connects, sends data or goes away:

typedef struct {
    void (*on_connect)(int link);
    void (*on_data)(int link, const uint8_t *data, size_t len);
    void (*on_closed)(int link);
} wifi_at_link_handler_t;

const wifi_at_link_handler_t http_server_handler = {
    .on_connect = on_connect,
    .on_data = on_data,         // collects the request line and the end of the headers
    .on_closed = on_closed,
};

The reply is sent from the main loop with AT+CIPSEND, then the link is closed with AT+CIPCLOSE.

Performance

  • Ping: about 4 ms average (3 to 9 ms), answered by the ESP
  • TCP echo of up to 8000 bytes intact, about 1.2 Mbit/s
  • ESP-AT supports one TCP server. With AT+CIPSERVERMAXCONN=4 one link stays free for outgoing connections (the NIST client). Of a burst of simultaneous connections only 1 to 2 are accepted at a time.
  • Recovers from an ESP reset and from a halted ESP

Switching between ESP-Hosted and ESP-AT

The wiring is the same for both, so switching is just flashing both chips. The ESP and STM32 firmware have to match.

  1. Halt the STM32 first. A running host resets the ESP through EN when the link goes quiet, and that reset can land in the middle of the ESP flash.
  2. Flash the ESP (ESP-AT or ESP-Hosted). Erasing the flash first is optional; it only clears the settings the other firmware stored.
  3. Flash and start the matching STM32 example. It resets the ESP through EN and brings the link up.
# 1. Halt the STM32
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "init; halt; exit"

# 2. Flash the ESP: ESP-AT ...
at_firmware/build.sh flash /dev/ttyACM1
# ... or ESP-Hosted
cd coprocessor && idf.py -B build_esp32c3 -D SDKCONFIG=sdkconfig.esp32c3 -p /dev/ttyACM1 flash

# 3. Flash and start the matching STM32 example
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program examples/sl_mcu_stm32f407_at/Debug/sl_mcu_stm32f407_at.elf verify reset exit"
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program examples/sl_mcu_stm32f407_hosted/Debug/sl_mcu_stm32f407_hosted.elf verify reset exit"

Tested from ESP-Hosted to ESP-AT and back, with and without an erase: each time the link came up on the first try, with 0 SPI errors, ping and the status page answering and NIST time synced.

Miscellaneous links