Bluetooht switch Wifi

Hi I use ESP32, my target if Bluetooht is connected then stay on it if not then connect WiFi, and I can't fix my code, please help, I'm lost in the code :frowning:

#include "BluetoothSerial.h"
#include <WiFi.h>


const char* ssid = "TEST";
const char* password = "*****";

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param){
  if(event == ESP_SPP_SRV_OPEN_EVT){
    Serial.println("Client Connected");
    
  }

  if(event == ESP_SPP_CLOSE_EVT ){
    Serial.println("Client disconnected");
  }
}

void setup() {
  Serial.begin(9600);
  delay(5000);
  SerialBT.begin("ESP32");
  Serial.println("Bluetooth initialized");
  
  SerialBT.register_callback(callback);
  const char data = SerialBT.read("Client Connected");

  
  delay(5000);
  
  switch (data) {
    case 1: Serial.println("Client Connected");
    break;
  
    default: Serial.println("");{
    WiFi.begin(ssid, password);{
    while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
    }
    
  }
    break;
  
}
}
void loop() {}

"lost in the code" is a very unspecific saying.

There is a demo-code WiFiBlueToothSwitch.ino

...arduino1.8.13\hardware\espressif\ESP32\libraries\WiFi\examples\WiFiBlueToothSwitch\WiFiBlueToothSwitch.ino

to get helpful answers you should describe your whole project.
best regards Stefan

You are making this more complicated than necessary, and your use of the ESP_SPP_CLOSE_EVT callback is wrong.

There is a BluetoothSerial.h library function .connected() which you can use.

#include "BluetoothSerial.h"
#include <WiFi.h>


const char* ssid = "TEST";
const char* password = "*****";

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(9600);
  delay(5000);
  SerialBT.begin("ESP32");
  Serial.println("Bluetooth initialized");
  Serial.println("Five seconds to connect BT before switching to WiFi");

  delay(5000);

  if (SerialBT.connected())
  {
    Serial.println("Bluetooth Connected");
  }

  else
  {
    Serial.println("No Bluetooth Connection");
    SerialBT.end();
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.println("Connecting to WiFi...");
    }
  }
}
void loop() {}

Thanks a lot @cattledog It helped me a lot.
More people like you who do, not talk, note reason. :slight_smile: