ESP32 - Turn off and turn on the WIFI

Hello. It is this page (https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/) I am seeing everything that the ESP32 consumes. It says that without WIFI it consumes 20mA and with Wifi it consumes more than 160mA. My question is: how to turn off Wifi when I'm not connected to it and how to turn it on only when I'm connected?

My code is the following (it works perfectly, with the problem that it sends data even when it is not connected to anything, and that is a waste of energy):

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>


BLEServer *pServer = NULL;
BLECharacteristic *pCharacteristic;

bool deviceConnected = false;
bool oldDeviceConnected = false;

float data_0;
int data_1;
int battery;

const int LED = 2;
float txValue = 0;
const int readPin = 32; // Use GPIO number. See ESP32 board pinouts

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID_TX "beb5483e-36e1-4688-b7f5-ea07361b26a8"
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
      BLEDevice::startAdvertising();
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");

        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }

        Serial.println();

        // Do stuff based on the command received from the app
        if (rxValue.find("0") != -1) { 
          Serial.println("Turning ON!");
          digitalWrite(LED, HIGH);
        }
        else if (rxValue.find("1") != -1) {
          Serial.println("Turning OFF!");
          digitalWrite(LED, LOW);
        }

        Serial.println();
        Serial.println("*********");
      }
    }
};


void checkToReconnect() //added
{
  // disconnected so advertise
  if (!deviceConnected && oldDeviceConnected) {
    delay(500); // give the bluetooth stack the chance to get things ready
    pServer->startAdvertising(); // restart advertising
    Serial.println("Disconnected: start advertising");
    oldDeviceConnected = deviceConnected;
  }
  // connected so reset boolean control
  if (deviceConnected && !oldDeviceConnected) {
    // do stuff here on connecting
    Serial.println("Reconnected");
    oldDeviceConnected = deviceConnected;
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  
  // Create the BLE Device
  BLEDevice::init("Adam");

  // Create the BLE Server
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_TX,
                      BLECharacteristic::PROPERTY_NOTIFY
                    );

  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  // Create a BLE Descriptor
  pCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID_RX,
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {

    checkToReconnect();

    // notify changed value
    if (deviceConnected) {

      txValue = analogRead(readPin) / 3.456; // This could be an actual sensor reading!
      //convert float txvalue to string
      char data_0[8]; // make sure this is big enuffz
      dtostrf(txValue, 1, 2, data_0);

      data_1 = 1;
      battery = 49;

      String str = "";
      str += data_0;
      str += ",";
      str += data_1;
      str += ",";
      str += battery;
      
      pCharacteristic->setValue((char*)str.c_str());
      pCharacteristic->notify();

      Serial.println("*** Sent Value: ");
      Serial.println(data_0);
      Serial.println(data_1);
      Serial.println(battery);
      Serial.println(" ***");

      // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms
    }
    delay(500);
}

When the BT is off because it has lost connection what's the plan for checking to see if BT is available?

1 Like

I admit that I am not an expert, I seek help for that very reason.

The ESP32 connects and disconnects, but the BT is still on, isn't it? It still draws more than 160mA.

By definition, if you're connected, it's on. So what did you really mean?

1 Like

Do you want to de energize the WiFI module if so under what conditions do you want the WiFi module powered down?

Deepsleep will power the WiFi module off.

The ESP32 BT WiFi controller api, Controller && VHCI - ESP32 - — ESP-IDF Programming Guide latest documentation (espressif.com)

2 Likes

The BLE server/peripheral is always advertising itself. You can turn off the advertising, but then how will another device find it and connect with it?

1 Like

This is always the problem.

When you are in deep sleep to conserve power, there is no communication since the communication systems require (significant, even BLE) power to operate.

The only way around it is to periodically wake from sleep and turn on some communication for long enough for your other system - which is permanently powered and operating - to get in touch.

1 Like

I understand perfectly what they tell me. But, look at my code... when it's offline. Which of all modes is it in? How much are you consuming in theory?

1 or 2?



What do you mean by "when it is off line"?

If you load the BT library the Wi-Fi is on. You want Wi-Fi off, use the ESP32's API, see post#5, and turn off Wi-Fi. #1

If you put the ESP32 module to deep sleep, as per post#5, then WiFi is off. #2

If you just want to turn the WiFi off...

  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
1 Like

Why do you want to disconnect from Wi-Fi?

after turning off by this command how to turn it on again ?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.