MKR100 stalls

Below is an example of what happens if it missed a data push

connected to thingspeak 
21713875
connected to thingspeak 
21729248
connected to thingspeak 
21744621
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21779924
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21812205
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21844486
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21876767
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21909048
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21941329
>>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<21973610
connected to thingspeak 
21988909
connected to thingspeak 
22004280
connected to thingspeak 
22019653
connected to thingspeak 
22035027

As you can see it just goes around and continues.
I had to dig through quite a lot of text to find that really bad block of 7 fails in a row.

Going to try implement your other suggestion but I want to try wait for a fail before I do.
May try to look for a specific http error too JIC it is that now debugging is sorta working.

Many thanks for helping me so much too btw.

I understand that the code repeats; looking at the times there is roughly a 32 second delay between them. My misunderstanding was that I thought you were talking about trying to data again immediately.

I can't place the 32 seconds; the only big delay that I could find in your earlier posted code was 12 seconds. Either you modified your code or I missed something (quite possible).

My apologies

I did extend the timers to ensure I was much longer than the minimum post time for TS

below is current code.
There is a 12 second delay at the loop entry and another delay at the end of the data push plus whatever time it takes for the program to process.

  /*
  This sketch is a combination of ADAFruits DHT sketch, WiFi101 Webclient
  and The arduino example from ThingSpeak
  Modified by Stephen Borsay for the MKR1000, feel free to use
   */
  
  #include <SPI.h> //you don't need this as we arn't using the shiled just chip
  #include <WiFi101.h>
  #include "DHT.h"
  
  #define DHTPIN 1    // what pin we're connected to, pin1 is 5th pin from end
  
  // Uncomment whatever DHT sensor type you're using!
  //#define DHTTYPE DHT11  // DHT 11
  #define DHTTYPE DHT21  // DHT 21
  //#define DHTTYPE DHT22  // DHT 22

  // define millis to time format
  #define SECS_PER_MIN  (60UL)
  #define SECS_PER_HOUR (3600UL)
  #define SECS_PER_DAY  (SECS_PER_HOUR * 24L)
  #define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)  
  #define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) 
  #define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
  #define elapsedDays(_time_) ( _time_ / SECS_PER_DAY
  // end time defines 
  
  DHT dht(DHTPIN,DHTTYPE);
  
  String apiKey ="xxxxxxxx"; // api from ThingSpeak
  
  char ssid[] = "xxxxxxx"; //  your network SSID (name)
  char pass[] = "xxxxxxx";    //your network password
  int keyIndex = 0;     // your network key Index number (needed only for WEP)
  
  //#define WEBSITE "api.thingspeak.com"
  
  int status = WL_IDLE_STATUS;
  // if you don't want to use DNS (and reduce your sketch size)
  // use the numeric IP instead of the name for the server:
  //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
  char server[] = "api.thingspeak.com";    // name address for Google (using DNS)
  
  // Initialize the Ethernet client library
  // with the IP address and port of the server
  // that you want to connect to (port 80 is default for HTTP):
  WiFiClient client;
  
  void setup() {
   
   //Initialize serial and wait for port to open:
    Serial.begin(57600);
    while (!Serial) 
    {
      ; // wait for serial port to connect. Needed for native USB port only
    }
  
    // check for the presence of the shield:
    if (WiFi.status() == WL_NO_SHIELD) {
    //  Serial.println("WiFi shield not present");
      // don't continue:
      while (true);
    }
  
    // 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/WEP network
      status = WiFi.begin(ssid, pass);
  
      // wait 10 seconds for connection:
      delay(10000);
    }
    
    Serial.println("Connected to wifi");
    printWifiStatus();
    
  }
  
  void loop() {



  
     // Wait a few seconds between measurements.
    delay(12000);
  
    //prefer to use float, but package size or float conversion isnt working
    //will revise in future with a string fuction or float conversion function
  
    int h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    int t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    int f = dht.readTemperature(true);
  
    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f))
    {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  
    // Compute heat index in Fahrenheit (the default)
    int hif = dht.computeHeatIndex(f, h);
    // Compute heat index in Celsius (isFahreheit = false)
    int hic = dht.computeHeatIndex(t, h, false);
  
  //  Serial.print("Humidity: ");
  //  Serial.print(h);
  //  Serial.print(" %\t");
  //  Serial.print("Temperature: ");
  //  Serial.print(t);
  //  Serial.print(" *C ");
  //  Serial.print(f);
  //  Serial.print(" *F\t");
  //  Serial.print("Heat index: ");
  //  Serial.print(hic);
  //  Serial.print(" *C ");
  //  Serial.print(hif);
  //  Serial.println(" *F\n");
  
    //  Serial.println("\nStarting connection to server..."); 
    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
     Serial.println("connected to thingspeak "); // original code
     Serial.println (millis());

            client.print(F("POST "));
            client.print("/update?key=apiKey&field1=" 
            +               (String) h
            +  "&field2=" +(String) t
            +  "&field3=" +(String) f
            +  "&field4=" +(String) hic
            +  "&field5=" +(String) hif
                                     );
                                        
            String tsData = "field1="   //need the length to give to ThingSpeak
            +             (String)  h
            +  "&field2=" +(String) t
            +  "&field3=" +(String) f
            +  "&field4=" +(String) hic
            +  "&field5=" +(String) hif
          ; 
  
  
            client.print("POST /update HTTP/1.1\n");  
            client.print("Host: api.thingspeak.com\n");
            client.print("Connection: close\n");
            client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
            client.print("Content-Type: application/x-www-form-urlencoded\n");
            client.print("Content-Length: ");
            client.print(tsData.length());  //send out data string legth to ts
            client.print("\n\n");
            client.print(tsData);
            client.stop();
            delay(3000); // 3 seconds + program cycle time + 12 second pre measure delay
      }
      else
      {
        Serial.print(">>>>>>>>>> failed to connect to thingspeak <<<<<<<<<<");
        Serial.println (millis());
      }
  
  }
  
  void printWifiStatus() {
    // print the SSID of the network you're attached to:
    //   Serial.print("SSID: ");
    //  Serial.println(WiFi.SSID());
  
    // print your WiFi shield'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");
  }

I am CONFIRMING that it is the MKR.

here is what I did.

  1. Noticed it had quit sending to TS.
  2. Pulled the usb power. (this should have forced a reset)
  3. re-applied USB power (again this should have forced a reset)
  4. re-started tera term but serial port unavailable (these things act like Leonardo's)
  5. tapped the MKR reset once (who's idea was it to put such a small and indented switch on there)
  6. tried tera term and MKR is available.
    7 montor teraterm window and connections are now working again to TS.

Simple and unequivocal conclusion is that I have to do a FULL RESET inc the reset button after a power up to get the MKR to pick up the ball and run with it again.

I know 100% that this is NOT a failure to achieve connection to TS nor is it a failure of TS to accept data its simply a hardware issue.

My only other theory (and that's all it is right now) is that the MKR still has build issues. Either with firmware or with its communications routines or that this one has a bad component that is subject to heat issues.
The last one I can pretty much rule out ambient temperature nearby as I have a UNO putting info up to TS sat nearby which will attest to nothing much more than 24' C with an avg of 22'C. Another thing to note is that this particular MKR has seen very little action until I added the AM2301.

I really do thank you for your patience and tenacity in trying to help but this MKR is heading for a YOUTUBE ending involving gratuitous violence and personal satisfaction.

Hi everyone, sorry I'm probably not posting on the right page but this is the biggest. Could I simply use an AA/AAA battery to power the mkr1000(with appropriate connector)? I'm worried about destroying the board and don't know much about this.

You may want to post this as a new topic rather than throwing it into a different subject.

But short answer is yes you can but DO NOT use the LIPO connector.

Check out the posts for pin out identification and such. or google the pin out for the MKR.

It does have a vcc in pin. but I am not sure if you would want to as it would probably drain regular batteries quite quickly.

Here is a link to the pinouts

OK I didn't put it under the HAMMER (yet) but its still under threat of death.

Saw a thread about a possible floating point issue with the MKR so followed that up and still no joy.

Here is a slightly odd thing.

The MKR locks up which is documented in the previous posts.

  1. Disconnect power completely for 10 seconds, connect power and it is still locked up and unresponsive.

  2. Disconnect power and whilst still disconnected press RESET, power up and it is still locked up and unresponsive.

  3. Power up and hold down RESET still unresponsive.

  4. Open IDE and still unresponsive.

  5. Try a different source thingspeak sketch for DHT's and it will still eventually lock up. (so not a sketch issue)

  6. Open serial monitor from IDE and it restarts (yes I know its designed to do that)
    It is clearly locked into a loop within the program that can only be reset triggered by a serial command.

  7. Disable all serial statements in sketches. Still goes into lock up so doubtful its an issue there.

  8. Enable extended debugging to rule out time based issues. Its totally random with anywhere between a couple of hours to over 15 hours before lock up.

  9. Tried watchdog timers and they help a little but it still wanders off into "NO-GO" zone eventually.

  10. Could also use a 555 to trigger the RESET line but again based on tests that's not going to work either

  11. I could fix this with a small bit of additional hardware (555) to drop the power every couple of hours but based on above that's not going to work and sort of defeats the object of the MKR

  12. Get slightly longer run times so long as it is being monitored via serial, but it still goes to cr@p at some point.

I cant see the point of having a wireless device that has to be physically connected to a computer to bring it back to life.

Q1. Why does a full power down do nothing ?

Q2. Is there a way to internally issue a command that makes it think it has just been connected to a computer thereby forcing it to reset itself ?

A2. Try this to call this function to reset the board : NVIC_SystemReset()

Thanks for the command

Have currently set it to reset every 10 minutes.
I can see from my serial output that a reset was called right on cue.

NEW issue is that after executing the reset the board loses its COM port and no longer shows up anywhere and stops sending data out to thingspeak.

That condition requires a single tap reset to reset the board.
The single reset is much better than the "power down, double tap reset, open serial console etc."

UPDATE
Changed your command to "void NVIC_SystemReset (void);" and now it appears to work ( time will tell pun intended )

Here is the code I used to add your command.

   if (myMinutes > 10)
 {
 
  Serial.println("<<<<<  RESET SYSTEM  >>>>>>");  // tell me it reset
   // NVIC_SystemReset();  // your command just for reference
   myMinutes = 0;  // reset clock or will keep going into reset
   void NVIC_SystemReset (void); // modified command
  }

Afraid that doesn't fix it either.

Going to include the complete current code JIC anyone can see something that I am missing. Bear in mind that before I added the suggestions about timers and resets it was still going into lock up.

/*
  This sketch is a combination of ADAFruits DHT sketch, WiFi101 Webclient
  and The arduino example from ThingSpeak
  Modified by Stephen Borsay for the MKR1000, feel free to use

  Modified by R.H.to include a timer and a software RESET thanks to members 
  on the Arduino forums. Timer is sorta pooched but works for the reset function sometimes
   */
  
  #include <WiFi101.h>
  #include "DHT.h"
  
  #define DHTPIN 1    // what pin DHT is connected to.
  
  // Uncomment whatever DHT sensor type you're using!
  //#define DHTTYPE DHT11  // DHT 11
  #define DHTTYPE DHT21  // DHT 21, AM 2301
  //#define DHTTYPE DHT22  // DHT 22, AM2302

  // define millis to time format
    unsigned long oneSecond = 1000UL;
    unsigned long startTime;
    int mySeconds = 0;
    int myMinutes = 0;
    int myHours = 0;
    int myDays = 0;
  // end time defines 
  
  DHT dht(DHTPIN,DHTTYPE);
  
  String apiKey ="2C154Q6GP01PL4XW"; // api from ThingSpeak
  
  char ssid[] = "BOB02";         // your network SSID (name)
  char pass[] = "MorseCode2";    // your network password
  // int keyIndex = 0;           // your network key Index number (needed only for WEP)
  
  int status = WL_IDLE_STATUS;
  // if you don't want to use DNS (and reduce your sketch size)
  // use the numeric IP instead of the name for the server:
  // IPAddress server(74,125,232,128);    // numeric IP for Google (no DNS)
  char server[] = "api.thingspeak.com";   // name address for Google (using DNS)
  
  // Initialize the Ethernet client library
  // with the IP address and port of the server
  // that you want to connect to (port 80 is default for HTTP):
  WiFiClient client;
  
  void setup() {
   
   // Initialize serial and wait for port to open:
      Serial.begin(57600);
      while (!Serial) 
    {
      ; // wait for serial port to connect. Needed for native USB (Leonardo, MKR) port only
    }
    // ********************
      startTime = millis();
    //*********************
  
    // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
      Serial.println("WiFi shield not present");
    // don't continue:
      while (true);
    }
  
    // 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/WEP network
      status = WiFi.begin(ssid, pass);
  
      // wait 10 seconds for connection:
      delay(10000);
    }   
    Serial.println("Connected to wifi");
    printWifiStatus(); 
  }
  
  void loop() {

     // Wait a 20 seconds between measurements. Minimum reccomended 15 seconds
    delay(20000);
  
    //prefer to use float, but package size or float conversion isnt working
    //will revise in future with a string fuction or float conversion function
  
    int h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    int t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    int f = dht.readTemperature(true);
  
    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f))
    {
      Serial.println("Failed to read from DHT sensor!");
      //*********             
        displayTime();
      //********* 
      return;   
    }
  
    // Compute heat index in Fahrenheit (the default)
    int hif = dht.computeHeatIndex(f, h);
    // Compute heat index in Celsius (isFahreheit = false)
    int hic = dht.computeHeatIndex(t, h, false);
  
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t");
    Serial.print("Heat index: ");
    Serial.print(hic);
    Serial.print(" *C ");
    Serial.print(hif);
    Serial.println(" *F\n");
  
    Serial.println("\nStarting connection to server..."); 
  //   if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
     Serial.println("connected to thingspeak "); // original code
     //*********             
       displayTime();
     //********* 

            client.print(F("POST "));
            client.print("/update?key=apiKey&field1=" 
            +               (String) h
            +  "&field2=" +(String) t
            +  "&field3=" +(String) f
            +  "&field4=" +(String) hic
            +  "&field5=" +(String) hif
                                     );
                                        
            String tsData = "field1="   //need the length to give to ThingSpeak
            +             (String)  h
            +  "&field2=" +(String) t
            +  "&field3=" +(String) f
            +  "&field4=" +(String) hic
            +  "&field5=" +(String) hif
          ; 
  
            client.print("POST /update HTTP/1.1\n");  
            client.print("Host: api.thingspeak.com\n");
            client.print("Connection: close\n");
            client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
            client.print("Content-Type: application/x-www-form-urlencoded\n");
            client.print("Content-Length: ");
            client.print(tsData.length());  //send out data string legth to ts
            client.print("\n\n");
            client.print(tsData);
            client.stop();
            delay(20000); // 30 seconds + program cycle time + 20 second pre measure delay
      }
      else
      {
        Serial.print(">>>>>>>>>> failed to connect to thingspeak <<<<<<<<<< ");

     // Perform a system reset to prevent MKR lockups.
     Serial.println("<<<<<  RESET SYSTEM  >>>>>> "); // Tell me it happend.
     myMinutes = 0; // Reset clock to prevent continual reset condition.
     void NVIC_SystemReset (void);  //Do the deed and restart the sucker.
     
      //*********             
        displayTime();
      //*********    
      }
  }
  
  void printWifiStatus() {
    //  print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
    //  print your WiFi shield'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");
  }
  
  //  TIME & RESET ROUTINE
  void displayTime()
  {
   startTime += oneSecond;
   if (mySeconds > 59)
   {
     myMinutes++;
     mySeconds = 0;
     if (myMinutes > 59)
     {
       myHours++;
       myMinutes=0;
       if (myHours > 23)
       {
         myDays++;
         myHours=0;
       }
     }
   }
   //Serial.print(myDays);  // not needed never runs that long without a lock up
   //Serial.print(":");     // not needed never runs that long without a lock up
   if (myHours < 10) Serial.print("0");
   Serial.print(myHours);
   Serial.print(":");
   if (myMinutes < 10) Serial.print("0");
   Serial.print(myMinutes);
   Serial.print(":");
   if (mySeconds < 10) Serial.print("0");
   Serial.println(mySeconds);
   mySeconds++;
   
   if (myMinutes > 7) // count to achive before reset
 {
  // Perform a system reset to prevent MKR lockups.
  Serial.println("<<<<<  RESET SYSTEM  >>>>>> "); // Tell me it happend.
   myMinutes = 0; // Reset clock to prevent continual reset condition.
   void NVIC_SystemReset (void);  //Do the deed and restart the sucker.
  }
  }

