In this tutorial, we’ll discuss how to use the ESP8266 AT commands with STM32 microcontrollers to connect an STM32 to a WiFi network. You’ll learn how the ESP8266 works as a WiFi co-processor, how to check which AT firmware your ESP8266 module is running and how to update it, how to wire the ESP8266 to an STM32 Blue Pill, and how to configure the STM32 UART with DMA in CubeMX to talk to it.
Then, we’ll build three STM32 ESP8266 example projects with our own non-blocking ESP-AT driver: talking to the module, joining a WiFi network with automatic reconnection, and a TCP client that sends and receives data. We’ll also measure the old and the updated ESP8266 AT firmware on the bench, and finish with a complete ESP8266 AT commands list with the real replies from our module. This is the second part of our STM32 WiFi tutorial series. Without further ado, let’s get right into it!
Note: The STM32 code examples in this tutorial are tested with: STM32 Blue Pill (STM32F103C8T6), ESP8266 (ESP-01, 1MB) with ESP8266 NonOS AT firmware.
STM32 ESP8266 WiFi: How It Works
The ESP8266 is a WiFi chip with its own processor, RAM, and TCP/IP stack. When it runs Espressif’s AT firmware, it behaves like a WiFi modem: the STM32 sends it text commands over a UART ( AT+CWJAP="MyWiFi","password" to join a network, AT+CIPSTART to open a TCP connection, AT+CIPSEND to send data), and the ESP8266 answers with text replies ( OK, ERROR, +IPD,... for received data).
This means the STM32 doesn’t need a TCP/IP stack, an RTOS, or a lot of RAM. A Blue Pill with 20KB of RAM can run a WiFi application, because all the networking happens inside the ESP8266. The price is speed and control: everything goes through one UART, and the STM32 only gets the features the AT firmware offers. We compared this approach with the other ways of adding WiFi to an STM32 in the STM32 WiFi guide, which is the first part of this series.

ESP8266 AT Firmware Versions: Which One Is on Your Module?
Before writing any STM32 code, check the AT firmware on your ESP8266 module. ESP8266 modules have been sold since 2014, and the AT firmware they ship with differs a lot: an old module may not support half of the commands in this tutorial, and it may not even talk at the baud rate you expect. There are three generations of ESP8266 AT firmware:
| AT Firmware | Built On | Flash Needed | AT Port (UART) | Notes |
|---|---|---|---|---|
| AT 0.2x (2014 to 2015) | ESP8266 SDK 0.9.x | 512KB | GPIO1 (TX), GPIO3 (RX) | No AT+PING, no AT+UART_CUR, no _CUR/_DEF commands. Often set to 9600 baud |
| NonOS AT 1.x (up to v1.7.6, June 2024) | ESP8266 NonOS SDK (last: v3.0.6) | 1MB or more | GPIO1 (TX), GPIO3 (RX) | The best fit for 1MB ESP8266 modules. 115200 baud |
| ESP-AT 2.x for ESP8266 (v2.2.x, v2.3.0.0) | ESP8266 RTOS SDK | 2MB or more | GPIO15 (TX), GPIO13 (RX) | Same command set as the ESP32 ESP-AT. The AT port moves to GPIO13/GPIO15, which the common 8-pin modules don’t break out |
The ESP8266 AT 2.x firmware uses GPIO13 and GPIO15 for the AT commands, as listed in Espressif’s ESP8266 AT hardware connection guide, and needs 2MB of flash. So for the common 1MB ESP8266 modules, the newest firmware you can use is the NonOS AT v1.7.6, the last release of the ESP8266 NonOS SDK. That’s the firmware we use in this tutorial.
To see what your module runs, send AT+GMR. Our first ESP8266 module replied with a 2015 firmware:
|
1 2 3 4 |
AT version:0.21.0.0 SDK version:0.9.5 OK |
And this is the reply after we updated our second module to NonOS AT v1.7.6 (the steps are below):
|
1 2 3 4 5 |
AT version:1.7.6.0(Jan 24 2022 08:56:02) SDK version:3.0.6-dev(072755c) compile time:Jun 17 2024 07:38:00 Bin version(Wroom 02):1.7.6 OK |
Note: Check the module’s flash size before you plan a firmware update. My first trial used an ESP8266 module with only 512KB of flash, so it couldn’t take any AT firmware newer than 0.2x. Read the flash size with esptool flash-id (shown below). Modules sold as ESP-01S usually have 1MB.
STM32 ESP8266 Wiring
Required Parts
| QTY. | Component Name | Amazon.com | AliExpress |
|---|---|---|---|
| 1 | STM32 Blue Pill (STM32F103C8T6) | Amazon | AliExpress |
| 1 | ST-Link V2 Debugger | Amazon | AliExpress |
| 1 | ESP8266 module (ESP-01 / ESP-01S, 1MB) + 2×4 breadboard adapter | Amazon | AliExpress |
| 1 | USB-TTL (UART) Converter, 3.3V | Amazon | AliExpress |
| 1 | BreadBoard | Amazon | AliExpress |
| 1 | Jumper Wires Pack | Amazon | AliExpress |
ESP-01 (ESP8266) Pinout
The most common ESP8266 module is the ESP-01 (and the ESP-01S, which has 1MB of flash and a pull-up on its reset pin). It has an 8-pin 2×4 header:
| ESP-01 Pin | Function | How We Connect It |
|---|---|---|
| VCC (3V3) | 3.3V supply, up to about 300mA peaks while transmitting | Blue Pill 3.3V (with the Blue Pill powered from USB) |
| GND | Ground | GND |
| TX (GPIO1) | UART0 TX: AT replies (and the boot log at 74880 baud) | STM32 PA10 (USART1 RX) |
| RX (GPIO3) | UART0 RX: AT commands | STM32 PA9 (USART1 TX) |
| CH_PD (EN) | Chip enable, must be high to run | 3.3V |
| RST | Reset, active low | Not connected (or a GPIO for hardware reset) |
| GPIO0 | Boot mode: low at reset = flash mode | Not connected (low only to update the firmware) |
| GPIO2 | General purpose, UART1 TX (log) | Not connected |

STM32 Blue Pill to ESP8266 Wiring
Connect the STM32’s USART1 to the ESP8266, and USART2’s TX pin to your USB-TTL adapter for the log (see the Blue Pill pinout for the pin locations). TX goes to RX, RX goes to TX, and all the grounds are connected:
PA9 USART1 TX, goes to the ESP8266 RX: the AT commands.
PA10 USART1 RX, goes to the ESP8266 TX: the replies, events, and received data.
3.3V Goes to the ESP8266 VCC and CH_PD (EN) pins.
PA2 USART2 TX, goes to the USB-TTL adapter’s RX: the log to your PC at 115200 baud.
GND Goes to the ESP8266 GND and the USB-TTL GND: common ground.


