Esp32 or Esp8266 Wemos resetting every several hours

Hi all,
I am trying to read signals from a machine using ESP32 WRoom-32 and send the data to a Mqtt server and write it to SD card. Everything work perfect for several hours until the ESP32 reset by itself for an unknown reason.
I tried ESP8266 and it work more hours but it reset by itself too. i tried to supply it with several voltage without any improvement.
This is the error message i always get

Connecting to linksys
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:10124
load:0x40080400,len:5856
entry 0x400806a8
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:10124
load:0x40080400,len:5856
entry 0x400806a8

Connecting to linksys
..ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:10124
load:0x40080400,len:5856
entry 0x400806a8

And here is my code

#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <SD.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
ESP8266WebServer server(80);
#else
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
WebServer server(80);
#endif


#define DBG_OUTPUT_PORT Serial

const char* ssid = "ssid";
const char* password = "password";


const char* host = "espM26";

// fixed ip code 
IPAddress local_IP (192,168,88,191);
// Set your Gateway IP address
IPAddress gateway (192,168,88,2);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);   //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
// end fixed ip -----------

//WebServer server(80);

static bool hasSD = false;
File myFile;
String logpath = "/logfile.txt";  //without "/" for 8266

volatile unsigned long count = 0;
volatile unsigned long hourlycount = 0;
volatile unsigned long prior_count = 0;
volatile unsigned long new_count = 0;
unsigned long start_count = 0;
unsigned long push_stop_count =0;
unsigned long warp_count =0;
unsigned long weft_count =0;

bool sendHourly_flag = true;
const int minute = 0; // the minet to send hourly

bool is_running = false;
int rpm_pin = 25; //D2  32-4
int start_pin = 33; //D1   32-34     8266- 5
int filling_pin = 35; //D4  32-35      8266-16
int warp_pin = 32; //D3     32-32      8266- 2
int loomnumber = 26; // loomnumber
unsigned long postidno = 0; // counter for post
String egtime_Now = "";
// int sel_pin = 13; //
const unsigned long interval = 1UL * 60UL * 60UL * 1000UL; // every 1 h
const unsigned long quarter_interval = (1UL * 60UL * 60UL * 1000UL)/4; // every 15 min
//volatile unsigned long currentMillis = millis();
volatile uint32_t currentMillis = millis();
//volatile unsigned long oldMillis = 00;
volatile uint32_t oldMillis = 00;

const char* mqtt_server = "192.168.88.21";       // server name or IP
const char* mqtt_user = "admin";           // username
const char* mqtt_password = "admin" ;  // password

const char* topic = "Loom26/data" ;                  //Mqtt Topic

long lastReconnectAttempt = 0;
WiFiClient wificlient;
PubSubClient client(wificlient);

// Define NTP Client to get time
WiFiUDP ntpUDP;
// NTPClient timeClient(ntpUDP, "192.168.1.183", utcOffsetInSeconds);
 NTPClient timeClient(ntpUDP,"africa.pool.ntp.org", 7200 , 60000);
//  NTPClient timeClient(ntpUDP,"192.168.1.183", 7200 , 60000);

#define SERVER_IP "192.168.88.21/www"
String apiKeyValue = "tPmAT5Ab3j7F9";
String bontApiValue ="bonTotolala250ASPosible";



ICACHE_RAM_ATTR void pulse () {
  
    static unsigned long last_interrupt_time = 0;
   volatile uint32_t interrupt_time = millis();
   // If interrupts come faster than 200ms, assume it's a bounce and ignore
   if (interrupt_time - last_interrupt_time > 50) 
   {
         // do your thing
      
         
        count = count + 1;
        hourlycount = hourlycount + 1;
      
  }
   last_interrupt_time = interrupt_time;
  
}

String dateNow(){
  timeClient.update();
  timeClient.update();
  timeClient.update();
    time_t epochTime = timeClient.getEpochTime();
    struct tm *ptm = gmtime ((time_t *)&epochTime); 
    int monthDay = ptm->tm_mday; 
    int currentMonth = ptm->tm_mon+1;
    int currentYear = ptm->tm_year+1900;
  String currentDate = String(monthDay) + ":" + String(currentMonth) + ":" + String(currentYear) + " "  ;
  String date_Now = "";
  date_Now = String(currentYear) + "-" + (currentMonth < 10 ? "0" : "") + String(currentMonth) + "-" + (monthDay < 10 ? "0" : "") + (String(monthDay));
  return date_Now ;
}

String dateTimeNow() {
  String date_formated = dateNow();
  String currentTime = timeClient.getFormattedTime();
  String date_Time_now =   "";
  date_Time_now = String(date_formated) + " " + String(currentTime) ;
  return date_Time_now ;
  
}
#ifdef ESP8266

#else
// ********S****SD Card handlers for 32*********

void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
    Serial.printf("Listing directory: %s\n", dirname);

    File root = fs.open(dirname);
    if(!root){
        Serial.println("Failed to open directory");
        return;
    }
    if(!root.isDirectory()){
        Serial.println("Not a directory");
        return;
    }

    File file = root.openNextFile();
    while(file){
        if(file.isDirectory()){
            Serial.print("  DIR : ");
            Serial.println(file.name());
            if(levels){
                listDir(fs, file.name(), levels -1);
            }
        } else {
            Serial.print("  FILE: ");
            Serial.print(file.name());
            Serial.print("  SIZE: ");
            Serial.println(file.size());
        }
        file = root.openNextFile();
    }
}

void createDir(fs::FS &fs, const char * path){
    Serial.printf("Creating Dir: %s\n", path);
    if(fs.mkdir(path)){
        Serial.println("Dir created");
    } else {
        Serial.println("mkdir failed");
    }
}

void removeDir(fs::FS &fs, const char * path){
    Serial.printf("Removing Dir: %s\n", path);
    if(fs.rmdir(path)){
        Serial.println("Dir removed");
    } else {
        Serial.println("rmdir failed");
    }
}

void readFile(fs::FS &fs, const char * path){
    Serial.printf("Reading file: %s\n", path);

    File file = fs.open(path);
    if(!file){
        Serial.println("Failed to open file for reading");
        return;
    }

    Serial.print("Read from file: ");
    while(file.available()){
        Serial.write(file.read());
    }
    file.close();
}

void writeFile(fs::FS &fs, const char * path, const char * message){
    Serial.printf("Writing file: %s\n", path);

    File file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("WriteFile Failed to open file for writing");
        return;
    }
    if(file.print(message)){
        Serial.println("File written");
    } else {
        Serial.println("Write failed");
    }
    file.close();
}

void appendFile(fs::FS &fs, const char * path, const char * message){
    Serial.printf("Appending to file: %s\n", path);

    File file = fs.open(path, FILE_APPEND);
    if(!file){
        Serial.println("Failed to open file for appending");
        return;
    }
    if(file.print(message)){
        Serial.println("Message appended");
    } else {
        Serial.println("Append failed");
    }
    file.close();
}

void renameFile(fs::FS &fs, const char * path1, const char * path2){
    Serial.printf("Renaming file %s to %s\n", path1, path2);
    if (fs.rename(path1, path2)) {
        Serial.println("File renamed");
    } else {
        Serial.println("Rename failed");
    }
}

void deleteFile(fs::FS &fs, const char * path){
    Serial.printf("Deleting file: %s\n", path);
    if(fs.remove(path)){
        Serial.println("File deleted");
    } else {
        Serial.println("Delete failed");
    }
}

void testFileIO(fs::FS &fs, const char * path){
    File file = fs.open(path);
    static uint8_t buf[512];
    size_t len = 0;
    uint32_t start = millis();
    uint32_t end = start;
    if(file){
        len = file.size();
        size_t flen = len;
        start = millis();
        while(len){
            size_t toRead = len;
            if(toRead > 512){
                toRead = 512;
            }
            file.read(buf, toRead);
            len -= toRead;
        }
        end = millis() - start;
        Serial.printf("%u bytes read for %u ms\n", flen, end);
        file.close();
    } else {
        Serial.println("The Test Failed to open file for reading");
    }


    file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("Failed to open file for writing");
        return;
    }

    size_t i;
    start = millis();
    for(i=0; i<2048; i++){
        file.write(buf, 512);
    }
    end = millis() - start;
    Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end);
    file.close();
}

// ********E****SD Card handlers 32*********
#endif


//---S--web server read handlers

void returnOK() {
  server.send(200, "text/plain", "");
}

