Cannot use Wifi after using bluetooth

Hi all,

I am using an arduino mkr 1010 and my project is to create a device that can be controlled through a website. I am using the WiFiNINA and ArduinoBLE libraries.

The first time the Arduino runs it should go into "setup mode" where it uses Bluetooth and waits for a connection from my website. Afterward, whenever the device is started up again it will just automatically connect to the wifi. On my website, I type in the SSID and password that I want the device to connect to. I am storing the data with the library FlashStorage. It all works until I try to run wifi.begin() after exiting setup mode which just causes my program to freeze. The Arduino will connect to wifi if the device is started up again so my assumption is that it doesn't work if wifi and Bluetooth are both activated. So my question is, is there a way to communicate over wifi after using Bluetooth? Not simultaneously, but one after another. I have tried running BLE.disconnect(), BLE.stopAdvertise(), and BLE.end() before calling wifi.begin() but it still doesn't work.

Start by posting your code using code tags </>


 Device = flash_dev_info.read();
  
  //check to see if there is any stored information
  if(Device.valid == false) {
    bluetoothDeviceSetup();
  }

  Serial.println("Connecting to wifi...");

  int connectionAttempts = 0;
  
  while (status != WL_CONNECTED) {
    if (connectionAttempts == 2) {
      bluetoothDeviceSetup();
      connectionAttempts = 0;
    }
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(Device.wifi_ssid);

    status = WiFi.begin(Device.wifi_ssid, Device.wifi_pass);


    // wait 10 seconds for connection:
    delay(5000);
    connectionAttempts++;
  }

  Serial.println("Connected to wifi");
void bluetoothDeviceSetup() {
  //get list of all wifi networks
    Serial.println("Setup Mode Active");
    Serial.println("Scanning available networks...");
    int numSSIDs = WiFi.scanNetworks();
    int availSSIDsChar = MAX_SSID_LENGTH * MAX_SSID_LENGTH +   MAX_SSID_LENGTH;
    char availSSIDs[MAX_SSID_LENGTH * MAX_SSID_LENGTH + MAX_SSID_LENGTH];
    if (numSSIDs == -1) {
      Serial.println("Couldn't get a WiFi connection");
      while (true);
    }
    int charCount = 0;
    for (int i = 0; i < numSSIDs; i++) {
      if (charCount + strlen(WiFi.SSID(i)) >= availSSIDsChar) {
        break; 
      }
      int currCharCount = charCount;
      for (int j = 0; j < strlen(WiFi.SSID(i)); j++) {
        availSSIDs[currCharCount + j] = WiFi.SSID(i)[j];
        charCount++;
      }
      availSSIDs[charCount] = '+';
      charCount++;
    }
    availSSIDs[charCount] = '\0';
    Serial.println(availSSIDs);
    
    //start bluetooth connection
    Serial.println("Initializing Bluetooth");

    //check to see if bluetooth fails
    if (!BLE.begin()){
      Serial.println("Bluetooth Low Energy Failed");
      while(1);
    }

    //localname for peripheral
    BLE.setLocalName(DEVICE_DEFAULT_NAME);
    //Set UUID for the service this device provides
    BLE.setAdvertisedService(wifiInit);

    //characteristics for the service
    wifiInit.addCharacteristic(devNAME);
    wifiInit.addCharacteristic(wifiSSID);
    wifiInit.addCharacteristic(wifiPASS);
    wifiInit.addCharacteristic(availNetworks);

    //add the service
    BLE.addService(wifiInit);
    BLE.setEventHandler(BLEConnected, bleConnectHandler);
    BLE.setEventHandler(BLEDisconnected, bleDisconnectHandler);

    devNAME.setEventHandler(BLEWritten, devNAMEWrite);    
    wifiSSID.setEventHandler(BLEWritten, wifiSSIDWrite);
    wifiPASS.setEventHandler(BLEWritten,  wifiPASSWrite);   
  
    devNAME.setValue(DEVICE_DEFAULT_NAME);
    wifiSSID.setValue(DEVICE_DEFAULT_NAME);
    wifiPASS.setValue(DEVICE_DEFAULT_NAME);
    availNetworks.setValue(availSSIDs);

    //bluetooth connecting led animation
    bluetoothConnecting();
    
    //advertise bluetooth
    BLE.advertise();

    Serial.println("Bluetooth® device active, waiting for connections...");
    
    //wifi initialization loop
    while(!devNameWritten || !wifiSSIDWritten || !wifiPASSWritten) {
      //poll though handlers
      BLE.poll(1000);
      //check to see if there is a connection
    }
    Serial.println("Completed Setup");
    Device.valid = true;
    flash_dev_info.write(Device);
    Serial.println("Device Information Written");
    BLE.disconnect();
    delay(500);
    BLE.stopAdvertise();
    delay(500);
    BLE.end();
}

