How to effectively disable WiFi on ESP32: codes and methods

Microcontrollers of the family ESP32 Wireless modules have become the de facto standard for IoT devices due to their low cost and built-in wireless communication module. However, this module is the primary power consumer in the system, creating certain challenges when designing standalone, battery-powered devices. Many developers face the need to programmatically manage the radio module's state to extend battery life.

In this article, we will examine in detail the software methods for disabling the wireless interface at the kernel level. FreeRTOS and libraries Arduino CoreYou'll learn how to properly terminate connections, put the chip into deep sleep mode, and completely power off the RF unit. Understanding these processes is critical for creating energy-efficient solutions.

Improper WiFi state management can lead not only to rapid battery drain but also to unstable operation of the microcontroller itself due to voltage surges or task conflicts. We'll cover not only simple shutdown commands but also the nuances of working with RTC memory and timer interrupts. This will allow you to create reliable code that will run for years without human intervention.

Why do you need to disable WiFi programmatically?

The main reason why developers tend to turn off WiFi on ESP32 Immediately after data transmission, the radio module consumes a colossal amount of power. In active transmission mode, the current can reach 250 mA, while in deep sleep mode (Deep Sleep) consumption drops to microamps. If your device is battery-powered, constant operation of the radio interface will negate all the advantages of this architecture.

In addition to power saving, there are scenarios where temporarily freeing up processor resources or eliminating radio interference is necessary. For example, when working with sensitive analog sensors or ADCs, background WiFi processes can introduce noise or delays into interrupt processing. Disabling the module allows for the full allocation of processing power. CPU for critical real-time tasks.

Security scenarios should also be considered. If the device doesn't need to constantly scan the network or be visible to external clients, it's logical to keep the interface off most of the time, activating it only according to a schedule or external event. This reduces the attack surface and minimizes the risk of unauthorized access to your device.

⚠️ Caution: Frequent cycling of the WiFi module on and off (e.g., once per second) may cause the chip to overheat or the TCP/IP stack to become unstable. Always allow the system time to shut down processes gracefully before completely powering down the RF unit.

Basic shutdown via WiFi.off

The easiest and most obvious way to disable a wireless module in the Arduino IDE is to use the method WiFi.offThis command initiates a software shutdown of the radio interface, breaking existing connections and stopping background scanning processes. It's important to understand that after executing this command, the module stops consuming transmit current, but the microcontroller itself remains active.

For the code to work correctly, you must wait until the shutdown procedure is completed. Stack LwIP, used in ESP32, it takes time to close sockets and flush buffers. If you try immediately after the command WiFi.off If you go into sleep mode, the process may be interrupted incorrectly, which will lead to errors the next time you wake up.

Let's look at an example of code where we connect, send data, and then disable the module:


void loop {

if (needToSendData) {

WiFi.begin(ssid, password);

while (WiFi.status!= WL_CONNECTED) {

delay(500);

}

// Sending data...

sendDataToServer;

// Correct shutdown

WiFi.disconnect(true);

WiFi.mode(WIFI_OFF);

// Transition to sleep

esp_deep_sleep_start;

}

}

Usage WiFi.mode(WIFI_OFF) is a more reliable method, since it explicitly tells the driver to switch the radio module's operating mode to the "off" state. This ensures that no Station, no AP modes will not remain active in the background.

Why doesn't WiFi.off sometimes work the first time?

The WiFi.off function is asynchronous. If you call it and immediately move to the next line of code that performs heavy operations, the disconnection process may take a long time. It's recommended to add a small delay or check the connection status before going to bed.

ESP32 Power Saving Modes

Simply turning off WiFi is only half the battle. To maximize energy savings, the microcontroller ESP32 offers several sleep modes, each with its own characteristics and power consumption levels. Choosing the right mode depends on how quickly the device needs to respond to external events and which peripheral modules need to remain active.

Mode Modem Sleep Allows you to maintain a WiFi connection while the CPU is stopped. This is useful if the device needs to remain online but isn't actively computing. Power consumption is reduced, but only slightly compared to turning off the radio completely. In this mode Light Sleep The CPU is stopped, but RAM and registers are preserved, allowing immediate resumption of work. WiFi can also be disabled here for greater savings.

  • 🔋 Active Mode: Fully functional, WiFi enabled, consumption up to 240 mA.
  • 📉 Modem Sleep: WiFi is active, CPU is stopped, consumption is about 15-20 mA.
  • 🌙 Light Sleep: CPU stopped, context saved, WiFi off, consumption ~0.8 mA.
  • 💤 Deep Sleep: Only RTC is working, WiFi is off, consumption is ~10 µA (0.01 mA).

For devices that transmit data once an hour or less, the ideal choice is a combination of turning off WiFi completely and switching to Deep SleepIn this state, the chip can operate for years on a standard lithium battery. However, it's important to remember that waking from deep sleep involves a complete system reboot (except for the RTC memory), and WiFi must be re-initiated via software.

📊 What sleep pattern do you use most often?
Light Sleep
Deep Sleep
Modem Sleep
I don't use sleep

Comparison of radio module deactivation methods