OK there was a chance but it seems the internal reset using NVIC does not operate for some reason.
Some of my message is a little too technical even for me so if you are an M0 geek bear in mind my skill level is WAAY below yours.

If it performed as it should then the clock should reset and there should be connection to the WiFi messages after a reset. similar to this

"Attempting to connect to SSID: NNNN
Connected to wifi
SSID: NNNN
IP Address: 192.168.0.18
signal strength (RSSI):-54 dBm"

Double checked the NVIC usage list in the cortex M0 manual and it "should" do a sys reset but only on interrupts not a whole system as I understand.

Does anyone know how to implement "SYSRESETREQ" or "AIRCR" in the M0 from the IDE as one of these may be more appropriate from my reading.

As far as the problem itself it bears striking similarity to this passages from the MO reference
"Reset
Reset is invoked on power up or a warm reset. The exception
model treats reset as a special form of exception. When reset is
asserted, the operation of the processor stops, potentially at any
point in an instruction. When reset is deasserted, execution
restarts from the address provided by the reset entry in the vector
table. Execution restarts in Thread mode.

The processor enters a lockup state if a fault occurs when executing the NMI or
HardFault handlers, or if the system generates a bus error when unstacking the PSR on
an exception return using the MSP. When the processor is in lockup state it does not
execute any instructions. The processor remains in lockup state until one of the
following occurs:
• it is reset
• a debugger halts it
• an NMI occurs and the current lockup is in the HardFault handler.
Note
If lockup state occurs in the NMI handler a subsequent NMI does not cause the
processor to leave lockup state."