The ST-Link stays on the Blue Pill’s SWD header (SWDIO, SWCLK, GND) as usual and isn’t shown in the diagram.
Note: Power the Blue Pill from its micro-USB port when its 3.3V pin feeds the ESP8266. The ST-Link’s 3.3V output can’t carry the ESP8266’s transmit current peaks (about 300mA), and the module resets during the WiFi join. On the common 2×4 breadboard adapters, CH_PD (EN) is not pulled up, so wire it to 3.3V yourself. Otherwise, the module stays off, and its TX line sits low.
Testing ESP8266 AT Commands With a USB-TTL Converter
Before connecting the ESP8266 to the STM32, it’s worth a quick test from your PC. It proves the module, its power, and its baud rate on their own, so any later problem is on the STM32 side. Connect the ESP8266 to a 3.3V USB-TTL converter instead of the Blue Pill (ESP8266 TX to converter RX, ESP8266 RX to converter TX, GND to GND), open a serial terminal at 115200 baud with CR+LF line endings, and type AT:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
> AT (39 ms) AT OK > AT+GMR (39 ms) AT+GMR AT version:1.7.6.0(Jan 24 2022 08:56:02) SDK version:3.0.6-dev(072755c) compile time:Jun 17 2024 07:38:00 Bin version(Wroom 02):1.7.6 OK > AT+CWMODE? (31 ms) AT+CWMODE? +CWMODE:2 OK > AT+UART_CUR? (29 ms) AT+UART_CUR? +UART_CUR:115273,8,1,0,1 OK > AT+CIPSTATUS (30 ms) AT+CIPSTATUS STATUS:5 OK |
Each command is echoed back (the echo is on by default), followed by the reply and OK. Our updated module answered every command in 30 to 40ms. If you get nothing, try 9600 baud (old firmware), check that CH_PD is at 3.3V, and swap TX and RX. If you get unreadable characters only at power-up, that’s the ESP8266 boot log, which is sent at 74880 baud.
How to Update the ESP8266 AT Firmware
If AT+GMR shows an AT version below 1.7, update the module. You need the same USB-TTL converter, esptool, and the AT binaries from the NonOS SDK. If you have the Arduino ESP8266 or ESP32 core installed, esptool is already on your PC (in the core’s tools/esptool_py folder), or install it with pip install esptool.
Step 1: Put the ESP8266 in Flash Mode
Keep the USB-TTL wiring from the test above, and connect GPIO0 to GND. Then reset the module (briefly connect RST to GND, or power-cycle it). With GPIO0 low at reset, the ESP8266 starts its ROM bootloader instead of the AT firmware.
Step 2: Check the Flash Size
Read the flash chip ID (replace COM20 with your converter’s port):
|
1 |
esptool --chip esp8266 --port COM20 flash-id |
Our second ESP8266 module reported Detected flash size: 1MB, so it can take the NonOS AT v1.7.6. Our first module reported 512KB, and we stopped there.
Step 3: Download the AT Binaries
From the ESP8266 NonOS SDK v3.0.6 bin folder, download boot_v1.7.bin, esp_init_data_default_v08.bin, blank.bin, and at/512+512/user1.1024.new.2.bin (the 512+512 “Nano AT” build, which is the one that fits 1MB of flash).
Step 4: Erase and Write the Flash
Write all the files in one command. The addresses are for a 1MB flash:
|
1 2 3 4 5 6 7 |
esptool --chip esp8266 --port COM20 --baud 115200 write-flash --erase-all -fm dout -fs 1MB ^ 0x00000 boot_v1.7.bin ^ 0x01000 user1.1024.new.2.bin ^ 0x7E000 blank.bin ^ 0xFB000 blank.bin ^ 0xFC000 esp_init_data_default_v08.bin ^ 0xFE000 blank.bin |
esptool checks each region after writing it ( Hash of data verified). The whole update took about 30 seconds on our module. Then disconnect GPIO0 from GND, reset the module, and send AT+GMR again to confirm the new version.
Note: Use -fm dout: many ESP8266 modules don’t boot with the faster QIO flash mode. On Linux or macOS, replace the ^ line continuations with \. If you prefer a GUI, Espressif’s Flash Download Tool for Windows uses the same files and addresses.
Note: After the update, the module starts in SoftAP mode ( +CWMODE:2) and creates its own WiFi network. Our driver switches it to station mode ( AT+CWMODE_CUR=1) before joining your network.
STM32 CubeMX Configuration Steps
All three examples use the same CubeMX configuration: USART1 with DMA for the ESP8266, USART2 for the log, and the on-board LED on PC13.
#1
Open STM32CubeMX, create a new project, and select the STM32F103C8T6 in the MCU selector
#2
Set SYS > Debug to Serial Wire

#3
Set RCC > High Speed Clock (HSE) to Crystal/Ceramic Resonator, and set HCLK to 72MHz in the Clock Configuration tab


#4
Enable USART1 in Asynchronous mode (115200 baud, 8N1)

#5
In USART1’s DMA Settings tab, add USART1_RX with Mode set to Circular, and add USART1_TX (Mode Normal)

#6
In USART1’s NVIC Settings tab, enable the USART1 global interrupt (the two DMA channel interrupts are enabled by CubeMX)

#7
Enable USART2 in Asynchronous mode (115200 baud, 8N1) for the log

#8
Set PC13 as GPIO_Output with the user label LED (the Blue Pill’s on-board LED)

Here’s the finished pin configuration:

#9
In Project Manager, name the project, set the Toolchain/IDE to STM32CubeIDE, and click Generate Code

STM32 ESP8266 AT Commands Driver (ESP_AT)
Sending AT and waiting for OK is easy. The hard part is everything else the ESP8266 sends: WIFI DISCONNECT when the router goes away, +IPD frames when data arrives, busy p... when a command comes too early, and a boot log at another baud rate when the module resets. A blocking HAL_UART_Receive loop misses these lines, and the code that waits for OK freezes the whole application.
So for this series, we wrote our own ESP_AT driver: plain C, HAL called directly, two files ( ESP_AT.c and ESP_AT.h), no dynamic memory, and about 8.8KB of flash and 3.9KB of RAM per module. It works with all three ESP8266 AT generations and with ESP-AT on the ESP32 family. Here is what it does:
- DMA reception in circular mode: every byte from the ESP8266 lands in a 2KB ring buffer with no CPU work, and the driver reads the buffer by the DMA counter. Nothing is lost while the main loop is busy (the STM32 UART DMA tutorial explains the mechanism).
- Non-blocking jobs: each task (begin, join, connect, send) is a small state machine run by ESP_AT_Process() in the main loop. It ends with an event. Every job also has a _Blocking version for simple programs.
- Events: WiFi connected, got IP, disconnected, link opened and closed, received data, and any other line the module sends by itself.
- Binary-safe receive: +IPD,<length>: data is read by its length, not by searching for text, so binary data and \r\n inside the data are safe.
- Auto-baud and baud switching: the driver finds the module’s baud rate (115200, 9600, 74880, and others) and can switch it to 921600 with AT+UART_CUR.
- Firmware detection: AT+GMR tells the driver which commands exist (for example, AT+CWJAP_CUR on NonOS AT 1.x, so the network isn’t written to flash on every join).
- Auto reconnect after a WiFi drop, busy p... retries, and passwords that are escaped as the AT manual requires and never printed in the log.