Is this your complete code?

No, the rest are just global variables and other functions that currently aren't in use to light up an led strip. I just sent that because the code is very long as of right now but here is everything.

#include <WiFiNINA.h>
#include <ArduinoBLE.h>
#include <Adafruit_NeoPixel.h>
#include <FlashStorage.h>
#ifdef __AVR__
 #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
#include "Global_vars.h"

//flash stored values
typedef struct {
  boolean valid;
  char dev_name[MAX_DEVICE_NAME];
  char wifi_ssid[MAX_SSID_LENGTH];
  char wifi_pass[MAX_PASS_LENGTH];
}DeviceInfo;

FlashStorage(flash_dev_info, DeviceInfo); 

//specify Struct variable
DeviceInfo Device;
boolean devNameRan = false;
boolean wifiSSIDRan = false;
boolean wifiPASSRan = false;
boolean devNameWritten = false;
boolean wifiSSIDWritten = false;
boolean wifiPASSWritten = false;

//Global wifi declarations
int status = WL_IDLE_STATUS;

//Global Bluetooth declarations
BLEService wifiInit("bcc98c51-d166-4ae2-80d6-65cd104db0bd");
BLECharacteristic devNAME("bcc98c52-d166-4ae2-80d6-65cd104db0bd", BLERead | BLEWrite | BLENotify, MAX_DEVICE_NAME);
BLECharacteristic wifiSSID("bcc98c53-d166-4ae2-80d6-65cd104db0bd", BLEWrite | BLEIndicate, MAX_SSID_LENGTH);
BLECharacteristic wifiPASS("bcc98c54-d166-4ae2-80d6-65cd104db0bd", BLEWrite | BLEIndicate, MAX_PASS_LENGTH);
BLECharacteristic availNetworks("bcc98c55-d166-4ae2-80d6-65cd104db0bd", BLERead, (MAX_SSID_LENGTH * MAX_SSID_LENGTH) + MAX_SSID_LENGTH);

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

int currTime = millis();
int prevTime = currTime;

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println("Starting...");

  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
    clock_prescale_set(clock_div_1);
  #endif
  strip.begin(); 
  strip.show();
  strip.setBrightness(255);
  
  Device = flash_dev_info.read();
  
  //check to see if there is any stored information
  if(Device.valid == false) {
    bluetoothDeviceSetup();
  }

  Serial.println("Connecting to wifi...");

  int connectionAttempts = 0;
  
  while (status != WL_CONNECTED) {
    if (connectionAttempts == 2) {
      bluetoothDeviceSetup();
      connectionAttempts = 0;
    }
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(Device.wifi_ssid);

    status = WiFi.begin(Device.wifi_ssid, Device.wifi_pass);


    // wait 10 seconds for connection:
    delay(5000);
    connectionAttempts++;
  }

  Serial.println("Connected to wifi");
  
}

void loop() {
  // put your main code here, to run repeatedly:
}

void bleConnectHandler(BLEDevice central) {
  // central connected event handler
  Serial.print("Connected event, central: ");
  Serial.println(central.address());
}

void bleDisconnectHandler(BLEDevice central) {
  // central disconnected event handler
  Serial.print("Disconnected event, central: ");
  Serial.println(central.address());
}

void devNAMEWrite(BLEDevice central, BLECharacteristic characteristic) {
  char *rec = (char*) malloc(sizeof(characteristic.value()));
  memset(rec, 0, sizeof(rec));
  characteristic.readValue(rec, MAX_DEVICE_NAME);
  char *recFormatted = (char*) malloc(strlen(rec));
  memset(recFormatted, 0, sizeof(recFormatted));
  strcpy(recFormatted, rec);
  Serial.print("Characteristic event: devNAME = ");
  Serial.println(recFormatted);
  free(rec);
  if (devNameRan) {
    strcpy(Device.dev_name, recFormatted);
    devNameWritten = true;
  }
  else {
    devNameRan = true;
  }
}