void returnFail(String msg) {
  server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path){
  String dataType = "text/plain";
  if(path.endsWith("/")) path += "index.htm";

  if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if(path.endsWith(".htm")) dataType = "text/html";
  else if(path.endsWith(".css")) dataType = "text/css";
  else if(path.endsWith(".js")) dataType = "application/javascript";
  else if(path.endsWith(".png")) dataType = "image/png";
  else if(path.endsWith(".gif")) dataType = "image/gif";
  else if(path.endsWith(".jpg")) dataType = "image/jpeg";
  else if(path.endsWith(".ico")) dataType = "image/x-icon";
  else if(path.endsWith(".xml")) dataType = "text/xml";
  else if(path.endsWith(".pdf")) dataType = "application/pdf";
  else if(path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if(dataFile.isDirectory()){
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
    DBG_OUTPUT_PORT.println("Sent less data than expected!");
  }

  dataFile.close();
  return true;
}

void handleFileUpload(){
  if(server.uri() != "/edit") return;
  HTTPUpload& upload = server.upload();
  if(upload.status == UPLOAD_FILE_START){
    if(SD.exists((char *)upload.filename.c_str())) SD.remove((char *)upload.filename.c_str());
    myFile = SD.open(upload.filename.c_str(), FILE_WRITE);
    DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
  } else if(upload.status == UPLOAD_FILE_WRITE){
    if(myFile) myFile.write(upload.buf, upload.currentSize);
    DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
  } else if(upload.status == UPLOAD_FILE_END){
    if(myFile) myFile.close();
    DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
  }
}

void deleteRecursive(String path){
  File file = SD.open((char *)path.c_str());
  if(!file.isDirectory()){
    file.close();
    SD.remove((char *)path.c_str());
    return;
  }

  file.rewindDirectory();
  while(true) {
    File entry = file.openNextFile();
    if (!entry) break;
    String entryPath = path + "/" +entry.name();
    if(entry.isDirectory()){
      entry.close();
      deleteRecursive(entryPath);
    } else {
      entry.close();
      SD.remove((char *)entryPath.c_str());
    }
    yield();
  }

  SD.rmdir((char *)path.c_str());
  file.close();
}

void handleDelete(){
  if(server.args() == 0) return returnFail("BAD ARGS");
  String path = server.arg(0);
  if(path == "/" || !SD.exists((char *)path.c_str())) {
    returnFail("BAD PATH");
    return;
  }
  deleteRecursive(path);
  returnOK();
}

void handleCreate(){
  if(server.args() == 0) return returnFail("BAD ARGS");
  String path = server.arg(0);
  if(path == "/" || SD.exists((char *)path.c_str())) {
    returnFail("BAD PATH");
    return;
  }
  if(path.indexOf('.') > 0){
    File file = SD.open((char *)path.c_str(), FILE_WRITE);
    if(file){
#ifdef ESP8266
      file.write((const char *)0);
#else
      // TODO Create file with 0 bytes???
      file.write(NULL, 0);
#endif
      file.close();
    }
  } else {
    SD.mkdir((char *)path.c_str());
  }
  returnOK();
}

void printDirectory() {
  if(!server.hasArg("dir")) return returnFail("BAD ARGS");
  String path = server.arg("dir");
  if(path != "/" && !SD.exists((char *)path.c_str())) return returnFail("BAD PATH");
  File dir = SD.open((char *)path.c_str());
  path = String();
  if(!dir.isDirectory()){
    dir.close();
    return returnFail("NOT DIR");
  }
  dir.rewindDirectory();
  server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  server.send(200, "text/json", "");
  WiFiClient client = server.client();

  server.sendContent("[");
  for (int cnt = 0; true; ++cnt) {
    File entry = dir.openNextFile();
    if (!entry)
    break;

    String output;
    if (cnt > 0)
      output = ',';

    output += "{\"type\":\"";
    output += (entry.isDirectory()) ? "dir" : "file";
    output += "\",\"name\":\"";
#ifdef ESP8266
    output += entry.name();
#else
    // Ignore '/' prefix
    output += entry.name()+1;
#endif
    output += "\"";
    output += "}";
    server.sendContent(output);
    entry.close();
 }
 server.sendContent("]");
 // Send zero length chunk to terminate the HTTP body
 server.sendContent("");
 dir.close();
}


void handleNotFound(){
  if(hasSD && loadFromSdCard(server.uri())) return;
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  DBG_OUTPUT_PORT.print(message);
}

void wifisetup(){
   // Configures static IP address
  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }
  
  WiFi.begin(ssid, password);
  DBG_OUTPUT_PORT.print("Connecting to ");
  DBG_OUTPUT_PORT.println(ssid);

  // Wait for connection
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 50) {//wait 10 seconds
    delay(200);
    Serial.print(".");
  }
  if(i == 21){
    DBG_OUTPUT_PORT.print("Could not connect to");
    DBG_OUTPUT_PORT.println(ssid);
    while(1) delay(500);
  }
  DBG_OUTPUT_PORT.print("Connected! IP address: ");
  DBG_OUTPUT_PORT.println(WiFi.localIP());
}
//*****S*****mqtt functions 
//Reconnect to mqtt server if connection is lost

boolean reconnect() {
  Serial.print("Connecting to MQTT broker ...");
      String clientId = "mqttMachine26-";
    clientId += String(random(0xffff), HEX);
  if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
    // Once connected, publish an announcement...
    //client.publish(topic,"hello world");
    // ... and resubscribe
    client.subscribe(topic);
  }
  Serial.print("ok");
  return client.connected();
}

void callback(char* topic, byte* cbpayload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)cbpayload[i]);
  }
  Serial.println();
}

//****E *****mqtt functions

void setup(void){
  DBG_OUTPUT_PORT.begin(115200);
  DBG_OUTPUT_PORT.setDebugOutput(true);
  DBG_OUTPUT_PORT.print("\n");

//configTime(String("EET-2"), String("192.168.1.183"));

   wifisetup();
   
   client.setServer(mqtt_server, 1883);    // Configure MQTT connection, change port if needed.
   client.setCallback(callback);

  if (MDNS.begin(host)) {
    MDNS.addService("http", "tcp", 80);
    DBG_OUTPUT_PORT.println("MDNS responder started");
    DBG_OUTPUT_PORT.print("You can now connect to http://");
    DBG_OUTPUT_PORT.print(host);
    DBG_OUTPUT_PORT.println(".local");
  }
  
  server.on("/list", HTTP_GET, printDirectory);
  server.on("/edit", HTTP_DELETE, handleDelete);
  server.on("/edit", HTTP_PUT, handleCreate);
  server.on("/edit", HTTP_POST, [](){ returnOK(); }, handleFileUpload);
  server.onNotFound(handleNotFound);

  server.begin();
  DBG_OUTPUT_PORT.println("HTTP server started");

  if (SD.begin(SS)){
     DBG_OUTPUT_PORT.println("SD Card initialized.");
     hasSD = true;
  }
//---E--web server read handlers
//*** S sd 32 ****
if(!SD.begin()){
        Serial.println("Card Mount Failed");
        return;
    }
    uint8_t cardType = SD.cardType();

    if(cardType == CARD_NONE){
        Serial.println("No SD card attached");
        return;
    }

    Serial.print("SD Card Type: ");
    if(cardType == CARD_MMC){
        Serial.println("MMC");
    } else if(cardType == CARD_SD){
        Serial.println("SDSC");
    } else if(cardType == CARD_SDHC){
        Serial.println("SDHC");
    } else {
        Serial.println("UNKNOWN");
    }
//*** E sd 32 *****

// -----------------
  timeClient.begin();

  timeClient.update();

  Serial.println(timeClient.getFormattedTime());
  
String time_now = (timeClient.getFormattedTime()); // variable to hold time as a string
  
  Serial.print("\r\nConnected: local ip address is http://");
  Serial.println(WiFi.localIP());
  Serial.println();


  pinMode (rpm_pin, INPUT); // RPM Signal using Interupt
  pinMode (start_pin, INPUT); // Start/Stop
  pinMode(filling_pin, INPUT);  // filling Stop
  pinMode(warp_pin, INPUT);  // Warp Stop
  // pinMode(sel_pin,INPUT);   // selvedge stop
  //NVIC_SET_PRIORITY(IRQ_PORTA,0);
 // attachInterrupt(4, ISR, CHANGE);
  attachInterrupt (digitalPinToInterrupt(rpm_pin), pulse, FALLING);
  //attachInterrupt (digitalPinToInterrupt(rpm_pin), pulse, RISING);

  lastReconnectAttempt = 0;
}

void  addtoSDfile(String logpath , String payload){
      
    //  myFile = SD.open(logpath.c_str(), FILE_APPEND);   
    #ifdef ESP8266
      myFile = SD.open(logpath.c_str(), FILE_WRITE);
      if(!myFile){
          myFile = SD.open(logpath.c_str(), FILE_WRITE);
        }
      myFile.print(payload.c_str());
      // delay (1000);
      myFile.close();
    #else
        myFile = SD.open(logpath.c_str(), FILE_APPEND);
      if(!myFile){
         // writeFile(SD, logpath.c_str() , payload.c_str());
          writeFile(SD, logpath.c_str() , payload.c_str());
        }else {
          appendFile(SD, logpath.c_str() , payload.c_str());
        }
     #endif
    }
    
String bignum(int num){
  if (num <10){
    return ("00000" + String(num));
    }else if (num <100 and num >=10){
      return ("0000" + String(num));
    }else if (num <1000 and num >=100){
      return ("000" + String(num));
    }else if (num <10000 and num >=1000){
      return ("00" + String(num));
    }else if (num <100000 and num >=10000){
      return ("0" + String(num));
    }else{
      return (String(num));
    }
  }
    


// flags----
String payload = "";
String h_payload = "";
String payload_start = "";
String mqpayload = "";
String mqpayload_start = "" ;
bool mqpayload_wretten = true ;
int h_payload_wretten = 2 ; //0 stopping  1 working  2 noHourly reading
String h_mqpayload = "";