There are many nuances to how we manage the state of a wireless interface. Different methods are suitable for different tasks: in some cases, you simply need to disconnect from the router, while in others, you need to completely power down the RF unit. Understanding the differences between disconnect, mode(WIFI_OFF) and system calls esp_wifi will help to avoid typical mistakes.

The table below compares the main commands and their impact on system state and power consumption. Please note that some commands require specific libraries or access rights to low-level functions.

Method / Team Impact on WiFi Consumption Recovery
WiFi.disconnect Breaks connection with AP High (module active) Instant
WiFi.mode(WIFI_OFF) Complete radio shutdown Low (RF off) Initialization required
esp_wifi_stop Stopping the WiFi driver Minimum Complex (requires restart)
esp_deep_sleep_start Disables everything except RTC Microamperes Resetting the chip

Using a low-level function esp_wifi_stop provides the most complete control, but requires caution. This function stops the WiFi task in the RTOS, which can lead to a system crash if other processes attempt to access the network. Therefore, for most Arduino applications, the combination WiFi.disconnect(true) And WiFi.mode(WIFI_OFF).

⚠️ Attention: Function esp_wifi_stop This function is part of the ESP-IDF and may conflict with higher-level Arduino abstractions if called at the wrong time in the loop. Use it only if you clearly understand the state of FreeRTOS tasks.

Entering Deep Sleep after Wi-Fi disconnection

The algorithm for maximizing power savings is always the same: collect data, enable WiFi, transmit, disable WiFi, and go into deep sleep. The key here is the order of actions. If you put your device to sleep without explicitly disabling WiFi, it may attempt to reconnect in the background, negating any energy savings.

To configure the wake-up timer, use the module esp_sleep_enable_timer_wakeupThis allows the device to "wake up" at a set interval, do its work, and go back to sleep. It is important to use RTC memory for storing counters or status flags, since regular RAM is cleared during deep sleep.


#include"esp_sleep.h"

#define uS_TO_S_FACTOR 1000000 / Microsecond to second conversion factor /

#define TIME_TO_SLEEP 60 / Sleep time in seconds /

void setup {

Serial.begin(115200);

// Operation logic

connectAndSendData;

// 1. Disable WiFi

WiFi.disconnect(true);

WiFi.mode(WIFI_OFF);

// 2. Setting up the wake-up timer

esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

Serial.println("Going into deep sleep...");

// 3. Fall asleep

esp_deep_sleep_start;

}

void loop {

// This code will not execute after sleep, because setup will start

}

When using esp_deep_sleep_start It is necessary to take into account that the next time the program is launched, it will start running from the beginning (functions setup). Therefore, your sketch logic should include a reset reason check to avoid performing unnecessary actions or resetting important data.

Common mistakes and troubleshooting

Even experienced developers often make mistakes when managing power. ESP32One of the most common problems is attempting to turn off WiFi while an active data transfer is in progress or the handshake with the router is incomplete. This causes the stack to freeze and requires a hard reset.

Another issue is related to power supply. When the WiFi module is turned on, it draws a peak current, which can cause voltage drops on cheap USB cables or weak power supplies. If you notice that the device reboots when connected to the network, try adding a large capacitor (10-47 µF) in parallel with the 3.3V and GND power contacts.

  • Ignoring statuses: Don't check WiFi.status Before shutting down, wait for the processes to complete.
  • Frequent stop/start: Do not turn off WiFi more often than once every few seconds, let the module cool down.
  • Interrupt Disable: Do not use delay In critical sections of code before going to bed, it is better to use timers.

If your device stops connecting to the network after several sleep/wake cycles, check if the heap memory is filling up. Memory leaks in WiFi libraries can accumulate if resources aren't properly freed before shutting down the module.

☑️ Checklist before going to bed

Completed: 0 / 4
Is it possible to turn off WiFi without entering Deep Sleep?

Yes, you can. Challenge WiFi.mode(WIFI_OFF) Disables the radio module, and power consumption drops from ~80-100 mA to ~10-20 mA (running CPU without WiFi). This is useful if the device needs to respond quickly to events but doesn't need WiFi right now.

Are WiFi settings reset after Deep Sleep?

Settings saved in NVS (Non-Volatile Storage) are retained. However, the WiFi module itself is disabled, and must be reactivated upon waking. WiFi.begin, if a connection is required. The connection is not automatically restored without an explicit call in the code.

Why does the ESP32 get hot when WiFi is disabled?

If WiFi is disabled by software, but the chip is still overheating, the processor may be running at maximum frequency or Bluetooth may be enabled. Check if this mode is still active. WIFI_AP or background scanning tasks. Heating can also be caused by a short circuit or a power supply issue.

How to completely power down ESP32?

It's impossible to completely power down the chip using software; it always draws current (microamps) in Deep Sleep mode. To completely power down the chip, you need to use an external power management circuit (such as a relay or MOSFET transistor), controlled by a timer or the microcontroller itself before sleep.

Does turning off WiFi affect Bluetooth performance?

Yes, it does. On the ESP32 chip, WiFi and Bluetooth share a radio module and antenna. WiFi.mode(WIFI_OFF) may not affect Bluetooth directly, but the function esp_wifi_stop Or entering deep sleep typically disables the entire RF unit, including BT. Independent control requires fine-tuning via the ESP-IDF.