Nano 33 Wifi http connection issues

Hi,
Basically my issue is WIFI keeps disconnecting or not able to connect in the beginning at all.
I am using nano iot 33 with a BOON netstick which works all the time(can see other device connected continuously).
I saw there is a long post about disconnecting WIFI issues and I am running into them myself, but didn’t understand what is the basic reset that needs to be done(without MQQT protocol) programmably in order to re-connect.
Thanks!

My code:

#include <SPI.h>
#include <WiFiNINA.h>
#include <Adafruit_SHT31.h>
#include <Wire.h>
#include <Digital_Light_TSL2561.h>
#include "arduino_secrets.h" 

String deviceID;
String macStr;
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;
byte mac[6];

Adafruit_SHT31 sht31 = Adafruit_SHT31();

#define SMAPIN A0
#define SMBPIN A2

const char WEBSITE[] = "api.pushingbox.com"; //pushingbox API server
const String devid = "v387AFB20A3CADC6"; //device ID on Pushingbox for our Scenario

unsigned long lastConnectionTime = 0;            // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000; // delay between updates, in milliseconds

String readString;
float humidity;
float temperature;
float weight;
int light;
int smA;
int smB;

void setup() {
 //Initialize serial and wait for port to open:
 Serial.begin(9600);
 delay(5000);
 Serial1.begin(9600);

 wifiSetup();

 sensorsSetup();

}

void loop() {
 wifiHandler();
 getTemperatureHumidity();
 getWeight();
 getSm();
 getLight();

 if (millis() - lastConnectionTime > postingInterval) {
   httpRequest();
 }

}

// this method makes a HTTP connection to the server:
void httpRequest() {
 // close any connection before send a new request.
 // This will free the socket on the Nina module
 client.stop();

 // if there's a successful connection:
 if (client.connect(WEBSITE, 80)) {
   Serial.println("connecting...");
   // send the HTTP PUT request:
   client.print("GET /pushingbox?devid=" + devid
      + "&deviceID=" + (String) deviceID
      + "&humidity=" + (String) humidity
      + "&temperature="      + (String) temperature
      + "&light="      + (String) light
      + "&weight="      + String(weight, 3)
      + "&smA="      + (String) smA
      + "&smB="      + (String) smB
        );

     // HTTP 1.1 provides a persistent connection, allowing batched requests
     // or pipelined to an output buffer
     client.println(" HTTP/1.1"); 
     client.print("Host: ");
     client.println(WEBSITE);
   client.println("User-Agent: ArduinoWiFi/1.1");
   client.println("Connection: close");
   client.println();
   Serial.println("Sent data");
   // note the time that the connection was made:
   lastConnectionTime = millis();
 } else {
   // if you couldn't make a connection:
   Serial.println("connection failed");
   status = WL_IDLE_STATUS;
   WiFi.disconnect();
   WiFi.end();
 }
}


void getTemperatureHumidity() {
 temperature = sht31.readTemperature();
 humidity = sht31.readHumidity();
}


void getWeight() {
  while (Serial1.available())
 {
   char c = Serial1.read();  //gets one byte from serial buffer
   readString += c; //makes the String readString
   delay(2);  //slow looping to allow buffer to fill with next character
   if (c == 'g' ) {
     int strLen =  readString.length(); 
     
     //Serial.print("strlen: ");Serial.println(strLen);
     //Serial.print("readString: ");Serial.println(readString);

     if (strLen == 12) { //DEBORAH
       weight = readString.substring(5,10).toFloat();
     }
     else if (strLen == 19) {
       if (readString.charAt(6) == 'N') { // NINA
         weight = readString.substring(11,17).toFloat();
         weight /= 1000;
       }
       else { //PETER
         weight = readString.substring(10,16).toFloat(); 
       }  
     }
     readString = "";
   }
   //Serial.print("weight: "); Serial.println(weight,3);

 }
}

void getSm() {
 smA=analogRead(SMAPIN);
 smB=analogRead(SMBPIN);
}

void getLight() {
 light = TSL2561.readVisibleLux();
}

void sensorsSetup(){
   setupLight();
   sht31_setup();
}


void setupLight(){
 Wire.begin();
 TSL2561.init();
}


void sht31_setup(){
 if (! sht31.begin(0x44)) {   // Set to 0x45 for alternate i2c addr
   Serial.println("Couldn't find SHT31");
 }
}

