Arduino Web Server stops to work

Hi all,
I try to create a simple Web Server using my new Arduino UNO WIFI Rev2.
I followed example and documentation and it is running.

I noted, just today, that if I try to “telnet” TCP port of WebServer, that in my case is a custom port, my Arduino web server stops to respond to future request!
Is it normal?
I think that “telnet X.X.X.X TCP_PORT” generate persisten connection.
Could it be the cause of this malfunction?

This is the part of my code about Web Server:

  WiFiClient client = server.available(); //creazione oggetto client del web server

  //Se un client si è connesso...
  if(client){
    Serial.println("Connessione ricevuta!");
    while(client.connected())
    { 
        if(client.available()){
            char c = client.read(); //lettura byte inviato dal client
            Serial.write(c); 
            if(c=='\n'){
              if(strAttuale.length()==0){
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println();
                client.println("<h1 style='color:red'>ARDUINO UNO</h1><br>");
                client.println();
                break;
              }//end if lineaAttuale
              else
                strAttuale=""; //svuotare la linea attuale se si riceve una nuova string          
            }//end if
            else if(c!= '\r')
              strAttuale=strAttuale+c; //concatenazione carattere nella stringa
        } //end if
    }//end while

    //chiusura connessione
     client.stop();    
  }//end if

How can I solve it?
Should I try to force to close connection?

Thanks in advanced
Best regards
Federico

You failed to post complete code, so this is a bit guessing. But it seems you used the String class in your code which is a really bad idea on AVR (and megaAVR) platforms as the have to less memory for that. There are tons of explanations on the Internet about the reason, so here just the ultra-short version: fragmentation.
Rewrite your code to avoid dynamic allocation, use stack variables.

Hi @pylon,

This is my code:

#include <SPI.h> //libreria protocollo HW SPI
#include <WiFiNINA.h> //libreria per modulo WIFI su Arduino UNO WIFI
#include "DHT.h" //libreria per sensore dht
#include <arduino-timer.h> //libreria per timer
#include <TimeLib.h> //libreria funzioni per gestione orario e data

//costanti per dht
#define DHT_PIN 2 //pin connessione dht con Arduino UNO WIFI
#define DHT_MODELLO DHT22 //dht oppure DHT11

//variabili
char wifi_network[] = "FRITZ!Box";
char password[] = "";
char orario[80];
int conn=0;
float temp=0.0;
float humid=0.0;
float pot_segnale_wifi=0.0;
String strAttuale="";
String datetime="";

WiFiServer server(9000); //configuro web server in ascolto su TCP-9000
//WiFiUDP ntpUDP; //creazione oggetto UDP
//NTPClient timeClient(ntpUDP, "ntp1.inrim.it",7200); //configuro parametri NTP (server e offset)

DHT dht(DHT_PIN, DHT_MODELLO); //creazione oggetto dht
auto timer = timer_create_default(); //creazione oggetto timer

//Configurazione statica di rete
IPAddress indirizzoip (192,168,99,4); //indirizzo IP statico LAN (192.168.99.3)
IPAddress netmask (255,255,255,0); //netmask LAN (255.255.255.0)
IPAddress gateway (192,168,99,254); //gateway router (192.168.99.254)
IPAddress serverdns(192,168,99,1);  //DNS Server LAN (192.168.99.1)

void misurazione(); //prototipo procedura "misurazione"
void riconnessione_wifi(); //protitpo procedura riconnessione alla rete wireless
void ntp_datetime(); //prototipo procedura NTP e conversione da UNIX time a stringa data e orario
void ping_check(); //prototipo procedura ICMP test Gateway, LAN DNS, NTP Server

//Setup
void setup() {
 Serial.begin(9600);
 WiFi.noLowPowerMode();
 //Verifica modulo WIFI
 if(WiFi.status()==WL_NO_MODULE){
    Serial.println("Modulo WIFI guasto o non presente! :(");
    Serial.println("Provare a riavviare la scheda");
    while(1);
  }//end if

  WiFi.config(indirizzoip,serverdns, gateway, netmask); //configurazione indirizzamento statico 

  //Loop per connessione alla rete WIFI 
  while(conn != WL_CONNECTED)
  {
     Serial.println("Connessione alla rete WIFI in corso...");
     conn = WiFi.begin(wifi_network, password); //connessione alla rete WiFi WPA2
  }//end while

  Serial.println("Avvio web server...");
  server.begin(); //avvio web server

  Serial.println("Web server avviato! In ascolto su porta TCP 9000");
  
  Serial.print("Inizializzo dht...");
  dht.begin(); //avvio oggetto sensore
  Serial.println("OK!");

  timer.every(5*60000, misurazione); //la funziona misurazione viene richiamata ogni 5 minuti
  //timer.every(5*1000, misurazione);

  ping_check();
  ntp_datetime();
} //end setup