Below are messages in sequence so you can see that it fails to do a "real" reset.

Starting connection to server...

failed to connect to thingspeak <<<<<<<<<< <<<<< RESET SYSTEM >>>>>>
00:00:52
Humidity: 40 %.Temperature: 24 *C 75 *F.Heat index: 23 *C 74 *F

Starting connection to server...

failed to connect to thingspeak <<<<<<<<<< <<<<< RESET SYSTEM >>>>>>
00:00:53
Humidity: 40 %.Temperature: 24 *C 75 *F.Heat index: 23 *C 74 *F

I'm not sure if calling the reset like you do works, I think you really should call it like this (without "void"):

__disable_irq();
NVIC_SystemReset();

You may also could try to call this code :
initiateReset(250);
delay(250);

EDIT => this is a bad idea : it will erase the full flash, calling the funny banzai() function. You'll have to reflash the program...

Changed it to your suggestion.

Also changed the DHT pin from D1 to D3 as its not listed as an INT pin. Just in case it was all so simple.

WOW so it also has a self destruct too pretty wicked !
Not sure what they were thinking about at the time with that one LOL.
OK load from ROM reset.. Nice to know.

Hi guys!
I intended post my issue opening a new thread, but found yours and probably this is the right place.
Firs of all, i apologyze for my english!
Let me tell you i am fighting whith a sketch for more than a mounth and, at this point, i'm unable to go on. :frowning:
I intended use the new MKR1000 (sold as 'internet of things') to remote controlling my conditioned air.
I started facing the most difficult part (in appearance!): capturing, decoding and sending infrared codes to the conditioner. This was done with no issues.
Later, i designed a simple webpage to allow remote access & operate the air conditioner. I also did it using Wifi101 library. It seemed to be working fine, but it was not tested continouslly for days.
Then, when i compiled the working version and let the board working, waiting for a user to connect, i found the main issue: After a few hours working, i can't access the board. It's not responding.
Arduino IDE has no powerfull debug tools, so i started monitoring the board through serial messages, until i found Serial got it's own issues: If you send a Serial.println("my message") and ain't no one to read it, the sketch stops. Also, the function Serial.availableForWrite() failed compiling... :o
So i focused the problem trying to cleaning the sketch to the minimum, to fix the problem.
Well, i think i've found the problem source is in the WiFi101 library. I only let a server simple webpage, and gets stopped after few hours.
Can't debug more, because i'm not an expert in http code. Just know my board connects with no issues and, when is working, it's doing exactly as expected.
I attach my debugging sketch, so anyone can test it and (if i'm lucky) report any bug found.
I apologyze again for the length of my message.
Thanks in advance! :slight_smile:

mephala.

StabilityTest0.ino (5.93 KB)

@ mephala

You probably spent a long time de-bugging and if like me you are still trying then DO NOT try the reset methods in any of the posts above.

Some of them (and variations) just lock up the MKR and disables the serial port which makes it invisible.

JIC it is pertinent what IDE are you using on what OS ?

If you need WiFi then I find the ESP's very stable over long term usage.

The range is about the same unless you get one with a proper antenna and the prices are fantastic in comparison and both can often be programmed via Arduino IDE.

Ballscrewbob,
Thanks for your immediate answer. :slight_smile:
I read your experiences about resetting the board, so thanks for avoiding me this task.
My IDE is the official, last 1.6.8 version, running over Windows 10. The WiFi101 library is version 0.9.1.
I know ESP's but, working with infrared codes, i needed to deal with processor-level instructions to set timers, and found more support over MKR boards. This part is now working fine, and the problem i'm facing is the webserver simple page stability.
I tryed to reduce it still more. Here you have the code:

#include <WiFi101.h>

const char ssid[] = "abc";                         // created AP name
const char wifiPass[] = "def";                         // AP password.

// the IP address for the shield:
const IPAddress privateIP(192, 168, 1, 61);
const IPAddress dns(192, 168, 1, 1);
const IPAddress gateway(192, 168, 1, 1);
const IPAddress netMask(255, 255, 255, 0);

WiFiServer server(80);
WiFiClient acServerClient;

void setup() {
  WiFi.config(privateIP, dns, gateway, netMask);
  delay(10000);
  reconnectWifiIfNecessary();
  server.begin();  // start the web server on port 80
}

void loop() {
  reconnectWifiIfNecessary();
  // Sending AC webpage:
  processAcServer();
  delay(200);
}

void reconnectWifiIfNecessary() {
  while ( WiFi.status() != WL_CONNECTED) {
    // Connect to WPA/WPA2 network:
    WiFi.begin(ssid, wifiPass);
    // wait 20 seconds for connection:
    delay(20000);
  }
}

void processAcServer() {
  acServerClient = server.available();              // listen for incoming clients
  if (acServerClient) {                             // if you get a client,
    String currentLine = "";                        // make a String to hold incoming data from the client
    while (acServerClient.connected()) {            // loop while the client's connected
      if (acServerClient.available()) {             // if there's bytes to read from the client,
        char c = acServerClient.read();             // read a byte, then
        if ((c == '\n') && (currentLine == "")) {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          sendAcControlWebPage();
          break;
        }
        if (c == '\n') {      // if you got a newline, then clear currentLine:
          currentLine = "";
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // close the connection:
    acServerClient.stop();
  }
}

void sendAcControlWebPage()  {
  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  acServerClient.println("HTTP/1.1 200 OK");
  acServerClient.println("Content-type:text/html");
  acServerClient.println("Connection: close");
  acServerClient.println();
  // send web page
  acServerClient.println("<!DOCTYPE html>");
  acServerClient.println("<html>");
  acServerClient.println("<head>");
  acServerClient.println("<title>Control aire condicionat</title>");
  acServerClient.println("</head>");
  acServerClient.println("<body>");
  acServerClient.println("<h3>CONTROL AIRE CONDICIONAT</h3>");
  acServerClient.print("<h4>(PLANTA BAIXA) Versió: 1.0</h4>");
  acServerClient.print("<p>Estat actual del aire condicionat: PARAT");
  acServerClient.println("<form method=\"get\">");
  acServerClient.println("<input type=submit value=\"Enviar\">");
  acServerClient.println("</form>");
  acServerClient.println("</body>");
  acServerClient.println("</html>");
}

It would be very helpfull if someone could test the bahaviour of the sketch, compiling and trying to access the page.
To do this, simply replace the ssid name and password for the right ones, compile and upload the sketch. After waiting 1-2 minutes for the board to connect your wifi, try accessing it typing "192.168.1.61" in your browser. The goal is confirm if webpage is still available after a few hours.
Of course, you should change IP private addres & netmask if necessary, to match yours.
Thanks in advance! :slight_smile:

Compiled and uploaded to my MKR just fine. Made changes to suit my network.
Am using 1.6.9 under Win 7 x64 here.
Lots of people have had issues with 1.6.8 and win 10 but seeing as you can upload I doubt that is anything to worry about at your end.
Most people seem to prefer 1.6.5 r5 or 1.6.9 for the IDE but if yours is OK I would not change it.

Did you notice any sort of pattern to it failing ? e.g. every 2 hours or does it appear to be random ?
Just a thought but at my end with my issues some serial output seems to extend the times between fails so long as I don't have too many serial statements which for some odd reason makes it fail more often.

Shows the following with the last being a click box that just refreshes the page here.
I will check in on it a little later.

CONTROL AIRE CONDICIONAT

(PLANTA BAIXA) Versió: 1.0

Estat actual del aire condicionat: PARAT

Enviar

UPDATE.
Just re-read your post about the serial issues. Not sure if you are aware that you have to wait for the serial to be available by adding the following to your code.

// place after void setup() {
// Initialize serial and wait for port to open:
      Serial.begin(57600);
      while (!Serial) 
    {
      ; // wait for serial port to connect. Needed for native USB (Leonardo, MKR) port only
    }

The MKR is a bit of an oddball in serial matters like the Leonardo.

Thanks again, Ballscrewbob! :slight_smile:
I also think the IDE & operating system aren't the problem. IDE, compiling and uploading are working fine.
No pattern found in failures: the webpage failed responding since few minutes to a couple of days :frowning:
The web page is simplified at its maximum, so it just refresh itself. The original version offers the option to select desired temperature for the AC. So reduced, it stills fails after a time :confused:
I extracted all the serial outputs from my code to be sure they're aren't disturbing & masking the problem.
Yes, i waited for the serial to be ready before going further. Also did:

if (Serial) {
  Serial.println(myMessage);
}

Also tryed this:

if (Serial) {
  if (Serial.availableForWrite() > myMessage.length) {
    Serial.println(myMessage);
  }
}

...but the function 'Serial.availableForWrite()' althroug doccumented, failed compiling! :o
But, if nobody reads the Serial, the sketch halts until someone does.
Waiting your news! :slight_smile:

mephala.

mephala:
...but the function 'Serial.availableForWrite()' althroug doccumented, failed compiling! :o
But, if nobody reads the Serial, the sketch halts until someone does.

This issue is solved here.

Thanks, AloyseTech!
I heard about this when googled for a solution, but realized my issue wasn't Serial related, but a webserver problem, so i decided extract all serial outputs from my source.
In the other hand, there's no need having a serial ouput in a device intendend to be isolated, communicating only by wifi.
Regards!

mephala.