To add the driver to your project, copy the ESP_AT folder next to Core, and add it to the include paths and source locations (Project > Properties > C/C++ General > Paths and Symbols). The download at the end of this tutorial has the driver and all three projects ready to build. These are the functions the examples use:
| Function | What It Does |
|---|---|
ESP_AT_Init(&esp, &cfg) | Checks the UART and DMA setup and starts the reception |
ESP_AT_Process(&esp) | Runs the parser, the jobs, and the timers. Call it in the main loop as often as possible |
ESP_AT_Begin(&esp) | Auto-baud, ATE0, AT+GMR (firmware detection), and the optional baud switch |
ESP_AT_Command(&esp, cmd, timeout) | Sends any AT command and collects its reply |
ESP_AT_WiFiJoin(&esp, ssid, pwd) | Station mode, joins the network, and reads the IP address |
ESP_AT_Connect(&esp, link, type, host, port) | Opens a TCP, UDP, or SSL connection |
ESP_AT_Send(&esp, link, data, len) | Sends data with AT+CIPSEND (long data is split into 2048-byte chunks) |
ESP_AT_..._Blocking() | The same jobs, waiting until they finish (for simple programs) |
STM32 ESP8266 WiFi Example 1: AT Commands
In the first example project, the STM32 finds the ESP8266, reads its firmware version, and sends ten common AT commands, printing each reply and how long it took. It’s the STM32 version of the USB-TTL test above, and it’s the first thing to run when you wire a new module.
Wiring: PA9 to ESP8266 RX, PA10 to ESP8266 TX, 3.3V to VCC and CH_PD, PA2 to the USB-TTL RX, and GND to both.
Here is The Application Code For This Example Project (main.c). Only the USER CODE sections are shown; the rest of the file is generated by CubeMX:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
/* USER CODE BEGIN Includes */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "ESP_AT.h" #include "wifi_secrets.h" /* USER CODE END Includes */ /* USER CODE BEGIN 0 */ /* One handle per ESP module */ static ESP_AT_HandleType esp; /* printf-style log on USART2 (the USB-UART adapter to the PC) */ static void Log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void Log(const char *fmt, ...) { char buf[200]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (n > (int)sizeof(buf) - 1) n = (int)sizeof(buf) - 1; if (n > 0) HAL_UART_Transmit(&huart2, (uint8_t *)buf, (uint16_t)n, 100); } /* Driver traffic log: ">>" = sent to the module, "<<" = received, "--" = driver note */ static void OnTrace(ESP_AT_HandleType *h, ESP_AT_TraceType type, const char *text) { (void)h; Log("%s %s\r\n", (type == ESP_AT_TRACE_TX) ? ">>" : (type == ESP_AT_TRACE_RX) ? "<<" : "--", text); } /* The HAL stops the DMA reception after a UART error; the driver restarts it */ void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { ESP_AT_UART_ErrorCallback(&esp, huart); } /* The commands this demo sends, with their timeouts. Each reply is printed by OnTrace. */ static const struct { const char *cmd; uint32_t timeout_ms; } demoCommands[] = { { "AT", 1000 }, /* is the module there? */ { "AT+GMR", 1000 }, /* firmware versions */ { "AT+CWMODE?", 1000 }, /* WiFi mode: 1 station, 2 SoftAP, 3 both */ { "AT+CWMODE=1", 1000 }, /* station mode (join a router) */ { "AT+CWLAP", 10000 }, /* scan for WiFi networks */ { "AT+CIPMUX?", 1000 }, /* single (0) or multiple (1) connections */ { "AT+CIFSR", 1000 }, /* IP and MAC addresses */ { "AT+CIPSTATUS", 1000 }, /* connection status */ { "AT+UART_CUR?", 1000 }, /* current UART settings (not on AT 0.2x) */ { "AT+SYSRAM?", 1000 }, /* free heap (ESP-AT only) */ }; /* USER CODE END 0 */ /* Inside main(), after the MX_..._Init() calls */ /* USER CODE BEGIN 2 */ ESP_AT_ConfigType cfg = {0}; ESP_AT_StatusType s; cfg.huart = &huart1; /* USART1: PA9 TX, PA10 RX, RX DMA circular */ cfg.onTrace = OnTrace; /* print every line sent and received */ Log("\r\n=== ESP_AT Demo 1: talk to the ESP module ===\r\n"); if (ESP_AT_Init(&esp, &cfg) != ESP_AT_OK) { Log("Init failed: check that USART1 RX DMA is in circular mode\r\n"); Error_Handler(); } /* Auto-baud, ATE0, AT+GMR, AT+CIPMUX=0 */ s = ESP_AT_Begin_Blocking(&esp); if (s != ESP_AT_OK) { Log("Begin failed: %s (check wiring, power, EN pin)\r\n", ESP_AT_StatusText(s)); } else { Log("\r\nModule found at %lu baud\r\n", (unsigned long)esp.baudRate); Log("Firmware: %s -> %s, feature flags 0x%04X\r\n\r\n", esp.version, ESP_AT_FirmwareText(esp.firmware), (unsigned)esp.features); for (uint32_t i = 0; i < sizeof(demoCommands) / sizeof(demoCommands[0]); i++) { s = ESP_AT_Command_Blocking(&esp, demoCommands[i].cmd, demoCommands[i].timeout_ms); Log("[%s in %lu ms]\r\n\r\n", ESP_AT_StatusText(s), (unsigned long)esp.lastCmdMs); } Log("Demo 1 done. Lines the module sends by itself are still printed below.\r\n"); } uint32_t ledTime = HAL_GetTick(); /* USER CODE END 2 */ /* Inside while (1) */ /* USER CODE BEGIN 3 */ ESP_AT_Process(&esp); /* keeps parsing what the module sends */ if (HAL_GetTick() - ledTime >= 500) { ledTime = HAL_GetTick(); HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); } } /* USER CODE END 3 */ |
STM32 ESP8266 Example 1 Code Explanation
OnTrace() prints every line the driver sends ( >>) and receives ( <<) on USART2, so you see the whole AT exchange. HAL_UART_ErrorCallback() hands UART errors to the driver, because the HAL stops the DMA reception after a framing or overrun error (which happens every time the ESP8266 prints its boot log at 74880 baud).
ESP_AT_Begin_Blocking() sends AT at each baud rate in the driver’s list until the module answers, then turns the echo off with ATE0 and reads AT+GMR. After that, esp.baudRate, esp.version, and esp.firmware tell the application what it’s talking to. The loop then sends each command in demoCommands[] with ESP_AT_Command_Blocking() and prints the result and the time from esp.lastCmdMs.
STM32 ESP8266 Example 1 Testing
This is the real hardware testing result for this example project on my Blue Pill and ESP8266 (network names and access point MAC addresses are hidden):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
=== ESP_AT Demo 1: talk to the ESP module === >> AT << OK -- module answers at 115200 baud >> ATE0 << OK >> AT+GMR << AT version:1.7.6.0(Jan 24 2022 08:56:02) << SDK version:3.0.6-dev(072755c) << compile time:Jun 17 2024 07:38:00 << Bin version(Wroom 02):1.7.6 << OK >> AT+CIPMUX=0 << OK Module found at 115200 baud Firmware: AT version:1.7.6.0(Jan 24 2022 08:56:02) -> NonOS AT 1.x, feature flags 0x003F >> AT << OK [OK in 2 ms] >> AT+GMR << AT version:1.7.6.0(Jan 24 2022 08:56:02) << SDK version:3.0.6-dev(072755c) << compile time:Jun 17 2024 07:38:00 << Bin version(Wroom 02):1.7.6 << OK [OK in 20 ms] >> AT+CWMODE? << +CWMODE:1 << OK [OK in 4 ms] >> AT+CWMODE=1 << OK [OK in 3 ms] >> AT+CWLAP << +CWLAP:(3,"",-81,"xx:xx:xx:xx:xx:xx",2,118,0,4,4,7,0) << +CWLAP:(3,"",-50,"xx:xx:xx:xx:xx:xx",9,25,0,5,3,7,0) << +CWLAP:(3,"Network1",-69,"xx:xx:xx:xx:xx:xx",3,50,0,4,4,7,1) << +CWLAP:(3,"MyWiFi",-49,"xx:xx:xx:xx:xx:xx",9,25,0,4,4,7,1) << +CWLAP:(4,"",-83,"xx:xx:xx:xx:xx:xx",4,36,0,5,3,7,0) << +CWLAP:(4,"Network2",-79,"xx:xx:xx:xx:xx:xx",9,60,0,5,3,7,1) << +CWLAP:(4,"Network3",-90,"xx:xx:xx:xx:xx:xx",5,60,0,5,3,7,0) << +CWLAP:(4,"",-65,"xx:xx:xx:xx:xx:xx",9,45,0,4,4,7,0) << +CWLAP:(3,"MyWiFi",-64,"xx:xx:xx:xx:xx:xx",9,46,0,4,4,7,0) << +CWLAP:(4,"",-75,"xx:xx:xx:xx:xx:xx",11,51,0,5,3,7,0) << OK [OK in 1663 ms] >> AT+CIPMUX? << +CIPMUX:0 << OK [OK in 4 ms] >> AT+CIFSR << +CIFSR:STAIP,"192.168.1.108" << +CIFSR:STAMAC,"d8:bf:c0:11:1f:49" << OK [OK in 11 ms] >> AT+CIPSTATUS << STATUS:4 << OK [OK in 5 ms] >> AT+UART_CUR? << +UART_CUR:115273,8,1,0,0 << OK [OK in 8 ms] >> AT+SYSRAM? << +SYSRAM:51608 << OK [OK in 5 ms] |
The module answered at 115200 baud on the first try, and most commands answered in 2 to 20ms. AT+CWLAP (the WiFi scan) took 1.7 seconds, because the module listens on every channel. Notice that AT+SYSRAM? shows about 51KB of free RAM inside the ESP8266, which is more than the Blue Pill has in total.
STM32 ESP8266 Example 2: Connect to WiFi and Get IP Address
In this example project, the STM32 joins your WiFi network, prints the IP address, gateway, and netmask, and then runs a non-blocking loop that keeps the connection alive:
- The on-board LED is on while the ESP8266 is connected, and blinks fast while it isn’t.
- When the module reports WIFI DISCONNECT (router restarted, out of range), the driver joins the network again by itself, with a growing delay between attempts.
- To show this without touching the router, the example drops the WiFi once with AT+CWQAP 30 seconds after the start.
Write your WiFi name and password in Core/Inc/wifi_secrets.h:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* * wifi_secrets.h * Your WiFi network name and password. Keep this file out of any project you share. */ #ifndef WIFI_SECRETS_H_ #define WIFI_SECRETS_H_ #define WIFI_SSID "YOUR_WIFI_NAME" #define WIFI_PASSWORD "YOUR_WIFI_PASSWORD" /* Example 3 only: the PC that runs tcp_echo_server.py (same network as the ESP module) */ #define SERVER_IP "192.168.1.100" #define SERVER_PORT 5000 #endif /* WIFI_SECRETS_H_ */ |
Here is The Application Code For This Example Project (main.c). Only the USER CODE sections are shown; the rest of the file is generated by CubeMX:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/* USER CODE BEGIN Includes */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "ESP_AT.h" #include "wifi_secrets.h" /* USER CODE END Includes */ /* USER CODE BEGIN 0 */ /* One handle per ESP module */ static ESP_AT_HandleType esp; /* printf-style log on USART2 (the USB-UART adapter to the PC) */ static void Log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void Log(const char *fmt, ...) { char buf[200]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (n > (int)sizeof(buf) - 1) n = (int)sizeof(buf) - 1; if (n > 0) HAL_UART_Transmit(&huart2, (uint8_t *)buf, (uint16_t)n, 100); } /* Driver traffic log: ">>" = sent to the module, "<<" = received, "--" = driver note */ static void OnTrace(ESP_AT_HandleType *h, ESP_AT_TraceType type, const char *text) { (void)h; Log("%s %s\r\n", (type == ESP_AT_TRACE_TX) ? ">>" : (type == ESP_AT_TRACE_RX) ? "<<" : "--", text); } /* The HAL stops the DMA reception after a UART error; the driver restarts it */ void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { ESP_AT_UART_ErrorCallback(&esp, huart); } /* 1: drop the WiFi once, 30 s after the start, with a raw AT+CWQAP (like a router going away), * to show the auto reconnect without touching the router. 0: off */ #define DEMO_SIMULATE_DROP 1 /* Events from the driver: WiFi state changes and the end of each job */ static void OnEvent(ESP_AT_HandleType *h, ESP_AT_EventType ev, const ESP_AT_EventDataType *d) { switch (ev) { case ESP_AT_EVT_WIFI_CONNECTED: Log("[event] WiFi connected (t = %lu ms)\r\n", (unsigned long)HAL_GetTick()); break; case ESP_AT_EVT_WIFI_GOT_IP: Log("[event] WiFi got an IP (t = %lu ms)\r\n", (unsigned long)HAL_GetTick()); break; case ESP_AT_EVT_WIFI_DISCONNECTED: Log("[event] WiFi disconnected (t = %lu ms), auto reconnect is on\r\n", (unsigned long)HAL_GetTick()); break; case ESP_AT_EVT_READY: Log("[event] the module restarted\r\n"); break; case ESP_AT_EVT_JOB_DONE: Log("[event] job %s done: %s\r\n", ESP_AT_JobText(d->job), ESP_AT_StatusText(d->status)); if ((d->job == ESP_AT_JOB_JOIN || d->job == ESP_AT_JOB_GET_IP) && d->status == ESP_AT_OK) Log(" IP %s, gateway %s, netmask %s\r\n", h->ip, h->gateway, h->netmask); break; case ESP_AT_EVT_URC: Log("[event] module says: %s\r\n", d->line); break; default: break; } } /* USER CODE END 0 */ /* Inside main(), after the MX_..._Init() calls */ /* USER CODE BEGIN 2 */ ESP_AT_ConfigType cfg = {0}; ESP_AT_StatusType s; cfg.huart = &huart1; cfg.autoReconnect = 1; /* rejoin by itself after WIFI DISCONNECT */ cfg.onEvent = OnEvent; cfg.onTrace = OnTrace; Log("\r\n=== ESP_AT Demo 2: WiFi join, IP, auto reconnect ===\r\n"); if (ESP_AT_Init(&esp, &cfg) != ESP_AT_OK) Error_Handler(); s = ESP_AT_Begin_Blocking(&esp); Log("Begin: %s, %s at %lu baud\r\n", ESP_AT_StatusText(s), ESP_AT_FirmwareText(esp.firmware), (unsigned long)esp.baudRate); /* Old AT 0.2x firmware sends no WIFI DISCONNECT message: poll the WiFi state instead */ if (!(esp.features & ESP_AT_FEAT_WIFI_EVENTS)) esp.cfg.wifiCheckMs = 5000; uint32_t t0 = HAL_GetTick(); s = ESP_AT_WiFiJoin_Blocking(&esp, WIFI_SSID, WIFI_PASSWORD); Log("Join: %s in %lu ms", ESP_AT_StatusText(s), (unsigned long)(HAL_GetTick() - t0)); if (s == ESP_AT_OK) Log(", IP %s\r\n", esp.ip); else Log(", +CWJAP error code %d (1 timeout, 2 password, 3 no AP, 4 failed)\r\n", esp.joinError); uint32_t ledTime = HAL_GetTick(), statusTime = HAL_GetTick(); uint8_t dropped = !DEMO_SIMULATE_DROP; /* USER CODE END 2 */ /* Inside while (1) */ /* USER CODE BEGIN 3 */ ESP_AT_Process(&esp); /* parser, events, auto reconnect: all in here */ /* LED: steady on while connected, fast blink while not (PC13 LED is active low) */ if (ESP_AT_IsWiFiConnected(&esp)) HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); else if (HAL_GetTick() - ledTime >= 100) { ledTime = HAL_GetTick(); HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); } /* Status line every 10 s */ if (HAL_GetTick() - statusTime >= 10000) { statusTime = HAL_GetTick(); Log("[status] t = %lu s, WiFi %s, IP %s\r\n", (unsigned long)(statusTime / 1000), ESP_AT_IsWiFiConnected(&esp) ? "connected" : "NOT connected", esp.ip[0] ? esp.ip : "-"); } /* Simulated router drop: a raw command, so the driver still has the network and rejoins it */ if (!dropped && HAL_GetTick() > 30000 && !ESP_AT_IsBusy(&esp)) { dropped = 1; Log("[demo] dropping the WiFi with AT+CWQAP to test the auto reconnect\r\n"); (void)ESP_AT_Command(&esp, "AT+CWQAP", 2000); } } /* USER CODE END 3 */ |
STM32 ESP8266 Example 2 Code Explanation
Setting cfg.autoReconnect = 1 is all it takes to keep the connection: the driver remembers the network from ESP_AT_WiFiJoin_Blocking() and joins it again after every WIFI DISCONNECT. OnEvent() receives the WiFi events and the end of each job, so the application knows the state without polling the module.
The main loop only calls ESP_AT_Process() and updates the LED from ESP_AT_IsWiFiConnected(). It never waits for the module. That’s the pattern for every real application: the STM32 keeps doing its own work, and the WiFi runs in the background.
Note: The old AT 0.2x firmware doesn’t send WIFI DISCONNECT at all. For that firmware, the example sets esp.cfg.wifiCheckMs = 5000, and the driver polls AT+CIPSTATUS every 5 seconds instead.
STM32 ESP8266 Example 2 Testing
This is the real hardware testing result for this example project:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
=== ESP_AT Demo 2: WiFi join, IP, auto reconnect === >> AT << OK -- module answers at 115200 baud >> ATE0 << OK >> AT+GMR << AT version:1.7.6.0(Jan 24 2022 08:56:02) << SDK version:3.0.6-dev(072755c) << compile time:Jun 17 2024 07:38:00 << Bin version(Wroom 02):1.7.6 << OK >> AT+CIPMUX=0 << OK [event] job BEGIN done: OK Begin: OK, NonOS AT 1.x at 115200 baud >> AT+CWMODE_CUR=1 << OK >> AT+CWJAP_CUR="MyWiFi","********" << WIFI CONNECTED [event] WiFi connected (t = 4321 ms) << WIFI GOT IP [event] WiFi got an IP (t = 5747 ms) << OK >> AT+CIPSTA_CUR? << +CIPSTA_CUR:ip:"192.168.1.108" << +CIPSTA_CUR:gateway:"192.168.1.1" << +CIPSTA_CUR:netmask:"255.255.255.0" << OK [event] job JOIN done: OK IP 192.168.1.108, gateway 192.168.1.1, netmask 255.255.255.0 Join: OK in 6128 ms, IP 192.168.1.108 [status] t = 16 s, WiFi connected, IP 192.168.1.108 [status] t = 26 s, WiFi connected, IP 192.168.1.108 [demo] dropping the WiFi with AT+CWQAP to test the auto reconnect >> AT+CWQAP << OK [event] job COMMAND done: OK << WIFI DISCONNECT [event] WiFi disconnected (t = 30024 ms), auto reconnect is on -- auto reconnect: joining again >> AT+CWMODE_CUR=1 << OK >> AT+CWJAP_CUR="MyWiFi","********" << WIFI CONNECTED [event] WiFi connected (t = 34422 ms) << WIFI GOT IP [event] WiFi got an IP (t = 35873 ms) << OK >> AT+CIPSTA_CUR? << +CIPSTA_CUR:ip:"192.168.1.108" << +CIPSTA_CUR:gateway:"192.168.1.1" << +CIPSTA_CUR:netmask:"255.255.255.0" << OK [event] job JOIN done: OK IP 192.168.1.108, gateway 192.168.1.1, netmask 255.255.255.0 [status] t = 36 s, WiFi connected, IP 192.168.1.108 [status] t = 46 s, WiFi connected, IP 192.168.1.108 [status] t = 56 s, WiFi connected, IP 192.168.1.108 [status] t = 66 s, WiFi connected, IP 192.168.1.108 |
The ESP8266 joined the network in 6.1 seconds: WIFI CONNECTED came 4.3 seconds after the start, and WIFI GOT IP (the router’s DHCP answer) 1.4 seconds later. When the example dropped the WiFi at 30 seconds, the driver started a new join 2 seconds after the WIFI DISCONNECT event, and the module had its IP address back 5.8 seconds after the drop.
STM32 ESP8266 WiFi Example 3: TCP Client (Send and Receive Data)
In this example project, the STM32 connects to a TCP server on your PC through the ESP8266 and exchanges data with it in both directions:
- The STM32 sends a text line every 2 seconds.
- The PC server sends each line back ( echo: ...), and the STM32 measures how long the echo takes.
- Every 6 seconds, the server sends LED TOGGLE, and the STM32 toggles its on-board LED.
- If the server stops, the STM32 tries to reconnect every 3 seconds, and it continues by itself when the server is back.
In other words, this is the skeleton of any STM32 WiFi device that reports data and takes commands. The whole application is a non-blocking state machine.
How AT+CIPSEND and +IPD Work
Sending data takes two steps. The STM32 sends AT+CIPSEND=<length>, waits for the ESP8266’s > prompt, and then sends exactly that many bytes. The module answers Recv <n> bytes and SEND OK when the data is on its way. Received data arrives at any time, as +IPD,<length>: followed by the data:
|
1 2 3 4 5 6 |
>> AT+CIPSEND=54 << > >> Hello from STM32 #1, uptime 8392 ms, received 0 bytes << Recv 54 bytes << SEND OK << +IPD,64:echo: Hello from STM32 #1, uptime 8392 ms, received 0 bytes |

