Integrating 1 Arduino Uno, 2 Bluetooth modules, 2 phones with one Blynk app interface

Hello Blynk community.

An update on my progress with regard to this issue. After a few more hours of research i came across a post on the Blynk forum which worked like a charm to sort out the issue of the compile error. Thank you at @BTT . For anyone else experiencing the same problem, here is the link:

I played around with these lines of code, added a small segment of code I read in another post, to achieve automatic WiFi network selection and the resulting code segment that I have developed thus far looks like this:

void SetupBlynkConnection(){

  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);
  Blynk.connectWiFi(ssid0, pass0);
  //Check if the first network is avaiable and connect
  if (Blynk.connectWiFi(ssid0, pass0)) {                                                    

    Serial.println("Attempting to connect to Wifi network 1");
    Blynk.connect(5000);
    Blynk.run();
    
  }
  //Check if second network is available and connect
  else if(!Blynk.connectWiFi(ssid0, pass0)){
    
    Serial.println("Wifi network 1 is not available so establishing connection to Wifi network 2");
    wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
    Blynk.config(wifi, auth, server, port);
    Blynk.connectWiFi(ssid1, pass1);
    Blynk.connect(5000);
    //Blynk.run();
    
    if(Blynk.connectWiFi(ssid1, pass1)){
      Serial.println("Connected to Blynk via Wifi network 2");
    }
    //if no networks are available then continue with rest of program
    else{

      Serial.println("No Wifi networks are avaialable for connection");
      
    }
  }
}

void CheckBlynkConnection(){
  
  Connected2Blynk = Blynk.connected();
  
  if(!Connected2Blynk){

     Serial.println("Blynk connection status: Disconnected\nAttempting to re-establish connection to Blynk...");
     SetupBlynkConnection();
     Blynk.connect(5000);
     Blynk.run();
     
  }
  else{
    
    Serial.println("Blynk connection status: Connected");     
 
  }
}

This segment of code is able to successfully detect and select the network to connect to. All this works great when the second network is available only this is not the case when the first network is available: the new challenge that i am facing is that when the first network is available the SetupBlynkConnection() subroutine executes as expected but when the CheckBlynkConnection() subroutines executes it achieves a disconnected status continuously. I am playing around with the lines of code still but can’t seem to definitively determine why this is happening. Any advice from the community would be greatly appreciated.

The code calles many functions unnecessarily and repetitively and creates those unwanted disconnections as you’re experiencing.

Try the following running code

bool SetupBlynkConnection()
{
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, cloudBlynkServer.c_str(), BLYNK_SERVER_HARDWARE_PORT);

  //Check if the first network is avaiable and connect
  if (Blynk.connectWiFi(ssid, pass)) 
  {                                                    
    Serial.println("Connected to primary Wifi network");    
  }
  //Check if second network is available and connect
  else
  {   
    Serial.println("Primary Wifi network not available, connecting to backup Wifi network");
    //wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
    //Blynk.config(wifi, auth, server, port);
    
    if (Blynk.connectWiFi(ssid1, pass1))
    {
      Serial.println("Connected to Blynk via backup Wifi network");
    }
    //if no networks are available then continue with rest of program
    else
    {
      Serial.println("No Wifi networks are avaialable for connection");     
      return false;
    }
  }
  return (Blynk.connect(5000));
}

void CheckBlynkConnection()
{ 
  if (!Blynk.connected())
  {

     Serial.println("Blynk connection status: Disconnected\nAttempting to re-establish connection to Blynk...");
     if ( SetupBlynkConnection() )
      Serial.println("Blynk connection status: OK...");
  }
}

#define NOT_USE_BLYNK_BEGIN   true

void setup()
{
  ...
  
  // Debug console
  Serial.begin(115200);
  delay(1000);
  Serial.println("\nStart Teensy4");

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  
  Serial.println("Start Blynk");

  #if USE_BLYNK_WM
    Blynk.begin(wifi);
  #else
    #if NOT_USE_BLYNK_BEGIN
      SetupBlynkConnection();
    #else
      //Blynk.begin(auth, wifi, ssid, pass);
      Blynk.begin(auth, wifi, ssid, pass, cloudBlynkServer.c_str(), BLYNK_SERVER_HARDWARE_PORT);
    #endif
  #endif
  
  timer.setInterval(30000L, CheckBlynkConnection);    // check every 30s if still connected to server
  ...
}