void wifiSetup() {
 // check for the WiFi module:
 if (WiFi.status() == WL_NO_MODULE) {
   Serial.println("Communication with WiFi module failed!");
   // don't continue
   while (true);
 }

 String fv = WiFi.firmwareVersion();
 if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
   Serial.println("Please upgrade the firmware");
 }

 // attempt to connect to Wifi network:
 while (status != WL_CONNECTED) {
   Serial.print("Attempting to connect to SSID: ");
   Serial.println(ssid);
   // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
   status = WiFi.begin(ssid, pass);

   // wait 10 seconds for connection:
   delay(10000);
 }
 // you're connected now, so print out the status:
 printWifiStatus();

}

void wifiHandler(){
 while (status != WL_CONNECTED) {
   Serial.print("Attempting to reconnect to SSID: ");
   Serial.println(ssid);
   // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
   status = WiFi.begin(ssid, pass);

   // wait 10 seconds for connection:
   delay(10000);
 }
}

void printWifiStatus() {
 // print the SSID of the network you're attached to:
 Serial.print("SSID: ");
 Serial.println(WiFi.SSID());

 // print your board's IP address:
 IPAddress ip = WiFi.localIP();
 Serial.print("IP Address: ");
 Serial.println(ip);

 // print the received signal strength:
 long rssi = WiFi.RSSI();
 Serial.print("signal strength (RSSI):");
 Serial.print(rssi);
 Serial.println(" dBm");
 
 
 WiFi.macAddress(mac);
 String mac0,mac1,mac2,mac3,mac4,mac5;
 mac0 = String(mac[0],HEX);
 mac1 = String(mac[1],HEX);
 mac2 = String(mac[2],HEX);
 mac3 = String(mac[3],HEX);
 mac4 = String(mac[4],HEX);
 mac5 = String(mac[5],HEX);
 deviceID = String(mac5 + ":" + mac4 + ":" + mac3 + ":" + mac2 + ":" + mac1 + ":" + mac0);
 Serial.print("mac address: "); Serial.println(deviceID);
}

Could you please modify your post and use code tags to place your code in a nice box? It should look like this

Your source code

I had a look at your code an noted the following:

  • you have wifiSetup and wifiHandler, both try to get a wifi connection working. I would recommend you remove wifiSetup from setup and handle this in a single task in the loop.

  • you handle wifi in httpRequest as well, try to handle all wifi stuff in one place

  • in wifiHandler the following statement does not work unless status is set somewhere else, status is a global variable, you update it inside the while statement but you might not get there

while (status != WL_CONNECTED)

  • you use a lot of global variables, you can use static variables inside functions the same way but they will be part of the function and will not be visible outside. This makes the code easier to read and copy to another project e.g.

foo (){

static int myStaticVariable = 0; // variable is set to 0 only the first time the function runs
int myLocalVariable = 0; // variable is set to 0 every time function runs

myStaticVariable++; // Increments every time function runs
myLocalVariable++; // always 1

}

Hi,
Thanks for the advices, I moved all variables I could to static.
In addition I took the state machine that was talked about and edited it to fit my needs, seem to work now, but not sure if will be enough to connect for the long term, and for that I would appreciate your approval.
This is the new code:

#include <SPI.h>
#include <WiFiNINA.h>
#include <Adafruit_SHT31.h>
#include <Wire.h>
#include <Digital_Light_TSL2561.h>
#include "arduino_secrets.h" 

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

// Initialize the Wifi client library
WiFiClient client;

Adafruit_SHT31 sht31 = Adafruit_SHT31();

#define SMAPIN A0
#define SMBPIN A2

String deviceID;
int temperature;
int humidity;
int light;
int weight;
int smA;
int smB;

const char WEBSITE[] = "api.pushingbox.com"; //pushingbox API server
const String devid = "v387AFB20A3CADC6"; //device ID on Pushingbox for our Scenario

unsigned long lastConnectionTime = 0;            // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 90000; // delay between updates, in milliseconds

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  delay(5000);
  Serial1.begin(9600);

  pinMode(LED_BUILTIN, OUTPUT);

  wifiHandler();

  sensorsSetup();

}

void loop() {
  wifiHandler();
  getTemperatureHumidity();
  getWeight();
  getSm();
  getLight();

  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }

}


// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(WEBSITE, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /pushingbox?devid=" + devid
       + "&deviceID=" + (String) deviceID
       + "&humidity=" + (String) humidity
       + "&temperature="      + (String) temperature
       + "&light="      + (String) light
       + "&weight="      + String(weight, 3)
       + "&smA="      + (String) smA
       + "&smB="      + (String) smB
         );

      // HTTP 1.1 provides a persistent connection, allowing batched requests
      // or pipelined to an output buffer
      client.println(" HTTP/1.1"); 
      client.print("Host: ");
      client.println(WEBSITE);
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
    Serial.println("Sent data");
    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}


void getTemperatureHumidity() {
  temperature = sht31.readTemperature();
  humidity = sht31.readHumidity();
}



void getWeight() {
  static String readString;
   while (Serial1.available())
  {
    char c = Serial1.read();  //gets one byte from serial buffer
    readString += c; //makes the String readString
    delay(2);  //slow looping to allow buffer to fill with next character
    if (c == 'g' ) {
      int strLen =  readString.length(); 
      
      //Serial.print("strlen: ");Serial.println(strLen);
      //Serial.print("readString: ");Serial.println(readString);

      if (strLen == 12) { //DEBORAH
        weight = readString.substring(5,10).toFloat();
      }
      else if (strLen == 19) {
        if (readString.charAt(6) == 'N') { // NINA
          weight = readString.substring(11,17).toFloat();
          weight /= 1000;
        }
        else { //PETER
          weight = readString.substring(10,16).toFloat(); 
        }  
      }
      readString = "";
    }
    //Serial.print("weight: "); Serial.println(weight,3);

  }
}

void getSm() {
  smA=analogRead(SMAPIN);
  smB=analogRead(SMBPIN);
}

void getLight() {
  light = TSL2561.readVisibleLux();
}

void sensorsSetup(){
    setupLight();
    sht31_setup();
}


void setupLight(){
  Wire.begin();
  TSL2561.init();
}


void sht31_setup(){
  if (! sht31.begin(0x44)) {   // Set to 0x45 for alternate i2c addr
    Serial.println("Couldn't find SHT31");
  }
}

void wifiHandler() {
    static int state = 0; // Static variable persists and keeps value with each function call
    static int wifiConnectTry = 0; // Count connection attempts
    static int wifiStatus = WL_IDLE_STATUS; // Initial status before first connection
    static bool firstConnection = true;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = 0;

    #define WIFI_CONNECT_TIMEOUT 10000 // 10 seconds waiting time between re-connection attempts

    // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

wifiStatus = WiFi.status();

enum WIFI_STATE_TYPE { WIFI_CONNECT, // Case 0
                       WIFI_STATE_RESTART = 255
                     };

switch ( state )
{
  case WIFI_CONNECT:
    if ( wifiStatus == WL_CONNECTED )
    {
      if (firstConnection) {
        firstConnection = false;
        printWifiStatus();
      }
      state = WIFI_CONNECT;
      wifiConnectTry = 0;
      digitalWrite(LED_BUILTIN, HIGH);
      break; // Continue after end of switch case statement
    }
    
    if ( millis() - previousMillis < WIFI_CONNECT_TIMEOUT && wifiConnectTry > 0 )
    {
      break; // Continue after end of switch case statement
    }

    if ( wifiConnectTry > 10 )
    {
      state = WIFI_STATE_RESTART;
      break; // Continue after end of switch case statement
    }

// Try to connect if from the above: 1. not already connected (case 0) and 2. if more than 10 seconds have passed and more than one connection attempt took place and 3. Less than 10 connection attempts took place
    wifiStatus = WiFi.begin( ssid, pass );
    firstConnection = true;
    previousMillis = millis();
    wifiConnectTry++;
    Serial.print( "Try: " );
    Serial.print( wifiConnectTry );
    Serial.print( " Status: " );
    Serial.println( wifiStatus );
    break; // Continue after end of switch case statement

// If case 0 or any other case was not the case, then reset the state variable, reset connection attempt counter, reset WiFi status to initial status, explicitly disconnect, explicitly end, switch off LED
  default:
    state = 0;
    wifiConnectTry = 0;
    wifiStatus = WL_IDLE_STATUS;
    WiFi.disconnect();
    WiFi.end();
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println( "WiFi restart" );
    break; // Continue after end of switch case statement
}


}

