Cayenne.loop reboots esp8266


Hello .
I’m developping an program for esp8266-01 to upload data into cayenne platform. I’m using arduino IDE and cayenne mqtt libraries from github.
All is running well but evey 30 minutes the Esp8266 reboots. I’ve removed all code except wifi connection and cayenne begin and loop functions to isolate the issue.
I’d appreciate any suggestion or clue.



can you share the code you are using.



This is the code (reduced to isolate the issue)
***You’ll find just cayenne mqtt and server management functions. Please dont take care of variables definition . ***
I’ve tested both with and without sending client requests/cayenne requests. In both cases the ESP reboots every 30’ aprox. (I’ve tested during 10 hours) .

//#define CAYENNE_DEBUG         // Uncomment to show debug messages
//#define CAYENNE_PRINT Serial  // Comment this out to disable prints and save space
#include <TimeLib.h> //TimeLib library is needed
#include <CayenneMQTTESP8266.h>
//#include "ThingSpeak.h" //library to send / receive data from ThingSpeak the IoT platform
#include <NtpClientLib.h> //Include NtpClient library header to syncronize date/time
#include <ESP8266WiFi.h> // gestion del modulo ESP8266
#include "ESP8266WebServer.h" // gestion del server HTTP en modulo ESP8266
#include <ESP8266HTTPClient.h> // http library to manage http connections to DDNS portal
#include  <EEPROM.h> // sustituida por la ESP_EEPROM
#include <Ticker.h>      // gestion de timer como interrupcion
Ticker tempo1;// crea objeto timer
String myStatus = ""; // status para ser enviado a ThingSpeak. 

//********************* VARIABLES A CONFIGURAR SEGUN NECESIDADES*************
const int nb_spaces_frame =12;//number of spaces to receive in the frame coming from the PIC. this is to avoid bad spurious frames 
const char* ssid = "-";// Nombre de red para la conexion a la red wifi
const char* password_WIFI = "";// Password de red para la conexion a la red wifi
const String domain_ddns="";// URL de este servidor basado en el ddns server
const String token_ddns="----";// token del servicio en el ddns server
char username[] = "----";
char password[] = "";
char clientID[] = "----";
//const char servertoconnect[] = "";    // URL of server for thingspeak 
//const char* myWriteAPIKey=""; // your channel key in thingspeak to write 
//const unsigned myChannelNumber=; // your channel number in thingspeak 
const int interval_thingspeak=2; // intervalo en segundos minimo de envios a cayenne (el servicio gratuito no deja enviar en menos de 1 seg) 
const String NTP_server=""; // zona horaria para la actualizacion de la hora . en españa UTC+1
const int NTP_time_zone=1;//defines the time Zone . Spain = UTC +1 (only valid for winter) 
const int preset_serial_time_out=2; // preseleccion en segundos time out port serie
const int preset_update_DDNS=1000; // periodo en segundos para chequeo de IP publica
//********************* VARIABLES de trabajo   ******************************

//WiFiServer server(80); //Create an instance of the ESP8266  server HTTP and specify the port to listen. It will reply to the Androdid APP client
ESP8266WebServer server(80);//Create an instance of the ESP8266  server HTTP and specify the port to listen. It will reply to the Androdid APP client
WiFiClient cliente;//es el cliente del ESP8266 para conectar con el thinspeak
const byte numChars = 200; // nb of characters for string to contain the string sent by PIC with all values
char receivedChars[numChars];// string to contain the string sent by PIC with all values
boolean Requestok=false; // flag to determine if http frame coming from the app is ok
int stat_client=0; // status of the client object sending to Thingspeak
unsigned long serial_timeout=0;// temporizador para detectar fallo de comunicacion del port serie
boolean serial_ko=0;// flag para detectar fallo de comunicacion del port serie
boolean serial_reset=0;// flag para control del reset del port comunicacion serie
long Client_timeout;// time out del cliente Thingspeak
unsigned long timer_send_energy;// temporizador para chequeo del reloj NTP y decision de envio a cayenne
String old_hour;
String old_month;
String new_hour;
String new_month;
int eeprom_init0=0;
int eeprom_init1=0;
int send_hourly=0;
int send_monthly=0;
String open_percentage,open_percentage_old,calibradook ,status1,reles_status1,reles_status2,reles_status_old1,reles_status_old2; // para calcular los valores a enviar a Thingspeak
unsigned long time_update_DDNS;
int update_DDNS=0;
String new_ip;
String old_ip;
int wait_init=0;
int initial=0;
int thinspeak_sent_init=0;
    static boolean recvInProgress = false;
    static byte ndx = 0;