void loop()
{
  Blynk.run();
  timer.run();
}

and this is the debug terminal output (runningTeensy4 and ESP8266 shield)

Start Teensy4
Start Blynk
[1332] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Teensy

[1332] Connecting to HueNet1
[7948] AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK
[15641] IP = 192.168.2.107
+CIFSR:STAMAC,5c:cf:7f:66:05:d2
[15641] Connected to WiFi
Connected to primary Wifi network
[25790] Ready (ping: 22ms).
[26229] Time sync: OK
Blynk connection status: Disconnected                  <= remove router HueNet1
Attempting to re-establish connection to Blynk...      <=  Blynk loss
[62817] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Teensy

[62817] Connecting to HueNet1
[69433] AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK
[79996] Failed to connect WiFi
Primary Wifi network not available, connecting to backup Wifi network
[79996] Connecting to HueNet                              <= backup WiFi
[86614] AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK
[92303] IP = 192.168.2.107
+CIFSR:STAMAC,5c:cf:7f:66:05:d2
[92303] Connected to WiFi
Connected to Blynk via backup Wifi network          <= Backup WiFi reconnected
[102514] Ready (ping: 21ms).                        <= and Blynk reconnected OK

and the debug output when Primary AP is not available at the beginning

Start Teensy4
Start Blynk
[1332] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Teensy

[1332] Connecting to HueNet1
[7948] AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK
[18512] Failed to connect WiFi              <= failed to connect to primary AP
Primary Wifi network not available, connecting to backup Wifi network
[18512] Connecting to HueNet                <= connecting to backup AP
[25130] AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK
[30821] IP = 192.168.2.107
+CIFSR:STAMAC,5c:cf:7f:66:05:d2
[30821] Connected to WiFi                    <= connected to backup AP
Connected to Blynk via backup Wifi network   <= and Blynk
[41040] Ready (ping: 22ms).

Hello @khoih
Thank you very much for your advice and assistance. Your code was helpful, I found that this code runs much quicker to connect to one of my 2 WiFi networks, however I am having a few problems. I added the code segment you suggested as shown here:


bool SetupBlynkConnection()
{
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, 8080);

  //Check if the first network is available and connect
  if (Blynk.connectWiFi(ssid1, pass1)) 
  {                                                    
    Serial.println("Connected to primary Wifi network");    
  }
  //Check if second network is available and connect
  else
  {   
    Serial.println("Primary Wifi network not available, connecting to backup Wifi network");
    //wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
    //Blynk.config(wifi, auth, server, port);
    
    if (Blynk.connectWiFi(ssid0, pass0))
    {
      Serial.println("Connected to Blynk via backup Wifi network");
    }
    //if no networks are available then continue with rest of program
    else
    {
      Serial.println("No Wifi networks are available for connection");     
      return false;
    }
  }
  return (Blynk.connect(5000));
}

void CheckBlynkConnection()
{ 
  if (!Blynk.connected())
  {

     Serial.println("Blynk connection status: Disconnected\nAttempting to re-establish connection to Blynk...");
     if ( SetupBlynkConnection() )                                                                                    //
      Serial.println("Blynk connection status: OK...");
  }
}

#define NOT_USE_BLYNK_BEGIN   true

void setup()
{
  
  // Debug console
  Serial.begin(9600);
  delay(1000);
  Serial.println("\nStart Teensy4");

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  
  Serial.println("Start Blynk");

  #if USE_BLYNK_WM
    Blynk.begin(wifi);
  #else
    #if NOT_USE_BLYNK_BEGIN
      SetupBlynkConnection();
    #else
      //Blynk.begin(auth, wifi, ssid, pass);
      Blynk.begin(auth, wifi, ssid0, pass0, server, 8080);
    #endif
  #endif
  
  //timer.setInterval(30000L, CheckBlynkConnection);    // check every 30s if still connected to server
  

    FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  
  
  //Blynk.begin(auth, wifi, ssid0, pass0);
  //SetupBlynkConnection();

  Serial.println("WS2812 RGB LED strip test reconnecting to the wifi when disconnected: V3 (Running code provided by Blynk community member)");
  timer1.setInterval(300, MainFunction);
  
}