void loop(void){
  server.handleClient();

      if (WiFi.status() == WL_CONNECTED) {

  
      timeClient.update();
      timeClient.update();
      timeClient.update();
      
    new_count = count;
    if (new_count != prior_count) {
      Serial.println(new_count);
      prior_count =  new_count;
      delay (100); // print at reasonable speed
    }

    if (is_running == false){
           if (!client.connected()) {
          volatile uint32_t now = millis();
          if (now - lastReconnectAttempt > 5000) {
            lastReconnectAttempt = now;
            // Attempt to reconnect
            if (reconnect()) {
              lastReconnectAttempt = 0;
            }
          }
           }else {
    // Client connected

    client.loop();
    
              if (h_payload_wretten == 0){
                cli();
                client.publish(topic , h_mqpayload.c_str());
                client.subscribe(topic);
                h_mqpayload = "";
                addtoSDfile(logpath , h_payload);
                h_payload_wretten = 2 ;
                h_payload = "";
                Serial.println("Writting hourly stopping");
                sei();
              }
      
              if (mqpayload_wretten == false){
                cli();
                client.publish(topic , mqpayload_start.c_str());
                client.subscribe(topic);
                //delay(20);
                
                if (h_payload_wretten == 1){
                client.publish(topic , h_mqpayload.c_str());
                client.subscribe(topic);
                // h_payload_wretten = "yes" ;
                Serial.println("Writting hourly working mqtt");
                h_mqpayload = "";
              }
              
                client.publish(topic , mqpayload.c_str());
                client.subscribe(topic); 
                Serial.println(mqpayload + "  >>>>>>   published to broker");
                //delay(10);
                mqpayload_wretten = true ;
                addtoSDfile(logpath , payload_start);
                //delay(10);
                
                if (h_payload_wretten == 1){
                addtoSDfile(logpath , h_payload);
                Serial.println("Writting hourly working SD");
                h_payload_wretten = 2 ;
                h_payload = "";
              }
              
                addtoSDfile(logpath , payload);
                sei();
                }
    }
    }

    if ((digitalRead(start_pin) == HIGH) and (is_running == false)) {
   //   noInterrupts();
      postidno += 1;
      count = 0;
      start_count = count;
      // Write in SD logfile
      egtime_Now  =  String(dateTimeNow());  
      payload_start = ("," + bignum(postidno) + "," + egtime_Now + "," + "Machine   Start" + "," + bignum(start_count) + "," + "\n" );
      mqpayload_start = "{\"egtime\":\"" + String(egtime_Now) + "\", \"loomnumber\":\"" + String(loomnumber) + "\", \"pickno\":\"" + String(start_count) + "\", \"status\":\"" + String("Machine Start") + "\", \"postidno\":\"" + String(postidno)  + "\" }";
      // mqpayload_wretten = false ;
      // addtoSDfile(logpath , payload);
    
      Serial.println("Machine Start");
      is_running = true;
      count = 0;
      Serial.print(" ");
      
  //    stop_bont_flag = false;
    return;
    }

    if ((digitalRead(filling_pin) == HIGH ) and (is_running == true)) {
     //noInterrupts();
      weft_count = count;
      postidno += 1;      
 //     f_stop_bont_count += 1;
      egtime_Now  =  String(dateTimeNow());  
      payload = ("," + bignum(postidno) + "," + egtime_Now + "," + "Filling    Stop" + "," + bignum(weft_count) + "," + "\n" ); 
      mqpayload = "{\"egtime\":\"" + String(egtime_Now) + "\", \"loomnumber\":\"" + String(loomnumber) + "\", \"pickno\":\"" + String(weft_count) + "\", \"status\":\"" + String("Filling Stop") + "\", \"postidno\":\"" + String(postidno)  + "\" }";
      mqpayload_wretten = false ;   
           // Write in SD logfile
      // addtoSDfile(logpath , payload);   
      Serial.print("filling Stop  Picks = ");
      Serial.println(weft_count);
//      count_bont_count = count_bont_count + count ;
      count = 0;
      is_running = false;
      return;     
    }
    if ((digitalRead(warp_pin) == HIGH) and (is_running == true)) {
      //noInterrupts();
      warp_count = count;
      postidno += 1;
      
//      w_stop_bont_count += 1;
      egtime_Now  =  String(dateTimeNow());
       payload = ("," + bignum(postidno) + "," + egtime_Now + "," + "Warp       Stop" + "," + bignum(warp_count) + "," + "\n" );
       mqpayload = "{\"egtime\":\"" + String(egtime_Now) + "\", \"loomnumber\":\"" + String(loomnumber) + "\", \"pickno\":\"" + String(warp_count) + "\", \"status\":\"" + String("Warp Stop") + "\", \"postidno\":\"" + String(postidno)  + "\" }";
       mqpayload_wretten = false ;   
           // Write in SD logfile
           
      // addtoSDfile(logpath , payload);
     
      Serial.print("Warp Stop  Picks = ");
      Serial.println(warp_count);
  //    count_bont_count = count_bont_count + count ;
      count = 0;
      is_running = false;
      Serial.print("  "); 
      return;
    }


    if ((digitalRead(start_pin) == LOW) and (is_running == true)) {
      //noInterrupts();
      push_stop_count = count;
      postidno += 1;
      
//      pb_top_bont_count +=1;
      egtime_Now  =  String(dateTimeNow());
      payload = ("," + bignum(postidno) + "," + egtime_Now + "," + "PushButton stop" + "," + bignum(push_stop_count) + "," + "\n" );
      mqpayload = "{\"egtime\":\"" + String(egtime_Now) + "\", \"loomnumber\":\"" + String(loomnumber) + "\", \"pickno\":\"" + String(push_stop_count) + "\", \"status\":\"" + String("PushButton stop") + "\", \"postidno\":\"" + String(postidno)  + "\" }";
      mqpayload_wretten = false ;   
           // Write in SD logfile
           
      // addtoSDfile(logpath , payload);

      Serial.print("push button stop  Picks = ");
      Serial.println(push_stop_count);
//      count_bont_count = count_bont_count + count ;
      count = 0;
      is_running = false;
      return;    
    }    
    // update the time every 15 min
    if ( millis() - oldMillis >= quarter_interval) {
      timeClient.update();
      Serial.println(timeClient.getFormattedTime());
      sendHourly_flag = true;
    //   stop_bont_flag = false;
      oldMillis = millis();
    }
   
    // send the fillings no hourly

     if(timeClient.isTimeSet()) {
           if ((sendHourly_flag == true) and (minute == timeClient.getMinutes())) {
              postidno += 1;
      
      timeClient.update();
      Serial.println(timeClient.getFormattedTime());
      egtime_Now  =  String(dateTimeNow());
      h_payload = (h_payload + "," + bignum(postidno) + "," + egtime_Now + "," + "hourly        0" + "," + bignum(count) + "," + "\n" );
      h_mqpayload = "{\"egtime\":\"" + String(egtime_Now) + "\", \"loomnumber\":\"" + String(loomnumber) + "\", \"pickno\":\"" + String(count) + "\", \"status\":\"" + String("hourly0") + "\", \"postidno\":\"" + String(postidno)  + "\" }";
              
           // Write in SD logfile
      // addtoSDfile(logpath , payload);
      if (is_running == true){
          h_payload_wretten = 1;
      }else if (is_running == false){
          h_payload_wretten = 0;
           }else{
            Serial.print(" hourly somthing rong in post id " + postidno );
            }
      Serial.print("Hourly status pick no  ");
      Serial.print(count);
      Serial.print("  in Time    ");
      Serial.println(timeClient.getFormattedTime());
      
      hourlycount = 0;
      sendHourly_flag = false;
      
             }
      return;
      }
  }
  else {
    Serial.println("WiFi Disconnected tring to reconnect again");
    wifisetup();
  }
//delay (100);
  
}

