electronicsguy/ESP8266

nodemcu is hanging after one day ?!!

Opened this issue · 3 comments

im using nodemcu and im try to connect my esp8266 to google sheet to
read and write to the sheet.
im using arduino ota to update my code.
the software is working fine for only one day and half for maximum
period of time and then my nodemcu hang and no serial data printed or
code execution except the arduino ota.
i have this issue one month ago i need your help please.

Welcome to HTTPSRedirect! Please provide enough info to debug the issue.

#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"
#include <DNSServer.h>
#include <espnow.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>
#include "DebugMacros.h"
#include <ESPAsyncWiFiManager.h>
#include <EEPROM.h>
#include <ArduinoJson.h> // https://arduinojson.org/ or install via Arduino library manager
#include "file.h"
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
void wifiSetup (void){
//read configuration from FS json
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);

    configFile.readBytes(buf.get(), size);
    DynamicJsonDocument jsonBuffer(1024);
    JsonObject json = jsonBuffer.as<JsonObject>();
    serializeJson(json, Serial);
    //json.printTo(Serial);
    if (!json.isNull()) {
      Serial.println("\nparsed json");
      strcpy(userkey, json["userkey"]);
    } else {
      Serial.println("failed to load json config");
    }
  }   

} else {
uint32_t start_time1 = millis();
Serial.println("delay started ");
Serial.println("failed to mount FS");
while((millis()-start_time1) < 70000)//sample for 1000ms
{
Serial.println(".");
};
}
//end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
AsyncWiFiManagerParameter custom_userkey("userkey", "Mobile APP UserKey", userkey, 40);
//Local intialization. Once its business is done, there is no need to keep it around
AsyncWiFiManager wifiManager(&webServer,&dnsServer);

//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);

//set static ip
//wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