void loop()
{
  Blynk.run();
  timer1.run();
}


void MainFunction(){

  if(PresetLightSelection==1){

      PresetLightSettings();
        
  }
  
  BlynkCounter++;
  if(BlynkCounter==50){   //Check if Blynk is connected every 15 seconds approximately 

    Serial.println("Checking Blynk connection status...");
    CheckBlynkConnection();
    BlynkCounter=0;
    
  }
  
}

Here is the serial monitor output when the blynk print command is included in the sketch:

Start Teensy4
Start Blynk
[1045] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Arduino Mega

[19118] Connecting to NETWORK1
[20129] ESP is not responding
Primary Wifi network not available, connecting to backup Wifi network
[20667] Connecting to NETWORK2
[23844] AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
compile time:May 20 2016 15:08:19
OK
[29232] +CIFSR:STAIP,"192.168.43.102"
+CIFSR:STAMAC,"3c:71:bf:25:ef:e0"
[29243] Connected to WiFi
Connected to Blynk via backup Wifi network
WS2812 RGB LED strip test reconnecting to the wifi when disconnected: V3 (Running code provided by Blynk community member)
[40665] Ready (ping: 651ms).
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...

As you can see, the system never realizes that the connection between Blynk and my Esp Hardware has been established when one of the 2 WiFi networks are available. So even when the system does connect to Blynk, it never runs the through the code segment

 if ( SetupBlynkConnection() )
     Serial.println("Blynk connection status: OK..."); 

Situation 1:
If both networks are unavailable on startup then the program stalls after it completes the void setup subroutine (it prints the WS2812 RGB LED strip test reconnecting to the wifi when disconnected: V3 (Running code provided by Blynk community member) and stops running). If either of the 2 networks becomes available the program then unfreezes and connects to the available network.
Situation 2:
If both the network fails/unavailable after a connection was established then when either of the networks returns/available then the system still remains frozen. Here is the serial output for this situation:

Start Teensy4
Start Blynk
Primary Wifi network not available, connecting to backup Wifi network
No Wifi networks are available for connection
WS2812 RGB LED strip test reconnecting to the wifi when disconnected: V3 (Runing code provided by Blynk community member)
Checking Blynk connection status...
Blynk connection status: Disconnected    //Here is where it stalls under situation 1
Attempting to re-establish connection to Blynk...
Connected to primary Wifi network
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Checking Blynk connection status...
Blynk connection status: Disconnected
Attempting to re-establish connection to Blynk...
Primary Wifi network not available, connecting to backup Wifi network
No Wifi networks are available for connection   //Here is where it stalls under situation 2

I apologize for not mentioning this earlier but I need my program to run even when there is no Wifi network available and reconnect when there is 1 available. I am playing around with the commands now to see if sprinkling some Blynk.connect() and Blynk.run() here and there might resolve the issues.

The code is just doing what you ask it to do

  1. Every 15s, it’ll print Checking Blynk connection status... no matter what.
    It’s only expected to run the SetupBlynkConnection() only when Blynk connection is lost.
...
if (!Blynk.connected())
  {

     Serial.println("Blynk connection status: Disconnected\nAttempting to re-establish connection to Blynk...");
     if ( SetupBlynkConnection() )                                                                                    //
      Serial.println("Blynk connection status: OK...");
  }
...
if(BlynkCounter==50){   //Check if Blynk is connected every 15 seconds approximately 

    Serial.println("Checking Blynk connection status...");
    CheckBlynkConnection();
    BlynkCounter=0;
    
  }
...
  1. This blocking Blynk.run() has been discussed many times here in the forum.

You can avoid that by

void loop()
{
 if (Blynk.connected())
 {
    Blynk.run();
 }

  timer1.run();
}

Well than I don’t think that i am asking it correctly to do what I want because the program is stalling both with and without the Blynk.run() inside of the ‘if statement’. It is not running the SetupBlynkConnection() code segment. It is actually stalling the program for a short while before running this sub routine once and then it stalls completely. There is other programming code that I have implement which is commands sent from Blynk to switch on an LED strip. One of them alternates the LED’s colours and when the program stalls, the LEDs also freeze. This is not what we programmed it to do or at least not what i intended for it to do.

