ESP32 交替使用 BLE 和 WiFi

ESP32 using BLE and WiFi alternately

我有一个 ESP32,它应该通过 BLE 接收数据,然后通过 WiFi 将数据发送到网络服务器。如果我在 Arduino 中分别编写这两个任务,那么一切正常,但是一旦我合并这两个任务,通过 WiFi 发送就会崩溃。

据我了解,BLE 和 WiFi 在 ESP32 上共享同一个无线电,因此需要交替执行任务以避免干扰。我试图通过在两个任务之间添加延迟来实现这一点,但没有成功。

这是我目前的代码:

#include <HTTPClient.h>
#include <BLEDevice.h>
#include <BLEScan.h>

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

int scanTime = 2; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
    }
};

void setup()
{

  Serial.begin(115200);
  Serial.setDebugOutput(1);
  Serial.setDebugOutput(0); //turn off debut output

  WiFi.begin(ssid, password);
  int retrycon = 50;
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    if (--retrycon == 0)
    {
      Serial.println("RESTART");
      ESP.restart();
    }
    Serial.print(".");
  }
  Serial.print("WiFi connected with IP: ");
  Serial.println(WiFi.localIP());

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true);
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);
}

void loop()
{
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  pBLEScan->clearResults();

  delay(3000);

  int tryconnect = 20;
  while (--tryconnect != 0) {
    if (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.println("...");
    } else {
      break;
    }
  }
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.reconnect();
    Serial.println("reconnect");
  }
  else {
    Serial.println("connected to WiFi");

    HTTPClient http;
    http.begin("http://httpbin.org/ip");
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.print("HTTP code ");
      Serial.println(httpCode);
    } else {
      Serial.println("Error on HTTP request");
    }
    http.end();
    delay(10000);
  }
}

谁能告诉我如何实现这两个任务(通过 BLE 接收,通过 WiFi 发送)以避免干扰?

我使用这样的命令来关闭 BLE 和 WiFi:

  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
  btStop();
  adc_power_off();
  //esp_wifi_stop(); // Doesn't work for me!
  esp_bt_controller_disable();

在我的代码中,我使用 BLE advertize/scan,然后执行上述操作,然后连接到 WiFi。没问题。哦,当你完成 BLE 时记得 BLEDevice::deinit,否则你无法将它放入 4Mb ESP32。我做 BLE、WiFi、HTTPS/SSL、OTA 并使用 SPIFFS 存储数据,所有这些都在没有 PSRAM 的标准 4Mb ESP32 (ESP-WROOM-32) 上。

以上都是一个降低功耗的函数,所以我每次更改时都会调用它'mode'。在深度睡眠中我只使用 5uA。

还有:

pBLEScan->setInterval(100);
pBLEScan->setWindow(99);

...对我不起作用,所以我将它们注释掉,然后扫描 3 秒。