void loop() {

  if(WiFi.status() != WL_CONNECTED){
      Serial.println("Tentativo di ripristino connessione alla rete wireless in corso...");
      riconnessione_wifi();
  }


  //timeClient.update(); //gestione NTP
  timer.tick(); //gestione ciclicla del timer
    
  WiFiClient client = server.available(); //creazione oggetto client del web server

  //Se un client si è connesso...
  if(client){
    Serial.println("Connessione ricevuta!");
    while(client.connected())
    {
        
        if(client.available()){
            char c = client.read(); //lettura byte inviato dal client
            Serial.write(c); 
            if(c=='\n'){
              if(strAttuale.length()==0){
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println();
                client.println("<h1 style='color:red'>ARDUINO UNO WI-FI REV2 - STAZIONE METEO</h1><br>");
                client.print("<b>Temperatura:</b> "); client.print(temp);client.println(" &#176;<br>");
                client.print("<b>Umidita': </b>"); client.print(humid);client.println(" %<br>");
                client.print("<b>RSSI: </b>"); client.print(pot_segnale_wifi); client.println(" dBm<br>");
                client.print("<b>Data e ora misurazione: </b>");client.print(orario);client.println("<br>");
                client.println();
                break;
              }//end if lineaAttuale
              else
                strAttuale=""; //svuotare la linea attuale se si riceve una nuova string          
            }//end if
            else if(c!= '\r')
              strAttuale=strAttuale+c; //concatenazione carattere nella stringa
        } //end if
    }//end while

    //chiusura connessione
     client.stop();    
  }//end if

} //end loop


/*
*++++++++++++++++++++++++++ PROCEDURE +++++++++++++++++++++++++++++++++++++++++++++++++
*/

//Semplice procedura misurazione temperatura ed umidità tramite DHT22
void misurazione(){
  Serial.println("Eseguo misurazione temperatura ed umidita'...");
  temp=dht.readTemperature();
  humid=dht.readHumidity();
  pot_segnale_wifi=WiFi.RSSI();
  ntp_datetime(); //richiamo procedura per orario e data
}//end misurazione()


void riconnessione_wifi()
{
   WiFi.config(indirizzoip,serverdns, gateway, netmask); 

  //Loop per connessione alla rete WIFI 
  while(conn != WL_CONNECTED)
  {
     Serial.println("Connessione alla rete WIFI in corso...");
     conn = WiFi.begin(wifi_network, password); //connessione alla rete WiFi WPA2
  }//end while

  Serial.println("Connesione WIFI ripristinata");
  
}//end riconnessione_wifi()

void ping_check(){
  //byte esito=0; 
  Serial.print("Inizio check network ICMP...");

  if(WiFi.ping("192.168.99.254")>0)
      Serial.print("LAN Gateway raggiungibile!...");
  else
    Serial.print("LAN Gateway non raggiungibile!...");
  
  if(WiFi.ping("192.168.99.1")>0)
      Serial.print("LAN DNS raggiungibile!...");
  else
    Serial.print("LAN DNS non raggiungibile!...");

   if(WiFi.ping("www.google.com")>0)
      Serial.print("Internet raggiungibile!...");
  else
    Serial.print("Internet non raggiungibile!...");

   Serial.println("Fine Network ICMP Check");
}//end ping_check()


void ntp_datetime(){
 time_t UNIX_time=WiFi.getTime()+7200;
 sprintf(orario,"%02d/%02d/%d -- %02d:%02d:%02d",day(UNIX_time),month(UNIX_time),year(UNIX_time),hour(UNIX_time),minute(UNIX_time),second(UNIX_time));
 Serial.print("Data e ora: ");Serial.println(orario);
}//end ntp_datetime

I already changed the part of the function that create string about date and time.
Before I used, inside that function, String variabile and I changed it using char array.

In this moment my Arduino UNO WIFI Rev2 is near my home router and web server continue to work.
Unfortunatelly, I noted that Arduino UNO WIFI Rev2 has got a short wifi range :frowning:

Thanks for your reply and help!

You should definitely get rid of the String class completely!

Also use the F() macro to hold constant strings in flash and don’t waste RAM for them.

That’s the case as it has only a small on-board antenna. If you put the board into a case try to have as less as possible material between the on-board antenna (between the ICSP header and the analog input pins) and the router. Line of sight is best.

Hi @pylon
I will try to follow your suggestions about F() macro.

I noted that again my Arduino UNO WiFi Rev2, very close to my Fritzbox router, lost connection with the wireless router.

It is strange due to on router WiFi logs I can’t see any “Deregistration event” but device is offline.
I created a function inside code to manage wireless reconnection and it looks fine.
I analyzed logs from smokeping (software to monitor network latency) and from router and it seems that Arduino Uno WiFi Rev2 doesn’t like the following event of Fritzbox:

Wi-Fi auto channel: Current detection of the Wi-Fi environment (2,4 GHz) in progress, in order to optimize the Wi-Fi channels in use; some wireless devices may be re-registered.

Wi-Fi auto channel: The channel settings (previously channel 13 [frequency 2.472 GHz]) were changed; now active on channel 6 (frequency 2.437 GHz).

I have upgraded firmware to the lastest version of wireless cheap more or less 2 month ago.

Thanks
Federico

That’s not strange, that’s to be expected. If the device goes out of range (for whatever reason) it cannot deregister.

I can imagine that the Arduino doesn’t like the channel change as the original standard didn’t allow that.

If your Fritzbox does that quite frequently it shows that your WiFi spectrum is “polluted” with foreign networks, which makes it even harder for the small antenna on the Arduino to see your network.

Hi @pylon

In my opinion it is strange if signal is good (about -30dBm to -60dbm).

I understood your opinion about absence of disconnection logs on Fritzbox router and I agree if the client device has got a poor signal (out of range of my BSSID).

Thanks
Federico

If your router changes the frequency the Arduino doesn’t have a chance to deregister even if it had a good signal quality before.

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