I have already tried placing the Blynk.run() inside of the ‘if statement’ the way you are suggesting but found that sometimes the hardware does not connect to Blynk at all this way.

You have to look at the blocking problem in your remaining hidden code, for example

if(PresetLightSelection==1){

      PresetLightSettings();
        
  }

Only you who hold the key and know where to find the bug. I’m afraid many people as well as I won’t have any more idea to share. That’s it.

You can also have a look at (for ESP8266 and ESP32)

Okay thanks for your advice and assistance @khoih, you gave a push in the right direction. I am currently using a method of elimination to detect where the culprit is that is causing the stalling.

As you know, WS2812 lib. is notoriously blocking and bad, yet not easily to be fixed. These links will help you start your research

https://forum.pjrc.com/threads/58838-Non-Blocking-WS2812-library-still-has-significant-delay
https://forum.pjrc.com/threads/58442-Non-Blocking-WS2812-LED-Library-and-Teensy-4-0
https://forum.pjrc.com/threads/58621-WS2812Serial-question-conflict-between-FastLED-and-Adafruit-NeoPixel-libraries
https://forum.pjrc.com/threads/57875-Teensy-4-0-and-FastLED

Good luck

I have isolated the WS2812 fastLED code segments and i still have the same problem: The code Blynk.connected() does not return a ‘connected’ indication when the Blynk.run() is placed within the ‘if statement’ code segment:

if(Blynk.connected()){
    Blynk.run();
}

So i concluded that the solution to the problem lies in altering the code responsible for the Blynk app to hardware connection. So just to be more explicit when my project is connected to a WiFi network that has access to the internet Blynk.connected() never achieves a positive result. It appears that a Blynk.run() is required to connect the app and hardware in the first place in order for the Blynk.connected() to result in a connected status. I am stuck in a vicious cycle and i have tried playing around with the code to break that cycle but i have been unsuccessful: I tried adding in a while loop and a counter to run the Blynk.run() command when the project connects to any available WiFi network:

bool SetupBlynkConnection()
{
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);

  //Check if the first network is available and connect
  if (Blynk.connectWiFi(ssid0, pass0)) 
  {                                                    
    Serial.println("Connected to primary Wifi network");    
    BlynkRunCounter=0;

    while(BlynkRunCounter<50){

      Blynk.run();
      Serial.println("BlynkRunCounter: ");
      Serial.println(BlynkRunCounter);
      BlynkRunCounter++;
    }
    
  }
  //Check if second network is available and connect
  else
  {   
    Serial.println("Primary Wifi network not available, connecting to backup Wifi network");

    Blynk.connect(2000);                                //Necessary in order to make the system connect to the second Wifi network
    
    if (Blynk.connectWiFi(ssid1, pass1))
    {
      Serial.println("Connected to Blynk via backup Wifi network");
      BlynkRunCounter=0;
      while(BlynkRunCounter<50){

        Blynk.run();
        Serial.println("BlynkRunCounter: ");
        Serial.println(BlynkRunCounter);
        BlynkRunCounter++;
      }
    
    }
    //if no networks are available then continue with rest of program
    else
    {
      Serial.println("No Wifi networks are available for connection");     
      return false;
    }
  }
  return (Blynk.connect(2000));
}

I am running out of ideas on how to break the viscous cycle. Did anyone experience a similar problem? Please, if anyone has any different approaches to try it would be really helpful.

I’m very new to Blynk but I’m using this code to scan for networks and connect to whichever one is available. It only checks at start up right now, but this could be checked anytime if needed. I can’t remember where I found this approach, but it’s working great. Maybe this approach is totally wrong, but I’m using Wemos D1 Mini Pro which uses the ESP8266 which I think is what you’re using. I’m not showing it here, but I also was able to find a serial number for each of five different Wemos D1 Mini Pro devices. Because I could identify which board my code was on, I could have one sketch downloaded to each device and the code could run differently based on which device was connected. Kind of fun. If the code shown below works for you, I can show you the additional program, but I removed it for clarity.