void printWifiStatus() {
  static byte mac[6];
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  
  
  WiFi.macAddress(mac);
  String mac0,mac1,mac2,mac3,mac4,mac5;
  mac0 = String(mac[0],HEX);
  mac1 = String(mac[1],HEX);
  mac2 = String(mac[2],HEX);
  mac3 = String(mac[3],HEX);
  mac4 = String(mac[4],HEX);
  mac5 = String(mac[5],HEX);
  deviceID = String(mac5 + ":" + mac4 + ":" + mac3 + ":" + mac2 + ":" + mac1 + ":" + mac0);
  Serial.print("mac address: "); Serial.println(deviceID);
}

Thanks!

Could you be so kind and get back to your first post and click on modify and place code tags around your code. It will make the post easier to read for others that might be interested. It also gives us more space on this page to add some more improvements if you like. :slight_smile:

omri1:
In addition I took the state machine that was talked about and edited it to fit my needs, seem to work now

That is a good start.

omri1:
not sure if will be enough to connect for the long term, and for that I would appreciate your approval.

I would recommend a few modifications.

First, at the end of your loop write some simple code that will give you the numbers of runs per second and the minimum and maximum time per loop. This will give you some good information about what is going on. A good goal is to get the loop to run as often as possible and the loop time to stay low.

Regarding the wifiHandler

  • you do not need to check whether the wifi module is there or not every time (check with your new counter code how much time this wastes)
  • the same is true for the firmware (check with your new counter code how much time this wastes)
  • just add a few more states to the state machine and only check these once
  • add a LED blinking pattern to the no module state, that way you will know something is wrong even without the Serial Monitor
  • with first connection you introduce a second state variable, try to rewrite your code so you do not need that you already have state

Regarding the loop

  • add timing code to start the sensor reading only when necessary use the new counter code to confirm, the loop can run ten to hundreds of thousand times a second

This will allow you to add new code to your project with minimal interference on the code you already have.

Regarding getWeight

  • remove the delay (this is an Arduino, it is not human, it does not need vacation can do many things in 2 milliseconds)
  • change the while into an if()
  • for this sensor you might not need any timing code because you will read the serial stream while it is arriving, so most of the time it should just check whether a new character has arrived and then return because the characters will arrive very slowly compared to the speed of the sketch

Regarding your comments

  • Try to look at them and see whether they are necessary. Your code should not need many comments. I know it difficult to find a good balance. At first you read its good practice, but then comments and code get out of sync. I try to rewrite code with good variable names and only use comments for things that the code cannot tell.

e.g. char c = Serial1.read(); //gets one byte from serial buffer

Don’t you think the code says exactly that? You could redefine Serial1 to tell you what sensor is connected there. That might be more useful.

break; // Continue after end of switch case statement

Same thing. You modified the code examples so far quite well, that I believe you do not need that comment. :slight_smile:

To complete all that, please test your code in your environment by ether disabling WiFi at the router or place the Arduino in a metal box a bit away from the router. You can keep the lit open a bit for the USB cable to see the Serial Monitor. Just long enough to disrupt the WiFi connection. You can lower the output power from your router if that has this option. Just for some testing.

Hi,
Thanks for the reply.
I will make these changes in the next few days. Meanwhile the connection has lost after about 8 hours, could you tell the main reason for that from my last code?
In addition, is there an easy way to save the log/prints when not connected to a computer? using non-volatile memory maybe?
Thanks.

omri1:
Meanwhile the connection has lost after about 8 hours, could you tell the main reason for that from my last code?

I suspect you removed too much from the state machine. You need a state where you just check the status and restart everything (set state to WIFI_STATE_RESTART) when you are no longer connected but where already connected. You need to go trough WIFI_STATE_RESTART which is handled by the default part of the switch.

omri1:
In addition, is there an easy way to save the log/prints when not connected to a computer? using non-volatile memory maybe?

The easiest is likely a SD card. There are small breakout boards available and microSD cards in the size you need are almost for free.

Hi,
I did some changes to the state machine, it seem to survive longer periods now, but will only know with time passing :slight_smile:
This is the new code, any comments will be welcomed:

#include <SPI.h>
#include <WiFiNINA.h>
#include <Adafruit_SHT31.h>
#include <Wire.h>
#include <Digital_Light_TSL2561.h>
#include "arduino_secrets.h" 

char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;

String deviceID;
float temperature;
float humidity;
int light;
float weight;
int smA;
int smB;

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 90000; // delay between updates