The PC TCP Server
Run this Python script on your PC (Python 3, no extra packages), and set SERVER_IP in wifi_secrets.h to your PC’s IP address ( ipconfig on Windows). Allow Python through the Windows firewall when it asks.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
"""TCP test server for ESP_AT Demo 3 (STM32 + ESP module as a TCP client). - Greets each client, echoes every line back as "echo: <line>", - sends an LED command every 6 seconds (LED TOGGLE), - prints everything with a timestamp. Stop with Ctrl+C. python tcp_echo_server.py [port] [--seconds N] --seconds N stops the server after N seconds (for scripted bench runs). """ import socket, sys, time, threading args = [a for a in sys.argv[1:] if not a.startswith("--")] port = int(args[0]) if args else 5000 stop_after = None if "--seconds" in sys.argv: stop_after = float(sys.argv[sys.argv.index("--seconds") + 1]) t_start = time.time() def log(msg): print(f"[{time.time() - t_start:8.3f}] {msg}", flush=True) def client(conn, addr): log(f"client {addr[0]}:{addr[1]} connected") conn.settimeout(0.2) buf = b"" next_cmd = time.time() + 6 try: conn.sendall(b"Hello STM32, this is the PC\n") while True: if time.time() >= next_cmd: conn.sendall(b"LED TOGGLE\n") log("sent: LED TOGGLE") next_cmd = time.time() + 6 try: d = conn.recv(4096) except socket.timeout: continue if not d: break buf += d while b"\n" in buf: line, buf = buf.split(b"\n", 1) text = line.decode(errors="replace").rstrip("\r") log(f"recv: {text}") conn.sendall(b"echo: " + line + b"\n") except OSError as e: log(f"connection error: {e}") finally: conn.close() log(f"client {addr[0]} closed") srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind(("0.0.0.0", port)) srv.listen(4) srv.settimeout(0.5) log(f"listening on port {port}") while stop_after is None or time.time() - t_start < stop_after: try: c, a = srv.accept() except socket.timeout: continue threading.Thread(target=client, args=(c, a), daemon=True).start() log("stopped") |
Here is The Application Code For This Example Project (main.c). Only the USER CODE sections are shown; the rest of the file is generated by CubeMX:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
/* USER CODE BEGIN Includes */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "ESP_AT.h" #include "wifi_secrets.h" /* USER CODE END Includes */ /* USER CODE BEGIN 0 */ /* One handle per ESP module */ static ESP_AT_HandleType esp; /* printf-style log on USART2 (the USB-UART adapter to the PC) */ static void Log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void Log(const char *fmt, ...) { char buf[200]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (n > (int)sizeof(buf) - 1) n = (int)sizeof(buf) - 1; if (n > 0) HAL_UART_Transmit(&huart2, (uint8_t *)buf, (uint16_t)n, 100); } /* Driver traffic log: ">>" = sent to the module, "<<" = received, "--" = driver note */ static void OnTrace(ESP_AT_HandleType *h, ESP_AT_TraceType type, const char *text) { (void)h; Log("%s %s\r\n", (type == ESP_AT_TRACE_TX) ? ">>" : (type == ESP_AT_TRACE_RX) ? "<<" : "--", text); } /* The HAL stops the DMA reception after a UART error; the driver restarts it */ void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) { ESP_AT_UART_ErrorCallback(&esp, huart); } /* The application: a small state machine, so the main loop never waits */ typedef enum { APP_BEGIN, APP_WAIT_BEGIN, APP_JOIN, APP_WAIT_JOIN, APP_ONLINE } AppStateType; static char txMsg[96]; /* must stay unchanged until the send job ends */ static uint32_t txCount = 0; static uint32_t txTime = 0; /* when the last message was handed to the driver */ static char rxLine[96]; /* received text, assembled into lines */ static uint16_t rxLen = 0; static uint32_t rxBytes = 0; /* A complete line from the PC: commands for the LED, everything else is printed */ static void HandleServerLine(const char *line) { if (strcmp(line, "LED ON") == 0) HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); else if (strcmp(line, "LED OFF") == 0) HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET); else if (strcmp(line, "LED TOGGLE") == 0) HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); else if (strncmp(line, "echo: ", 6) == 0) { Log("[app] echo came back after %lu ms\r\n", (unsigned long)(HAL_GetTick() - txTime)); return; } else return; Log("[app] LED command: %s\r\n", line); } static void OnEvent(ESP_AT_HandleType *h, ESP_AT_EventType ev, const ESP_AT_EventDataType *d) { (void)h; switch (ev) { case ESP_AT_EVT_DATA: /* +IPD data: may arrive in several chunks (d->remaining = bytes still to come) */ rxBytes += d->len; Log("[event] +IPD link %u: %u bytes%s\r\n", d->link, d->len, d->remaining ? " (more follows)" : ""); for (uint16_t i = 0; i < d->len; i++) { char c = (char)d->data[i]; if (c == '\n' || rxLen >= sizeof(rxLine) - 1) { rxLine[rxLen] = '\0'; if (rxLen > 0 && rxLine[rxLen - 1] == '\r') rxLine[rxLen - 1] = '\0'; Log("[app] from PC: \"%s\"\r\n", rxLine); HandleServerLine(rxLine); rxLen = 0; } else rxLine[rxLen++] = c; } break; case ESP_AT_EVT_LINK_OPENED: Log("[event] link %u open\r\n", d->link); break; case ESP_AT_EVT_LINK_CLOSED: Log("[event] link %u closed\r\n", d->link); rxLen = 0; break; case ESP_AT_EVT_WIFI_DISCONNECTED: Log("[event] WiFi disconnected\r\n"); break; case ESP_AT_EVT_WIFI_GOT_IP: Log("[event] WiFi got an IP\r\n"); break; case ESP_AT_EVT_JOB_DONE: if (d->status != ESP_AT_OK || d->job != ESP_AT_JOB_SEND) Log("[event] job %s done: %s\r\n", ESP_AT_JobText(d->job), ESP_AT_StatusText(d->status)); break; default: break; } } /* USER CODE END 0 */ /* Inside main(), after the MX_..._Init() calls */ /* USER CODE BEGIN 2 */ ESP_AT_ConfigType cfg = {0}; AppStateType app = APP_BEGIN; uint32_t nextConnect = 0, nextSend = 0; cfg.huart = &huart1; cfg.autoReconnect = 1; cfg.onEvent = OnEvent; cfg.onTrace = OnTrace; Log("\r\n=== ESP_AT Demo 3: TCP client, send and receive (+IPD) ===\r\n"); Log("Server: %s:%u (run tools\\tcp_echo_server.py on the PC)\r\n", SERVER_IP, (unsigned)SERVER_PORT); if (ESP_AT_Init(&esp, &cfg) != ESP_AT_OK) Error_Handler(); /* USER CODE END 2 */ /* Inside while (1) */ /* USER CODE BEGIN 3 */ ESP_AT_Process(&esp); uint32_t now = HAL_GetTick(); switch (app) { case APP_BEGIN: /* start the module check */ if (ESP_AT_Begin(&esp) == ESP_AT_OK) app = APP_WAIT_BEGIN; break; case APP_WAIT_BEGIN: if (ESP_AT_GetJobStatus(&esp) == ESP_AT_RUNNING) break; if (ESP_AT_GetJobStatus(&esp) == ESP_AT_OK) { Log("[app] module ready: %s\r\n", esp.version); app = APP_JOIN; } else app = APP_BEGIN; /* try again */ break; case APP_JOIN: if (ESP_AT_WiFiJoin(&esp, WIFI_SSID, WIFI_PASSWORD) == ESP_AT_OK) app = APP_WAIT_JOIN; break; case APP_WAIT_JOIN: if (ESP_AT_GetJobStatus(&esp) == ESP_AT_RUNNING) break; if (ESP_AT_GetJobStatus(&esp) == ESP_AT_OK) { Log("[app] joined, IP %s\r\n", esp.ip); app = APP_ONLINE; } else app = APP_JOIN; break; case APP_ONLINE: if (ESP_AT_IsBusy(&esp) || !ESP_AT_IsWiFiConnected(&esp)) break; /* auto reconnect handles WiFi */ if (!ESP_AT_IsLinkOpen(&esp, 0)) { if ((int32_t)(now - nextConnect) >= 0) { nextConnect = now + 3000; /* retry every 3 s while the server is down */ (void)ESP_AT_Connect(&esp, 0, ESP_AT_LINK_TCP, SERVER_IP, SERVER_PORT); } } else if ((int32_t)(now - nextSend) >= 0) { nextSend = now + 2000; /* one line every 2 s */ int n = snprintf(txMsg, sizeof(txMsg), "Hello from STM32 #%lu, uptime %lu ms, received %lu bytes\n", (unsigned long)++txCount, (unsigned long)now, (unsigned long)rxBytes); txTime = now; if (ESP_AT_Send(&esp, 0, txMsg, (uint32_t)n) == ESP_AT_OK) Log("[app] sending #%lu (%d bytes)\r\n", (unsigned long)txCount, n); } break; } } /* USER CODE END 3 */ |
STM32 ESP8266 Example 3 Code Explanation
The application has five states: begin, wait for begin, join, wait for join, and online. Each state starts a non-blocking job ( ESP_AT_Begin(), ESP_AT_WiFiJoin()) and moves on when ESP_AT_GetJobStatus() is no longer ESP_AT_RUNNING. In the online state, the STM32 opens link 0 with ESP_AT_Connect() when it’s closed, and sends a line every 2 seconds with ESP_AT_Send().
Received data comes as ESP_AT_EVT_DATA events. A large +IPD frame is delivered in chunks of up to 256 bytes, with d->remaining telling you how many bytes of the same frame are still to come, so a 1460-byte TCP packet needs only 256 bytes of RAM on the STM32. The example collects the bytes into lines and acts on LED ON, LED OFF, and LED TOGGLE.
Note: The buffer you pass to ESP_AT_Send() must stay unchanged until the send job ends, because the driver sends it after the > prompt arrives. That’s why txMsg is a static buffer and not a local variable.
STM32 ESP8266 Example 3 Testing
This is the real hardware testing result for this example project, the STM32 side first:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
=== ESP_AT Demo 3: TCP client, send and receive (+IPD) === Server: 192.168.1.101:5000 (run tools\tcp_echo_server.py on the PC) >> AT << OK -- module answers at 115200 baud >> ATE0 << OK >> AT+GMR << AT version:1.7.6.0(Jan 24 2022 08:56:02) << SDK version:3.0.6-dev(072755c) << compile time:Jun 17 2024 07:38:00 << Bin version(Wroom 02):1.7.6 << OK >> AT+CIPMUX=0 << OK [event] job BEGIN done: OK [app] module ready: AT version:1.7.6.0(Jan 24 2022 08:56:02) >> AT+CWMODE_CUR=1 << OK >> AT+CWJAP_CUR="MyWiFi","********" << WIFI DISCONNECT << WIFI CONNECTED << WIFI GOT IP [event] WiFi got an IP << OK >> AT+CIPSTA_CUR? << +CIPSTA_CUR:ip:"192.168.1.108" << +CIPSTA_CUR:gateway:"192.168.1.1" << +CIPSTA_CUR:netmask:"255.255.255.0" << OK [event] job JOIN done: OK [app] joined, IP 192.168.1.108 >> AT+CIPSTART="TCP","192.168.1.101",5000 << CONNECT [event] link 0 open << OK [event] job CONNECT done: OK >> AT+CIPSEND=54 [app] sending #1 (54 bytes) << OK << > << Recv 54 bytes << SEND OK << +IPD,28: [event] +IPD link 0: 28 bytes [app] from PC: "Hello STM32, this is the PC" << +IPD,60: [event] +IPD link 0: 60 bytes [app] from PC: "echo: Hello from STM32 #1, uptime 5127 ms, received 0 bytes" [app] echo came back after 123 ms >> AT+CIPSEND=55 [app] sending #2 (55 bytes) << OK << > << Recv 55 bytes << SEND OK << +IPD,61: [event] +IPD link 0: 61 bytes [app] from PC: "echo: Hello from STM32 #2, uptime 7127 ms, received 88 bytes" [app] echo came back after 54 ms >> AT+CIPSEND=56 [app] sending #3 (56 bytes) << OK << > << Recv 56 bytes << SEND OK << +IPD,62: [event] +IPD link 0: 62 bytes [app] from PC: "echo: Hello from STM32 #3, uptime 9127 ms, received 149 bytes" [app] echo came back after 55 ms >> AT+CIPSEND=57 [app] sending #4 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #4, uptime 11127 ms, received 211 bytes" [app] echo came back after 110 ms << +IPD,11: [event] +IPD link 0: 11 bytes [app] from PC: "LED TOGGLE" [app] LED command: LED TOGGLE >> AT+CIPSEND=57 [app] sending #5 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #5, uptime 13127 ms, received 285 bytes" [app] echo came back after 61 ms >> AT+CIPSEND=57 [app] sending #6 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #6, uptime 15127 ms, received 348 bytes" [app] echo came back after 62 ms >> AT+CIPSEND=57 [app] sending #7 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #7, uptime 17127 ms, received 411 bytes" [app] echo came back after 40 ms << +IPD,11: [event] +IPD link 0: 11 bytes [app] from PC: "LED TOGGLE" [app] LED command: LED TOGGLE >> AT+CIPSEND=57 [app] sending #8 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #8, uptime 19127 ms, received 485 bytes" [app] echo came back after 69 ms >> AT+CIPSEND=57 [app] sending #9 (57 bytes) << OK << > << Recv 57 bytes << SEND OK << +IPD,63: [event] +IPD link 0: 63 bytes [app] from PC: "echo: Hello from STM32 #9, uptime 21127 ms, received 548 bytes" [app] echo came back after 35 ms >> AT+CIPSEND=58 [app] sending #10 (58 bytes) << OK << > << Recv 58 bytes << SEND OK << +IPD,64: [event] +IPD link 0: 64 bytes [app] from PC: "echo: Hello from STM32 #10, uptime 23127 ms, received 611 bytes" [app] echo came back after 77 ms << +IPD,11: [event] +IPD link 0: 11 bytes [app] from PC: "LED TOGGLE" [app] LED command: LED TOGGLE >> AT+CIPSEND=58 [app] sending #11 (58 bytes) << OK << > << Recv 58 bytes << SEND OK << +IPD,64: [event] +IPD link 0: 64 bytes [app] from PC: "echo: Hello from STM32 #11, uptime 25127 ms, received 686 bytes" [app] echo came back after 34 ms >> AT+CIPSEND=58 [app] sending #12 (58 bytes) << OK << > << Recv 58 bytes << SEND OK << +IPD,64: [event] +IPD link 0: 64 bytes [app] from PC: "echo: Hello from STM32 #12, uptime 27127 ms, received 750 bytes" [app] echo came back after 34 ms |
And the PC side:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
[ 0.000] listening on port 5000 [ 9.598] client 192.168.1.108:43523 connected [ 9.631] recv: Hello from STM32 #1, uptime 5127 ms, received 0 bytes [ 11.614] recv: Hello from STM32 #2, uptime 7127 ms, received 88 bytes [ 13.614] recv: Hello from STM32 #3, uptime 9127 ms, received 149 bytes [ 15.615] recv: Hello from STM32 #4, uptime 11127 ms, received 211 bytes [ 15.643] sent: LED TOGGLE [ 17.617] recv: Hello from STM32 #5, uptime 13127 ms, received 285 bytes [ 19.615] recv: Hello from STM32 #6, uptime 15127 ms, received 348 bytes [ 21.615] recv: Hello from STM32 #7, uptime 17127 ms, received 411 bytes [ 21.819] sent: LED TOGGLE [ 23.615] recv: Hello from STM32 #8, uptime 19127 ms, received 485 bytes [ 25.615] recv: Hello from STM32 #9, uptime 21127 ms, received 548 bytes [ 27.615] recv: Hello from STM32 #10, uptime 23127 ms, received 611 bytes [ 27.828] sent: LED TOGGLE [ 29.614] recv: Hello from STM32 #11, uptime 25127 ms, received 686 bytes [ 31.613] recv: Hello from STM32 #12, uptime 27127 ms, received 750 bytes [ 33.612] recv: Hello from STM32 #13, uptime 29127 ms, received 814 bytes [ 34.033] sent: LED TOGGLE [ 35.613] recv: Hello from STM32 #14, uptime 31127 ms, received 889 bytes [ 37.612] recv: Hello from STM32 #15, uptime 33127 ms, received 953 bytes [ 39.613] recv: Hello from STM32 #16, uptime 35127 ms, received 1017 bytes [ 40.221] sent: LED TOGGLE [ 40.298] stopped |
All 12 lines came back, with an echo round trip of 32 to 89ms through the ESP8266, the router, and the PC. In our longer run, 38 of 38 lines came back, and when we stopped the server, the STM32 got CLOSED, retried every 3 seconds, and continued by itself when the server was back.
Measured: Old vs Updated ESP8266 AT Firmware
We ran the same tests on our two ESP8266 modules: the first one with its original AT 0.21.0.0 firmware (2015, 512KB flash, it can’t be updated), and the second one after the update to NonOS AT v1.7.6. Both were driven by the same Blue Pill at 115200 baud:
| Test | AT 0.21.0.0 (SDK 0.9.5) | NonOS AT v1.7.6 (SDK 3.0.6) |
|---|---|---|
| WiFi join time | 3.1 to 5.1s, some joins failed | 5.0 to 6.1s, 5 of 5 joins OK |
| WIFI CONNECTED / GOT IP / DISCONNECT events | Not sent | Sent |
| Automatic reconnect after a drop | Needs polling | IP back in 5.8s |
AT+PING to the router | Not supported | 4ms average (5 of 5) |
Baud rate switch (AT+UART_CUR) | Not supported | 115200 to 921600 in 71ms |
| TCP upload throughput | Limited to 115200 baud | 7.2KB/s at 115200, 31.8KB/s at 921600 |
AT+RST to ready (at 921600) | – | 331ms |
Free RAM inside the ESP8266 (AT+SYSRAM?) | Not supported | about 51KB |
The old firmware joined the network faster, but it failed some joins and has none of the features a robust application needs: no WiFi events, no ping, and no way to raise the baud rate. With the updated firmware, the UART speed is the throughput limit. At 921600 baud, the 64KB upload ran at 31.8KB/s, more than 4 times the 115200 baud result, and 71,719 bytes echoed back by the PC arrived in 351 +IPD frames with no byte lost.