#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <WiFiClient.h>

char auth[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

char ssid1[] = "network1";  //home
char pass1[] = "xxxxxxxxxx";
char ssid2[] = "network2";  //work
char pass2[] = "xxxxxx";
char ssid3[] = "network3";  //cabin
char pass3[] = "xxxxxxxxxxxxxx";

BlynkTimer timer;

void mainLoop()
{
  //most of your code goes here
}

void setup() {
  Serial.begin(9600);
  int n = WiFi.scanNetworks(); // WiFi.scanNetworks will return the number of networks found
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      Serial.println("");
      //This is where I'll connect to which ever WiFi system is available
      if (WiFi.SSID(i).equals(ssid1)) {
        Blynk.begin(auth, ssid1, pass1);
      } else if (WiFi.SSID(i).equals(ssid2)) {
        Blynk.begin(auth, ssid2, pass2);
      } else if (WiFi.SSID(i).equals(ssid3)) {
        Blynk.begin(auth, ssid3, pass3);
      }
      delay(10);
    }
  }
  timer.setInterval(1000L, mainLoop);  //run every second
}

void loop()
{
  Blynk.run();
  timer.run();
}

Maybe reading the documentation would help…
https://docs.blynk.cc/#blynk-firmware-connection-management

NOTE: After Blynk.config(...) is called, your hardware is not yet connected to the server. It will try to connect while until it hits first instance of Blynk.run() or Blynk.connect() routine.
To skip connecting to the server or to disconnect manually, call Blynk.disconnect() after configuration.

The poor grammar in this statement is somewhat confusing, but I think it should say “It will not try to connect until it hits the first instance of Blynk.run() or until the Blynk.connect() routine is called.”

Pete.

Hello @PeteKnight.
Thanks but I have already read this extract of the documentation, I did not find particularly helpful in this situation. Maybe i over looked something? Please do tell if there is something specific that occurred to you when you read these lies that you thought would be helpful in my situation.

I tried a Blynk.connect() inside of the SetupBlynkConnection() previously but this not help. As long as the Blynk.run() remains inside of the if statement, a connected status indication is not being reached :confused:

Hello @docaberle. Thank you very much for sharing. I came across something like this as well. TI tried something similar but i am trying to avoid using blocking functions such as the Blynk.begin(). Its been documented, and tested, to prevent any code from executing until the project hardware connects to the Blynk server. My issue is that i would like my program to execute when no internet connection is available and reconnect when an internet connection becomes available.
Did you experience a situation when your project was running and none of your networks were available? what happens to your program when none of your networks are available?

In that case, you’re structuring your code incorrectly.
But, without knowing where these snippets of code fit into your larger overall picture its difficult to know how to advise.
You seemed to be saying that you’d discovered that “that a Blynk.run() is required to connect the app and hardware in the first place in order for the Blynk.connected() to result in a connected status”. This is partially true, but in my experience a Blynk.connect() immediately after the Blynk.config() is a better way to do it.

Also, I don’t use Blynk.connectWiFi but prefer to manage my own WiFi connection via WiFi.config and WiFi.begin. This is mostly because I assign static IP addresses to all if my devices and don’t always use Blynk, so it makes my code more universal if I call the underlying WiFi libraries rather than using the Blynk wrapper library for the WiFi connection.

Pete.

Wow, you’re absolutely right. If it cannot connect to a network nothing else happens after Blynk.begini. With the code below you’ll see only this in the monitor:

before
[71] Connecting to MyNetwork


void setup() {
  Serial.begin(9600);
  Serial.println("before");
  Blynk.begin(auth, ssid, pass);
  Serial.println("after");
  delay(10);
  timer.setInterval(1000L, mainLoop);
}

Too bad there wasn’t a timeout parameter from Blynk.begin that would bail out of the function if it couldn’t connect. The library could be modified, but that’s never fun and easy to overwrite.

You don’t need to - you use the non-blocking Blynk.config and Blynk.connect commands instead.

However, if you want to explore your issue further then please create a new topic about it, rather than hijacking this topic.

Pete,