void setup() {
  Serial.begin(9600);
  delay(2000);
  Serial1.begin(9600);
  Serial.println("Plants");
  pinMode(LED_BUILTIN, OUTPUT);

  wifiTask();

}

void loop() {
  #define INTERVAL 5 * 1000
  static unsigned long lastDataRecord = 0;
  
  wifiTask();

  if ( millis() - lastDataRecord > INTERVAL )
  {
    updateSensors();
    prints();
    lastDataRecord = millis();
  }

  getWeight();

  loopAnalysis();

}

void updateSensors() { 
  getTemperatureHumidity();
  getSm();
  getLight();
}


int httpRequest() {
  static WiFiClient client;
  static const char WEBSITE[] = "api.pushingbox.com";
  static const String devid = "v387AFB20A3CADC6";

  client.stop();

  if (client.connect(WEBSITE, 80)) {
    Serial.println("connecting...");
    client.print("GET /pushingbox?devid=" + devid
       + "&deviceID=" + (String) deviceID
       + "&humidity=" + (String) humidity
       + "&temperature="      + (String) temperature
       + "&light="      + (String) light
       + "&weight="      + String(weight, 3)
       + "&smA="      + (String) smA
       + "&smB="      + (String) smB
         );

    
      client.println(" HTTP/1.1"); 
      client.print("Host: ");
      client.println(WEBSITE);
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
    Serial.println("Sent data");
    
    lastConnectionTime = millis();
    return 1;
  } else {
    Serial.println("failed to connect to http");
    return 0;
  }
}

void getTemperatureHumidity() {
  static Adafruit_SHT31 sht31 = Adafruit_SHT31();
  static bool shtValid = false;
  if (shtValid) {
    temperature = sht31.readTemperature();
    humidity = sht31.readHumidity();
    if (isnan(temperature) || isnan(humidity))
      {
          temperature = 0;
          humidity = 0;
          Serial.println("Failed to read from DHT");
          shtValid = false;
      }
  }
  else {
    if (!sht31.begin(0x44)) {
      Serial.println("Couldn't find SHT31");
    }
    else {
      shtValid = true;
    }
  }
}

void getLight() {
  static bool lightVaild = false;
  if (isTSLconnected()) {
    if (lightVaild) {
      light = TSL2561.readVisibleLux();
    }
    else {
      TSL2561.init();
      lightVaild = true;
    }
  }
  else { 
    Serial.println("TSL2561 not connected");
    light = -1;
    lightVaild = false;
  }
}

bool isTSLconnected() {
  Wire.beginTransmission(0x29);
  int error = Wire.endTransmission();
  if (error == 0) {
    return true;
  }
  else {
    return false;
  }
}

void getWeight() {
  #define TIME_OUT 5000
  static String readString;
  static unsigned long lastTimeWeightActivated = 0;
  if (Serial1.available())
  {
    char c = Serial1.read();
    readString += c;
    if (c == 'g' ) {
      lastTimeWeightActivated = millis();
      int strLen =  readString.length(); 
      
      //Serial.print("strlen: ");Serial.println(strLen);
      //Serial.print("readString: ");Serial.println(readString);

      if (strLen == 12) { //DEBORAH
        weight = readString.substring(5,10).toFloat();
      }
      else if (strLen == 19) {
        if (readString.charAt(6) == 'N') { // NINA
          weight = readString.substring(11,17).toFloat();
          weight /= 1000.0;
        }
        else { //PETER
          weight = readString.substring(10,16).toFloat(); 
        }  
      }
      readString = "";
    }
    //Serial.print("weight: "); Serial.println(weight,3);
  }
  else if (millis() - lastTimeWeightActivated > TIME_OUT) {
      weight = 0;
  }
}

void getSm() {
  #define SMAPIN A0
  #define SMBPIN A2
  smA=analogRead(SMAPIN);
  smB=analogRead(SMBPIN);
}