ESP8266 AT Commands on The Oscilloscope
Here’s what an AT command and its reply look like on my oscilloscope captures. CH1 (yellow) is PA9, the STM32’s TX line to the ESP8266, and CH3 (blue) is PA10, the ESP8266’s TX line back to the STM32.
The first command of Example 2 is AT plus CR LF: 4 bytes in 0.35ms at 115200 baud. The cursors show that the ESP8266’s reply starts 720µs after the command starts, so the module answered about 0.38ms after it received the last byte:
The WiFi join is a different story. At 500ms/div, the cursors run from the AT+CWJAP_CUR command (X1) to the module’s WIFI GOT IP line (X2): 3.70 seconds in this run. WIFI CONNECTED came at 2.43 seconds, and the OK came at 4.06 seconds, right before the STM32 asked for the IP address with AT+CIPSTA_CUR?. During all that time, the STM32 is free: the driver doesn’t wait in a loop, it gets the result as events:
Notice the short dips on both lines in the join capture, every 93ms. They aren’t UART bytes: the lines never go low enough. Zooming into one of them at 200µs/div shows that the ESP8266’s TX idle level drops from 3.16V to 2.28V for 0.67ms, and the STM32’s TX line dips at the same moment. Both lines follow the same 3.3V supply, so this is the supply itself sagging while the ESP8266’s radio transmits during the network scan. The UART still works because 2.28V is still a valid high level for the STM32, but it’s the reason the ESP8266 needs a strong 3.3V supply and a capacitor close to its VCC pin:
ESP8266 AT Commands List (With Real Replies)
These are the ESP8266 AT commands you’ll use most with an STM32, grouped by function, with the real replies from our ESP8266 module running NonOS AT v1.7.6. Every command ends with \r\n. The full reference is Espressif’s ESP8266 AT Instruction Set.
ESP8266 AT Commands List: Basic, WiFi, and TCP/IP (click to expand)
Basic AT Commands
| Command | What It Does | Reply From Our ESP8266 | Time (ms) |
|---|---|---|---|
AT | Tests that the module is alive | OK | 2 |
ATE0 / ATE1 | Turns the command echo off / on | OK | 2 |
AT+GMR | AT and SDK versions | AT version:1.7.6.0(Jan 24 2022 08:56:02)SDK version:3.0.6-dev(072755c)compile time:Jun 17 2024 07:38:00Bin version(Wroom 02):1.7.6OK | 19 |
AT+RST | Restarts the module | OK, then the boot log at 74880 baud, then ready | 264 to ready |
AT+UART_CUR? | Current UART settings (not saved): baud, data bits, stop bits, parity, flow control | +UART_CUR:115273,8,1,0,1 | 8 |
AT+UART_CUR=921600,8,1,0,0 | Changes the baud rate until the next reset | OK (then the module talks at 921600) | 71 |
AT+UART_DEF? | UART settings saved in flash | +UART_DEF:0,0,0,0,0 (blank after the update, the module boots at 115200) | 6 |
AT+SLEEP? | Sleep mode (0 off, 1 light, 2 modem sleep) | +SLEEP:2 | 4 |
AT+SYSRAM? | Free RAM inside the ESP8266, in bytes | +SYSRAM:51608 | 6 |
AT+RFPOWER=82 | Maximum TX power (0 to 82, in 0.25dBm steps) | OK | 3 |
WiFi AT Commands
| Command | What It Does | Reply From Our ESP8266 | Time (ms) |
|---|---|---|---|
AT+CWMODE? | WiFi mode: 1 station, 2 SoftAP, 3 both | +CWMODE:1 | 4 |
AT+CWMODE_CUR=1 | Station mode, not saved in flash | OK | 3 |
AT+CWJAP_CUR="ssid","pwd" | Joins a network (the _DEF version saves it in flash) | WIFI CONNECTEDWIFI GOT IPOK | 5035 |
AT+CWJAP_CUR? | The network the module is connected to: SSID, BSSID, channel, RSSI | +CWJAP_CUR:"MyWiFi","xx:xx:xx:xx:xx:xx",9,202,0 | 13 |
AT+CWLAP | Scans for WiFi networks | +CWLAP:(3,"MyWiFi",-47,"xx:xx:xx:xx:xx:xx",9,23,0,4,4,7,1)... one line per networkOK | 1648 |
AT+CWQAP | Disconnects from the network | OKWIFI DISCONNECT | 4 |
AT+CWAUTOCONN? | Joins the last network automatically after power-up (1 = on) | +CWAUTOCONN:1 | 6 |
AT+CWDHCP_CUR? | DHCP state (bit 0 SoftAP, bit 1 station) | +CWDHCP_CUR:3 | 5 |
AT+CWHOSTNAME? | The module’s host name on your network | +CWHOSTNAME:ESP-111F49 | 7 |
AT+CIPSTAMAC_CUR? | Station MAC address | +CIPSTAMAC_CUR:"d8:bf:c0:11:1f:49" | 10 |
AT+CIPSTA_CUR? | IP address, gateway, and netmask | +CIPSTA_CUR:ip:"192.168.1.108"+CIPSTA_CUR:gateway:"192.168.1.1"+CIPSTA_CUR:netmask:"255.255.255.0" | 16 |
AT+CIFSR | IP and MAC address (works on every firmware) | +CIFSR:STAIP,"192.168.1.108"+CIFSR:STAMAC,"d8:bf:c0:11:1f:49" | 11 |
TCP/IP AT Commands
| Command | What It Does | Reply From Our ESP8266 | Time (ms) |
|---|---|---|---|
AT+CIPSTATUS | Status: 2 got IP, 3 connected, 4 disconnected, 5 no WiFi | STATUS:2 | 4 |
AT+CIPMUX? | Single (0) or multiple (1) connections | +CIPMUX:0 | 5 |
AT+CIPMODE? | 0 normal mode, 1 transparent (passthrough) mode | +CIPMODE:0 | 5 |
AT+CIPSTO? | TCP server timeout, in seconds | +CIPSTO:180 | 5 |
AT+CIPDOMAIN="www.google.com" | DNS lookup | +CIPDOMAIN:142.251.154.119 | 59 |
AT+PING="192.168.1.1" | Pings a host, the reply is the time in ms | +2 | 7 |
AT+CIPSNTPCFG=1,0,"pool.ntp.org" | Enables SNTP time (time zone 0 = UTC) | OK | 6 |
AT+CIPSNTPTIME? | Date and time from the SNTP server | +CIPSNTPTIME:Thu Nov 26 05:41:13 2026 | 11 |
AT+CIPSTART="TCP","192.168.1.101",5000 | Opens a TCP connection (“UDP” and “SSL” also work) | CONNECTOK | 24 |
AT+CIPSEND=5 | Sends 5 bytes: wait for the > prompt, then send the data | OK>Recv 5 bytesSEND OK | 54 to SEND OK |
| (received data) | Data from the server, sent by the module at any time | +IPD,28:Hello STM32, this is the PC | – |
AT+CIPCLOSE | Closes the connection | CLOSEDOK | 6 |
STM32 ESP8266 Troubleshooting
The ESP8266 doesn’t answer AT commands
Check, in this order: CH_PD (EN) is at 3.3V, TX and RX are crossed (STM32 TX to ESP8266 RX), the grounds are connected, and the baud rate matches (old firmware is often at 9600, and our driver tries the common rates by itself). Then test the module alone with a USB-TTL converter, as shown above. If its TX line stays low, the module isn’t running.
Garbage characters at power-up
The ESP8266 prints its boot log at 74880 baud on the same UART as the AT commands. Ignore everything until the module prints ready or answers AT. On the STM32 side, these bytes cause framing errors that stop the HAL’s DMA reception, which is why our driver restarts it in HAL_UART_ErrorCallback().
The module resets or disconnects during the WiFi join
That’s power. The ESP8266 draws about 300mA peaks when it transmits, and a weak 3.3V supply sags and resets it. On our breadboard, the 3.3V line dipped by 0.88V for 0.67ms with each transmission (see the scope capture above). Power the Blue Pill from USB (not from the ST-Link), keep the wires short, and add a 100µF capacitor across the module’s VCC and GND.
AT+CWJAP returns FAIL or ERROR
The reply +CWJAP:<code> tells you why: 1 = timeout, 2 = wrong password, 3 = network not found, 4 = connection failed. The ESP8266 is 2.4GHz only, so it can’t see a 5GHz network. Commas, double quotes, and backslashes in the SSID or password must be escaped with a backslash (our driver does it).
The reply is busy p…
It’s short for (busy processing…); the module is still working on the previous command (a join, a connection). Wait for its OK or ERROR before sending the next command. Our driver resends the command after 200ms, up to 25 times.
AT+PING or AT+UART_CUR returns ERROR
The module runs the old AT 0.2x firmware, which doesn’t have these commands. Check with AT+GMR and update the firmware if the flash size allows it.
esptool can’t connect, or the flash read fails
GPIO0 must be low while the module resets, and then the ROM bootloader answers at 115200 baud. Remove anything else on the TX and RX lines (the STM32, oscilloscope probes): we had corrupted flash reads with the scope probes still on the lines.
STM32 ESP8266 FAQ
Can the STM32 Blue Pill power the ESP8266?
Yes, from its 3.3V pin, as long as the Blue Pill itself is powered from its micro-USB port. Its regulator can supply the ESP8266’s transmit peaks. The ST-Link’s 3.3V output can’t, so don’t power the setup from the ST-Link alone.
Do I need a level shifter between the STM32 and the ESP8266?
No. Both run at 3.3V, so their UART pins connect directly.
What is the difference between the ESP-01 and the ESP-01S?
The ESP-01S has 1MB of flash (many older ESP-01 boards have 512KB), pull-up resistors on CH_PD, RST, and GPIO0, and a blue LED on GPIO2 instead of the TX pin. For the AT firmware in this tutorial, choose the ESP-01S or any module with 1MB or more.
What is the default baud rate of the ESP8266 AT firmware?
115200 baud for NonOS AT 1.x and ESP-AT 2.x. Many old AT 0.2x modules were set to 9600. The boot log is always at 74880 baud.
Should I use an ESP8266 or an ESP32-C3 with STM32?
For a new design, the ESP32-C3: it costs about the same, its AT port is separate from its boot log, and it gets the current ESP-AT releases. The ESP8266 is a good choice when you already have one. The same STM32 code and driver work with both, as we show in the ESP32 AT commands with STM32 tutorial.
Can I program the ESP8266 itself instead of using AT commands?
Yes. With the Arduino ESP8266 core or the ESP8266 SDK, the ESP8266 runs your own firmware, and the STM32 talks to it with your own protocol. We’ll do that in the WebSocket part of this series, where the ESP runs as a smart bridge.
STM32 WiFi Tutorial Series
This tutorial is the second part of our STM32 WiFi tutorial series. Each part builds one complete, tested project with an STM32 Blue Pill and an ESP WiFi module, using our ESP_AT driver:
| Part | Tutorial | What You’ll Build |
|---|---|---|
| 1 | STM32 WiFi | Choosing a WiFi module, quick start, ESP32-C3 vs ESP8266 measured |
| 2 | ESP8266 AT Commands With STM32 (this tutorial) | ESP8266 AT firmware, commands, and our ESP_AT driver |
| 3 | ESP32 AT Commands (ESP-AT) With STM32 | ESP-AT firmware, commands, SNTP time, and our ESP_AT driver |
| 4 | STM32 HTTP Client Over WiFi | GET, POST, HTTPS, and JSON parsing |
| 5 | STM32 Web Server | Control GPIOs and read sensors from a browser |
| 6 | STM32 MQTT | Publish and subscribe, Home Assistant |
| 7 | STM32 OTA Firmware Update | Update the STM32’s firmware over WiFi |
| 8 | STM32 WebSocket | Real-time data with an ESP32 smart bridge |
Download STM32 ESP8266 Example Projects + ESP_AT Driver
Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.
Wrap Up
To conclude this tutorial, we’ve used the ESP8266 AT commands with an STM32 Blue Pill to connect it to WiFi. We checked the module’s AT firmware, updated it to NonOS AT v1.7.6, configured the STM32 UART with circular DMA, and built three example projects with our ESP_AT driver: talking to the module, joining WiFi with automatic reconnection, and a TCP client that sends and receives data. The measurements showed why the firmware matters: the updated module sends the WiFi events, supports ping, and reaches 31.8KB/s at 921600 baud.
In the next part of this series, we’ll run the same driver and examples on an ESP32-C3 with the current ESP-AT firmware. If you’re new to the STM32 UART, the STM32 UART tutorial and the STM32 UART IDLE line detection tutorial are a good place to start.