Hello @PeteKnight
I say that the Blynk.run() is required because when testing my program i first tried to establish a connection with the server with a Blynk.connect() as shown in the 3 places labelled in the code segment to follow. I was surprised that the command in ‘Place 1’ did not result in a connection and tried the other places. Unfortunately In all 3 places the result of a Blynk.connected() would be negative (not connected). I have commented out FastLED code segments as I am first trying to establish a stable Blynk connection with my networks. To summarize, the following lines of code is what my firmware consists of:


bool SetupBlynkConnection()
{
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);
  //Blynk.connect(2000);  **//Place 1**
  
  //Check if the first network is available and connect
  if (Blynk.connectWiFi(ssid0, pass0)){

    //Blynk.connect(2000); **//Place 2**
    Serial.println("Connected to primary Wifi network");    
    BlynkRunCounter=0;

    /*while(BlynkRunCounter<50){

      Blynk.run();
      Serial.println("BlynkRunCounter: ");
      Serial.println(BlynkRunCounter);
      BlynkRunCounter++;
    }
    */
  }
  //Check if second network is available and connect
  else
  {   
    Serial.println("Primary Wifi network not available, connecting to backup Wifi network");
  
    Blynk.connect(2000);                                //Necessary in order to make the system connect to the second Wifi network
    
    if (Blynk.connectWiFi(ssid1, pass1))
    {
      Serial.println("Connected to Blynk via backup Wifi network");
      BlynkRunCounter=0;
     /* while(BlynkRunCounter<50){

        Blynk.run();
        Serial.println("BlynkRunCounter: ");
        Serial.println(BlynkRunCounter);
        BlynkRunCounter++;
      }*/
    
    }
    //if no networks are available then continue with rest of program
    else
    {
      Serial.println("No Wifi networks are available for connection");     
      return false;
    }
  }
  return (Blynk.connect(2000));
}

void CheckBlynkConnection()
{ 

  //Blynk.connect(2000);  **//Place 3**
  
  if (!Blynk.connected())
  {

     Serial.println("Blynk connection status: Disconnected\nAttempting to re-establish connection to Blynk...");
     if ( SetupBlynkConnection() )                                                                                    //
     Serial.println("Blynk connection status: Reconnected");
  }
  else if(Blynk.connected()){

    Serial.println("Blynk connection status: Connected");
    
  }
}

#define NOT_USE_BLYNK_BEGIN   true

void setup()
{
  
  // Debug console
  Serial.begin(9600);
  delay(1000);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  //To test if the code is blocked or not. pin 12 switches on an LED when pin 11 goes to ground
  pinMode(12, OUTPUT);
  pinMode(11,INPUT_PULLUP);
  Serial.println("Establishing WiFi and Blynk connections...");

  #if USE_BLYNK_WM
    Blynk.begin(wifi);
  #else
    #if NOT_USE_BLYNK_BEGIN
      SetupBlynkConnection();
    #else
      //Blynk.begin(auth, wifi, ssid, pass);
      Blynk.begin(auth, wifi, ssid0, pass0, server, 8080);
    #endif
  #endif

  Serial.println("WS2812 RGB LED strip test reconnecting to the wifi when disconnected: \nV3 (Running code adapted from Blynk community member)");
  timer1.setInterval(300, MainFunction);
  
}


void loop()
{

  if(Blynk.connected()){
    Blynk.run();
  }
  
  timer1.run();
  
}


void MainFunction(){
 
    BlynkCounter++;
    if(BlynkCounter==100){   //100 for 30 seconds
  
      Serial.println("Checking Blynk connection status...");
      CheckBlynkConnection();
      BlynkCounter=0;
      
    }
  
  if(digitalRead(11)==LOW){

    digitalWrite(12,HIGH);
    Serial.println("LED switched ON");
    
  }
  else{

    digitalWrite(12,LOW);
    
  }
  
}

I don’t seem to be having an issue connecting to a WiFi network because the command Blynk.connectWiFi() does achieve a positive result when a WiFi network is available. But i will also look into this and see if somehow solves my problem. Thanks Pete

How do you imagine that the device will connect to the Blynk server when you’ve not yet established a Wi-Fi connection?

Pete.

I am sorry Pete i meant i was surprised about ‘Place 2’.