//add all your parameters here
wifiManager.addParameter(&custom_userkey);
//reset settings - for testing
//wifiManager.resetSettings();
//set minimu quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("xxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxx")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}else{
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(userkey, custom_userkey.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument jsonBuffer(1024);
JsonObject json = jsonBuffer.to();
json["userkey"] = userkey;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
//json.printTo(Serial);
serializeJson(jsonBuffer, Serial);
serializeJson(jsonBuffer, configFile);
//json.printTo(configFile);
configFile.close();
//end save
wifiPASSWORD = WiFi.psk();
wifiSSID = String(WiFi.SSID());
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
EEPROM.write(119, user_id.length() + 1);
EEPROM.commit();
EEPROM.write(319, wifiPASSWORD.length() + 1);
EEPROM.commit();
wifiPASSWORD.toCharArray(wifiSETUP.wifiPASSWORD5,40);
for( int i=0 ; i<=user_id.length() + 1 ; i++)
{
delay(100);
EEPROM.write(320+i, wifiSETUP.wifiPASSWORD5[i] );
}
EEPROM.commit();
EEPROM.write(419, wifiSSID.length() + 1);
EEPROM.commit();
wifiSSID.toCharArray(wifiSETUP.wifiSSID5,40);
for( int i=0 ; i<=user_id.length() + 1 ; i++)
{
delay(100);
EEPROM.write(420+i, wifiSETUP.wifiSSID5[i] );
}
EEPROM.commit();
}
webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", myESP8266page); });
webServer.onNotFound([](AsyncWebServerRequest *request)
{ request->send(404, "text/html", myNotFoundPage); });
AsyncElegantOTA.begin(&webServer); // Start ElegantOTA
webServer.begin();
Serial.println("FOTA server ready!");
Serial.println("local ip");
Serial.println(WiFi.localIP());
loopEnable = true;
}
}
void feedbackSensorReadings(void){
float sensor_max1;
sensor_max1 = getMaxValue1();
if (sensor_max1<=10)
{
sensor_max1 = 0;
}else if (sensor_max1>10)
{
sensor_max1 = 1;
}
RGBpower1f = String(sensor_max1);
Serial.print("RGBpower1f = ");
Serial.println(RGBpower1f);
}
int getMaxValue1()
{
float sensorValue1; //value read from the sensor
float sensorMax1 = 0;
uint32_t start_time1 = millis();
while((millis()-start_time1) < 250)//sample for 1000ms
{
sensorValue1 = analogRead(FEEDBACKSENSOR1);
if (sensorValue1 > sensorMax1)
{
sensorMax1 = sensorValue1;
}
}
return sensorMax1;
}
String IpAddressToString(const IPAddress& ipAddress) {
return String(ipAddress[0]) + String(".") +
String(ipAddress[1]) + String(".") +
String(ipAddress[2]) + String(".") +
String(ipAddress[3]) ;
}
void setup() {
Serial.begin(9600);
pinMode(D4, OUTPUT);
pinMode(green, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(switchButton, OUTPUT);
analogWrite(red, EEPROM.read(151));
analogWrite(green, EEPROM.read(152));
analogWrite(blue, EEPROM.read(153));
digitalWrite(switchButton, EEPROM.read(154));
Serial.println(EEPROM.read(150));
Serial.println(EEPROM.read(151));
Serial.println(EEPROM.read(152));
Serial.println(EEPROM.read(153));
Serial.println(EEPROM.read(154));
wifiSetup();
pinMode(Led, OUTPUT);
digitalWrite(Led, LOW);
Serial.println();
ip = IpAddressToString( WiFi.localIP() );
macAddress = String(WiFi.macAddress());
counter = 0;
}
void loop() {
if (loopEnable == true)
{
digitalWrite(D4,HIGH);
fullData.toCharArray(fullDataArr,14);
dot = 0;
redValue = "";
greenValue = "";
blueValue = "";
RGBpower1 = "";
for( int i=0 ; i<=fullData.length() ; i++)
{
if (String(fullDataArr[i]) == ".")
{
dot = dot + 1;

}    
else if ( fullDataArr[i] >= 0 || fullDataArr[i] <= 255 ){
  if (dot == 0)
  {
    redValue +=  String(fullDataArr[i]);
  }else if (dot == 1)
  {
    greenValue +=  String(fullDataArr[i]);    
  }else if (dot == 2)
  {
    blueValue +=  String(fullDataArr[i]);      
  }else if (dot == 3)
  {
    RGBpower1 += String(fullDataArr[i]);
  }
}

}
if (RGBpower1 == "1")
{
digitalWrite(switchButton, HIGH);
Serial.println("RGB SWITCH on");
}else if (RGBpower1 == "0")
{
digitalWrite(switchButton, LOW);
Serial.println("RGB SWITCH oFF");
}
EEPROM.write(151, redValue.toInt());
// EEPROM.commit();
analogWrite(red,redValue.toInt());
Serial.print("red value = ");
Serial.println(redValue.toInt());
analogWrite(green,greenValue.toInt());
Serial.print("green value = ");
Serial.println(greenValue.toInt());
EEPROM.write(152, greenValue.toInt());
// EEPROM.commit();
EEPROM.write(153, blueValue.toInt());
// EEPROM.commit();
analogWrite(blue,blueValue.toInt());
Serial.print("blue value = ");
Serial.println(blueValue.toInt());
EEPROM.write(154, RGBpower1.toInt());
EEPROM.commit();
Serial.print("RGBpower value = ");
Serial.println(RGBpower1.toInt());
counter = counter + 1;
// counter++;
Serial.print("COUNTER = ");
Serial.println(counter);
if (counter == 100)
{
loopCounter = loopCounter + 1;
counter = 0;
}
feedbackSensorReadings();
payload = payload_base + """ + String(ESP.getFreeHeap()) + "," + String(ESP.getFreeContStack()) + "," + counter + "," + String(ESP.getMaxFreeBlockSize()) + "," + ip + "," + String(ESP.getHeapFragmentation()) + "," + loopCounter + "," + serialNumber + "," + RGBpower1f + ""}";
digitalWrite(D4,LOW);
readingData2();
}
}
void readingData2(void)
{
static int error_count = 0;
static int connect_count = 0;
const unsigned int MAX_CONNECT = 20;
static bool flag = false;
//digitalWrite(D0,HIGH);
if (!flag){
free_heap_before = ESP.getFreeHeap();
free_stack_before = ESP.getFreeContStack();
client = new HTTPSRedirect(httpsPort);
client->setInsecure();
flag = true;
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");
}
if (client != nullptr){
if (!client->connected()){
client->connect(host, httpsPort);
//flag = false;
}
}
else{
DPRINTLN("Error creating client object!");
error_count = 5;
}
if (connect_count > MAX_CONNECT){
//error_count = 5;
connect_count = 0;
flag = false;
delete client;
return;
}
if (!(client->reConnectFinalEndpoint())){
++error_count;
DPRINT("Error-count while connecting: ");
DPRINTLN(error_count);
}
else
{
Serial.println("reconecteeeeeeeeeeeeeeeeeeeeeeed");
error_count = 0;
}
if (rowID == 0)
{
Serial.print("GET Google sheet Row ID: ");
payload5 = "";
while(String(payload5) != serialNumber)
{
Serial.println(cellAddress5 + String(i) );
if (client->GET(url5 + String(i), host)){
//get the value of the cell
payload5 = client->getResponseBody();
payload5.trim(); /// temperature value
Serial.println(payload5);
//++connect_count;
if (String(payload5) == serialNumber)
{
rowID = i;
}
else{
i++;
}
}
};
}
if (client->GET(url6 + String(rowID), host)){
//get the value of the cell
payload6 = client->getResponseBody();
payload6.trim(); /// temperature value
//Serial.println(payload2);
fullData = payload6;
Serial.print("fullDataValue = ");
Serial.println(fullData);
// Serial.println(fullData.length());
++connect_count;
}
// Publish data to Google Sheets
Serial.println("Publishing data...");
Serial.println(payload);
if(client->POST(url, host, payload)){
}
else{
// do stuff here if publish was not successful
Serial.println("Error while connecting");
}
if (error_count > 3){
Serial.println("Halting processor...");
delete client;
client = nullptr;
Serial.printf("Final free heap: %u\n", ESP.getFreeHeap());
Serial.printf("Final stack: %u\n", ESP.getFreeContStack());
// Serial.flush();
ESP.reset();
}
// delay(4000);
}

here is my code
my code is working well for 2 days and then my nodemcu is hanging except ota link to update the binnary code