void wifiTask() {
    static int state = 0;
    static int wifiConnectTry = 0;
    static int wifiStatus = WL_IDLE_STATUS;
    static int httpStatus = 0;
    static int httpConnectTry = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = 0;

    #define WIFI_CONNECT_TIMEOUT 10000 // seconds waiting between re-connection attempts
    #define HTTP_CONNECT_TIMEOUT 5000
    #define HTTP_CONNECTED 1
    #define HTTP_DISCONNECTED 0

enum WIFI_STATE_TYPE { WIFI_CONNECT, // Case 0
                       HTTP_CONNECT,
                       HTTP_POLL,
                       WIFI_STATE_RESTART = 255
                     };



switch ( state )
{
  case WIFI_CONNECT:
    if ( wifiStatus == WL_CONNECTED )
    {
        Serial.println("WIFI Connected");
        printWifiStatus();
        state++;
        digitalWrite( LED_BUILTIN, HIGH );
        break;
    }
    if ( millis() - previousMillis < WIFI_CONNECT_TIMEOUT && wifiConnectTry > 0 )
    {
      break;
    }

    if ( wifiConnectTry > 10 )
    {
      state = WIFI_STATE_RESTART;
      break;
    }
    wifiStatus = WiFi.begin( ssid, pass );
    previousMillis = millis();
    wifiConnectTry++;
    Serial.print( "Try: " );
    Serial.print( wifiConnectTry );
    Serial.print( " Status: " );
    Serial.println( wifiStatus );
    break;
  case HTTP_CONNECT:
    if (httpStatus == HTTP_CONNECTED) {
      state++;
      break;
    }
    if ( millis() - previousMillis < HTTP_CONNECT_TIMEOUT && httpConnectTry > 0 )
    {
      break;
    }

    if ( httpConnectTry > 10 )
    {
      state = WIFI_STATE_RESTART;
      break;
    }
    httpStatus = httpRequest();
    previousMillis = millis();
    httpConnectTry++;
    Serial.print( "http Try: " );
    Serial.print( httpConnectTry );
    Serial.print( " http Status: " );
    Serial.println( httpStatus );
    break;
  case HTTP_POLL:
    if (millis() - lastConnectionTime > postingInterval) {
        httpStatus = httpRequest();
        if (httpStatus == HTTP_DISCONNECTED) {
          state = HTTP_CONNECT;
          break;
        }
    }
    break;
  default:
    state = 0;
    wifiConnectTry = 0;
    wifiStatus = WL_IDLE_STATUS;
    httpConnectTry = 0;
    httpStatus = HTTP_DISCONNECTED;
    WiFi.disconnect();
    WiFi.end();
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println( "WiFi restart" );
    break;
}

}

void printWifiStatus() {
  static byte mac[6];
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  
  
  WiFi.macAddress(mac);
  String mac0,mac1,mac2,mac3,mac4,mac5;
  mac0 = String(mac[0],HEX);
  mac1 = String(mac[1],HEX);
  mac2 = String(mac[2],HEX);
  mac3 = String(mac[3],HEX);
  mac4 = String(mac[4],HEX);
  mac5 = String(mac[5],HEX);
  deviceID = String(mac5 + ":" + mac4 + ":" + mac3 + ":" + mac2 + ":" + mac1 + ":" + mac0);
  Serial.print("mac address: "); Serial.println(deviceID);
}


void loopAnalysis()
{
  static unsigned long previousMillis = 0;
  static unsigned long lastMillis = 0;
  static unsigned long minLoopTime = 0xFFFFFFFF;
  static unsigned long maxLoopTime = 0;
  static unsigned long loopCounter = 0;

#define INTERVAL 1000

  unsigned long currentMillis = millis();
  if ( currentMillis - previousMillis > INTERVAL )
  {
    Serial.print( "Loops: " );
    Serial.print( loopCounter );
    Serial.print( " ( " );
    Serial.print( minLoopTime );
    Serial.print( " / " );
    Serial.print( maxLoopTime );
    Serial.println( " )" );
    previousMillis = currentMillis;
    loopCounter = 0;
    minLoopTime = 0xFFFFFFFF;
    maxLoopTime = 0;
  }
  loopCounter++;
  unsigned long loopTime = currentMillis - lastMillis;
  lastMillis = currentMillis;
  if ( loopTime < minLoopTime )
  {
    minLoopTime = loopTime;
  }
  if ( loopTime > maxLoopTime )
  {
    maxLoopTime = loopTime;
  }
}


void prints() {
  Serial.print("temperature: "); Serial.println(temperature);
  Serial.print("humidity: "); Serial.println(humidity);
  Serial.print("light: "); Serial.println(light);
  Serial.print("weight: "); Serial.println(weight,3);
  Serial.print("smA: "); Serial.println(smA);
  Serial.print("smB: "); Serial.println(smB);
}

Thanks