I was just trying the Blynk.connect() in “Place 1” since it seemed that it was necessary for a connection to occur as shown in the quote above.

I continued testing by implementing the following code and noticed something strange on the serial monitor:

bool SetupBlynkConnection()
{
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);
  
  //Check if the first network is available and connect
  if (Blynk.connectWiFi(ssid0, pass0)){

    Blynk.connect(2000); //Place 2
    Serial.println("Connected to primary Wifi network");    
    BlynkRunCounter=0;

    while(!Blynk.connected()){
      
      Blynk.run();
      Serial.println("BlynkRunCounter: ");
      Serial.println(BlynkRunCounter);
      BlynkRunCounter++;

      if(Blynk.connected()){

        Serial.println("Blynk is connected");
   
      }
      
    }
    
  }
  //Check if second network is available and connect
  else
  {   
    Serial.println("Primary Wifi network not available, connecting to backup Wifi network");
 
    Blynk.connect(2000);                                //Necessary in order to make the system connect to the second Wifi network
    
    if (Blynk.connectWiFi(ssid1, pass1))
    {
      Serial.println("Connected to Blynk via backup Wifi network");
      BlynkRunCounter=0;
     /* while(BlynkRunCounter<50){

        Blynk.run();
        Serial.println("BlynkRunCounter: ");
        Serial.println(BlynkRunCounter);
        BlynkRunCounter++;
      }*/
    
    }
    //if no networks are available then continue with rest of program
    else
    {
      Serial.println("No Wifi networks are available for connection");     
      return false;
    }
  }
  return (Blynk.connect(2000));
}

void loop()
{
   
  if(Blynk.connected()){
    Blynk.run();
    Serial.println("Blynk.run() is running");
  }
  
  timer1.run();
  
}

Serial monitor output:

Establishing WiFi and Blynk connections...
Connected to primary Wifi network
BlynkRunCounter: 
0
BlynkRunCounter: 
1
BlynkRunCounter: 
2
BlynkRunCounter: 
3
BlynkRunCounter: 
4
BlynkRunCounter: 
5
BlynkRunCounter: 
6
BlynkRunCounter: 
7
BlynkRunCounter: 
8
BlynkRunCounter: 
9
BlynkRunCounter: 
10
BlynkRunCounter: 
11
BlynkRunCounter: 
12
BlynkRunCounter: 
13
BlynkRunCounter: 
14
BlynkRunCounter: 
15
BlynkRunCounter: 
16
BlynkRunCounter: 
17
BlynkRunCounter: 
18
BlynkRunCounter: 
19
BlynkRunCounter: 
20
BlynkRunCounter: 
21
BlynkRunCounter: 
22
BlynkRunCounter: 
23
BlynkRunCounter: 
24
BlynkRunCounter: 
25
BlynkRunCounter: 
26
Blynk is connected
Test reconnecting to the wifi when disconnected: 
V3 (Running code adapted from Blynk community member)
//The Blynk.run() in the void loop does not execute//
Checking Blynk connection status...
Blynk connection status: Disconnected

I force a connection with the Blynk server using the while loop which is evident by the fact that the serial monitor prints Blynk is connected which is governed by the ‘If’ statement within the while loop but for some reason the connection then breaks almost immediately becuase the ‘If’ statement governing the Blynk.run in the void loop() never executes. There is no additional code from other libraries or other programming code so I can’t understand why the connection is broken. :confused:

Hello Blynk community
I am trying a different approach. I would like to scan available WiFi networks and if one network matches one of the hardcoded networks then a Wifi connection followed by a Blynk connection must be executed. I looked through the web and through this forum but could not find something that worked the way I needed. My internet searches only indicated code when an esp8266 is used as a stand alone controller or is interfaced with an arduino uno, either case the code would not run on the IDE with the controller selected as the arduino uno. I did come across something on the blynk forum here which was posted by tbdltee:

  String APlist = wifi.getAPList();
  Serial.print ("AP List:");
  Serial.println (APlist);

But this concatenates and prints the combined list of wifi networks in the vicinity. I am looking for a way to test each individual scanned wifi ssid against the my hardcoded ones. Can someone please advise what is the best way to do this.