WE tried to isolate the EN pin but we got the same error. Also we tried to keep it in the USB to supply it but it didnt make any difference. even tried to tweek the code but nothing improve it.
Thank you for advance.

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

That the reboot does not give a reason, such as an exception code, I'd suspect power.

Post a schematic. Post an image of the project.

Thank you for your reply, Here is the schematic for the circuit diagram we use, the supply is external 5VDC 10A, also we tried to supply with USB cable but we get the same error. We used esp32 and or the wemos esp8266 with the same reset and error.

What is the power source for the sdcard reader ?
What is the voltage at the emitter of the optocouplers when high and disconnected from Wemos ?

the power source we are using is SMPS 5VDC 10A supplying all our components, the voltage is disconnected from the wemos when the optocupler led is off, the voltage goes through the wemos is 3.3v or 3.2 at the pull down resistor.

I was hoping for something overheating somewhere...
A very small "maybe" for a memory leak.

Could the OP take a photo of the project and post the photo in a reply?


Here is an image of it.
I really appreciate your help.

That 2 MCU's running different code would be failing and there is no ESP exception error the issue points to something else other than the ESP32 or ESP8266.

Could you post an underside image?

Did you put any power supply filtering on the board?

Thank you for sharing your thoughts. I have some doubt that the code makes memory leak, because it works perfectly for several hours and rest for unknown reasons. Is there any way to test memory leaking?

Unsigned longs on a ESP32 are 64 bit numbers.

An interrupt for an ESP32 should be in the form of


void IRAM_ATTR onTimer()
{
  BaseType_t xHigherPriorityTaskWoken;
  xEventGroupSetBitsFromISR(eg, OneMinuteGroup, &xHigherPriorityTaskWoken);
} // void IRAM_ATTR onTimer()
// interrupt service routine for WiFi events put into IRAM
void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
{
  switch (event) {
      break;
    default: break;
  }
} // void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
//
void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  memset( x_message.payload, '\0', payloadSize ); // clear payload char buffer
  x_message.topic = ""; //clear topic string buffer
  x_message.topic = topic; //store new topic
  memcpy( x_message.payload, payload, length );
  xQueueOverwrite( xQ_Message, (void *) &x_message );// send data to queue
} // void mqttCallback(char* topic, byte* payload, unsigned int length)
////

Before issuing a WiFi.begin(ssid, password); issue a WiFi.disconnect(). WiFi.disconnect() not only disconnects the WiFi but, and this is important, the WiFI stack gets set back to its default values.

Looks like the reconnect() just assumes a good WiFi connection?

Really serial prints in a callback? Very bad idea.

quicker way of getting data from the mqtt callback

void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  memset( x_message.payload, '\0', payloadSize ); // clear payload char buffer
  x_message.topic = ""; //clear topic string buffer
  x_message.topic = topic; //store new topic
  memcpy( x_message.payload, payload, length );
  xQueueOverwrite( xQ_Message, (void *) &x_message );// send data to queue
} // void mqttCallback(char* topic, byte* payload, unsigned int length)

issue a

MQTTclient.setKeepAlive( 90 ); // setting keep alive to 90 seconds makes for a very reliable connection, must be set before the 1st connection is made.

before making the first mqtt connection.

1 Like
Serial.println(ESP.getFreeHeap());

periodically

Is it a voltage regulator in the image ?

1 Like

Thanks a lot for your comment, I'll try to modify the code as your instructions and, get back to you with the results.
Thanks again.

1 Like

Thanks a lot for your comment, yes it is a voltage regulator, but we disconnected it.
Thanks for the code, I'll try it and get back to you.
Thanks again.

Please explain "

". Such as what does that mean? Removed the Vreg from the MCU development board?

Sorry, I mean disconnected the one in the photo we sent, so that vreg in the photo is disabled. Sure we did not remove the verge from the esp32. Sorry for that miss understand.

Can we get a image of the backside of the board?

here is the backside image for the board

1 Like