void wifiSSIDWrite(BLEDevice central, BLECharacteristic characteristic) {
  char *rec = (char*) malloc(sizeof(characteristic.value()));
  memset(rec, 0, sizeof(rec));
  characteristic.readValue(rec, MAX_SSID_LENGTH);
  char *recFormatted = (char*) malloc(strlen(rec));
  memset(recFormatted, 0, sizeof(recFormatted));
  strcpy(recFormatted, rec);
  Serial.print("Characteristic event: wifiSSID = ");
  Serial.println(recFormatted);
  free(rec);
  free(recFormatted);
  if (wifiSSIDRan) {
    strcpy(Device.wifi_ssid, recFormatted);
    wifiSSIDWritten = true;
  }
  else {
    wifiSSIDRan = true;
  }
}

  
void wifiPASSWrite(BLEDevice central, BLECharacteristic characteristic) {
  char *rec = (char*) malloc(sizeof(characteristic.value()));
  memset(rec, 0, sizeof(rec));
  characteristic.readValue(rec, MAX_PASS_LENGTH);
  char *recFormatted = (char*) malloc(strlen(rec));
  memset(recFormatted, 0, sizeof(recFormatted));
  strcpy(recFormatted, rec);
  Serial.print("Characteristic event: wifiPASS = ");
  Serial.println(recFormatted);
  free(rec);
  free(recFormatted);
  if (wifiPASSRan) {
    strcpy(Device.wifi_pass, recFormatted);
    wifiPASSWritten = true;
  }
  else {
    wifiPASSRan = true;
  }
}

void bluetoothDeviceSetup() {
  //get list of all wifi networks
    Serial.println("Setup Mode Active");
    Serial.println("Scanning available networks...");
    int numSSIDs = WiFi.scanNetworks();
    int availSSIDsChar = MAX_SSID_LENGTH * MAX_SSID_LENGTH +   MAX_SSID_LENGTH;
    char availSSIDs[MAX_SSID_LENGTH * MAX_SSID_LENGTH + MAX_SSID_LENGTH];
    if (numSSIDs == -1) {
      Serial.println("Couldn't get a WiFi connection");
      while (true);
    }
    int charCount = 0;
    for (int i = 0; i < numSSIDs; i++) {
      if (charCount + strlen(WiFi.SSID(i)) >= availSSIDsChar) {
        break; 
      }
      int currCharCount = charCount;
      for (int j = 0; j < strlen(WiFi.SSID(i)); j++) {
        availSSIDs[currCharCount + j] = WiFi.SSID(i)[j];
        charCount++;
      }
      availSSIDs[charCount] = '+';
      charCount++;
    }
    availSSIDs[charCount] = '\0';
    Serial.println(availSSIDs);
    
    //start bluetooth connection
    Serial.println("Initializing Bluetooth");

    //check to see if bluetooth fails
    if (!BLE.begin()){
      Serial.println("Bluetooth Low Energy Failed");
      while(1);
    }

    //localname for peripheral
    BLE.setLocalName(DEVICE_DEFAULT_NAME);
    //Set UUID for the service this device provides
    BLE.setAdvertisedService(wifiInit);

    //characteristics for the service
    wifiInit.addCharacteristic(devNAME);
    wifiInit.addCharacteristic(wifiSSID);
    wifiInit.addCharacteristic(wifiPASS);
    wifiInit.addCharacteristic(availNetworks);

    //add the service
    BLE.addService(wifiInit);
    BLE.setEventHandler(BLEConnected, bleConnectHandler);
    BLE.setEventHandler(BLEDisconnected, bleDisconnectHandler);

    devNAME.setEventHandler(BLEWritten, devNAMEWrite);    
    wifiSSID.setEventHandler(BLEWritten, wifiSSIDWrite);
    wifiPASS.setEventHandler(BLEWritten,  wifiPASSWrite);   
  
    devNAME.setValue(DEVICE_DEFAULT_NAME);
    wifiSSID.setValue(DEVICE_DEFAULT_NAME);
    wifiPASS.setValue(DEVICE_DEFAULT_NAME);
    availNetworks.setValue(availSSIDs);

    //bluetooth connecting led animation
    bluetoothConnecting();
    
    //advertise bluetooth
    BLE.advertise();

    Serial.println("Bluetooth® device active, waiting for connections...");
    
    //wifi initialization loop
    while(!devNameWritten || !wifiSSIDWritten || !wifiPASSWritten) {
      //poll though handlers
      BLE.poll(1000);
      //check to see if there is a connection
    }
    Serial.println("Completed Setup");
    Device.valid = true;
    flash_dev_info.write(Device);
    Serial.println("Device Information Written");
    BLE.disconnect();
    delay(500);
    BLE.stopAdvertise();
    delay(500);
    BLE.end();
}

void bluetoothConnecting() {
  int animTime = 2000;
  int animInterval = 20;
  int flowLen = 5;
  for (float t = 0; t <= animTime; t = t + animInterval) {
    float animCompletion = t / animTime;
    float pos = (float) LED_COUNT * ease_in_out(animCompletion); 
    for (int i = 0; i <= flowLen; i++) {
      strip.setPixelColor((int)pos - i, strip.Color(0, 0, 255));
    }
    strip.show();
    delay(animInterval);
  }
}

void bluetoothConnected() {
 
}

float ease_in_out(float t) {
  return t * t * (3.0f - 2.0f * t);
}


Cool, that's one of the first things most anyone on here will ask you to do before they can try to help.

1 Like

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