//bool alreadyConnected=false; // para cerrar el cliente conectado
String time_date;
float Preal_max,Irms_max, Energy,Maximeter,Factor;
float Energy_hour_old,Energy_month_old;
int powerup=0; //para detectar que se ha encendido el power y poder enviar a cayenne el openpercentage de la persiana
int powerup_sent=0;
// ******  rutina de interrupcion por tiempo que se ejecuta cada x segundos***** ******************
void tempo1_sub() {    
  //Cayenne.virtualWrite(V2, 69);//borrar
 //if(++wait_init>5){Cayenne.virtualWrite(V6, Energy); wait_init=0;} // borrarinitial delay to catch reboots in Thinspeak because thinspeak has a minimiun period for writes of 20 seg  
 if(powerup<5){  //espera para envio de valores de apertura de persiana a cayenne despues de un powerup
 if(powerup==5 && powerup_sent==0){ powerup_sent=1;Cayenne.virtualWrite(V7, 1);} // detects ESP8266 reboot and sends to cayenne 
}  // *** fin rutina timer

// ********************************************************
// ******  rutina que se ejecuta 1 vez al inicio ***** 
// ********************************************************

void setup() {
   //ESP.wdtDisable(); // desbilita el WDT por soft de 1 seg . sigue habilitado el de hardware que es de 6 seg.  para habilitarlo de nuevo ESP.wdtEnable(1000);

// inicio del setup 
  pinMode(2, OUTPUT);
  digitalWrite (2,0);    // escritura del rele de salida para que el rele no haga guiños al arrancar
  pinMode(0, OUTPUT);
  digitalWrite (0,0);    // escritura del rele de salida para que el rele no haga guiños al arrancar

  // Connect to WiFi network  . retries each 500 msec . If no connection --> program doesn't continue 
  WiFi.begin(ssid, password_WIFI);  
  while (WiFi.status() != WL_CONNECTED) {
    // Starts the serve  
  server.on("/", handleRootPath);    //Associate the handler function to the path . In this case "\" means the root directory. handleRootPath is the name of the function to call
  server.begin();                    //Start the server
  NTP.begin (NTP_server, NTP_time_zone, true, 0);// time zone España UTC+1 (ojo solo en invierno)
  delay(100);  // time to stabilize

 // Init Cayenne myDevices
  Cayenne.begin(username, password, clientID, ssid, password_WIFI);  
  tempo1.attach(1, tempo1_sub); // init timer each segundo
}//********fin del setup

// *************************************************
// ******  rutina que se ejecuta en continuo  ***** 
// *************************************************
void loop() { 
    // Gestión de comunicación con Cayenne myDevices

//************ Server starts handling queries  ************************  
    server.handleClient();// server handle info
}//********fin del loop del programa

//************ AUXILIARY FUNCTIONS CALLED FROM THE MAIN LOOP  ************************
//************ ************************************************************

//************ // This function will be called every time a Dashboard widget writes a value to Virtual Pin 2.
//************ ********************************************************************************************************
 // NOTE: Channel = Virtual Pin
 String valorV1=String(getValue.asInt());//getValue.asStr();
     Serial.print ("SM"+ valorV1 +"E");

// *******************************************
// **************Server management**************
// ********************************************
void handleRootPath() {            //Handler for the rooth path
           // ******************************************************************************************
           //***********  OJO esto es necesario para que no haga reboot cada ciertas horas   ***********
           // ******************************************************************************************
              time_date=NTP.getTimeDateString ();                   
              String req = server.argName(0);               
            // Match the request 
            if (req=="calibracion") {   //envia trama con char "C" al PIC para ponerlo en modo calibracion
                      String cal_char = "C";
                      Serial.print ("S"+cal_char+"E");         
            else if (req=="movecurtain") {//envia trama con char "M" + openpercentage al PIC para mover persiana
                      Serial.print ("SM"+server.arg(0)+"E");
            else if (req=="movecurtain") {//envia trama con char "R" para resetear la energia del PIC
                      Serial.print ("SR"+server.arg(0)+"E");
            else if (req.indexOf("getvalues") != -1)  {Requestok=true;  } // peticion de lectura de los valores            
            if (Requestok==true) {
                String s="getvalues";
                s+= receivedChars;
                s+= " " + String(Irms_max)  + " " + String(Preal_max);
                //s += "</html>\n";
                server.send(200, "text/plain", s);


there are too much going on your code. if you are able to get output on serial monitor then add #define CAYENNE_DEBUG to see what is causing the disconnect.



At a quick glance everything looks ok to me. Usually resets and connection issues are due to delays that are too long or loops that are stuck in an infinite loop. You don’t have either of those so as Shramik said you should enable debug to get some more info as to what is happening when the device crashes.

1 Like