Must restart one time per 24h

I have a "pretty" simple system, a feeder for my fish, with web interface

But I must power off each day.

Any Idea why this happens?

Runs on ESP32 WROOM module + a SSR relay

start/stop time of day
feeding interval
feeding pause

image

The code:

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <TimeLib.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <Preferences.h>
#include <PubSubClient.h>

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

WebServer server(80);

int ssrPin = 14;  // Pin number for the LED

// timing
int runtime     = 2;   // Default runtime in seconds
int waitTime    = 15;  // 1800 = 30 min Default wait time in seconds
int startHour   = 07;  // Default start hour
int startMinute = 0;   // Default start minute
int stopHour    = 20;  // Default stop hour
int stopMinute  = 0;   // Default stop minute
int setssr      = 5;   // default tid knappen mater i sekund

unsigned long previousMillis = 0;
unsigned long currentMillis;
bool ledState = false;

Preferences preferences;
WiFiUDP udp;
NTPClient timeClient(udp, "no.pool.ntp.org");

WiFiClient espClient;
PubSubClient client(espClient);

// Functions
void handleRoot();
void handleStopTime();
void handleStartTime();
void handleWaitTime();
void handleRuntime();
void loadStoredData();
void storeData();
void printCurrentTime();

String formatTime(int hour, int minute) {
  String formattedTime = "";
  if (hour < 10) {
    formattedTime += "0";
  }
  formattedTime += String(hour);
  formattedTime += ":";
  if (minute < 10) {
    formattedTime += "0";
  }
  formattedTime += String(minute);
  return formattedTime;
}

//##########################  HA    ######################################

//Variable to send float to HA
float forer = 0;
float ntp = 0;

// create a character arrays to store the string to mqtt
char materMsg[10] = {"Mater"}; // sender en tekst
char ntpMsg[10] = {"NTP Error"};
//float materMsg = 1; // sender en tekst
//float ntpMsg = 1;

// mqtt server
const char* mqtt_username   = "xx";        // HA MQTT username
const char* mqtt_password   = "xx";      // HA MQTT password
const char* mqtt_clientID   = "xx";              // HA MQTT client ID, må være unikt pr IoT

//topics Home Assistant
const char* per_mater_topic = "perMater";
const char* npt_error_topic = "ntpError";

// topic YAML
#define materTopic    "materPer" //MQTT Denne er definert i Home Assistant -> File Editor -> configuration.yaml
#define errorNtpTopic "errorNtp"  //MQTT Denne er definert i Home Assistant -> File Editor -> configuration.yaml


void setup() {
  pinMode(ssrPin, OUTPUT);
  digitalWrite(ssrPin, LOW);

  Serial.begin(115200);
  delay(10);
  Serial.println("Foringsautomaten Per, versjon 16");
  Serial.println("Vent....");

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Kobler til WiFi ");
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Koblet til WiFi");
  Serial.print("IP adresse å skrive inn i nettleser: ");
  Serial.println(WiFi.localIP());

  client.setServer("192.168.0.60", 1883);    // MQTT server og port på Leia

  timeClient.begin();
  timeClient.setTimeOffset(2 * 3600);  // Set time offset for Norway (2 hours ahead of UTC)

  loadStoredData();

  server.on("/", handleRoot);
  server.on("/runtime", handleRuntime);
  server.on("/waittime", handleWaitTime);
  server.on("/starttime", handleStartTime);
  server.on("/stoptime", handleStopTime);
  server.on("/buttonClick", handleButtonClick);
  server.begin();   //webserver
  Serial.println("Webserver 'Foringsautamaten Per' er starta");
  delay(500);
  Serial.print(startHour);
  Serial.print(":");
  Serial.println(startMinute);
  Serial.print(stopHour);
  Serial.print(":");
  Serial.println(stopMinute);
  Serial.println("Foringstider lastet fra minnet");
  Serial.println();
}

void loop() {
  timeClient.update();
  server.handleClient();   //webserver
  currentMillis = millis();

  if (currentMillis % 30000 == 0) {
    printCurrentTime();
  }

  // Set the current time based on the NTP time
  setTime(timeClient.getEpochTime());

  /* MQTT if client was disconnected then try to reconnect again */
  if (!client.connected()) {
    while (!client.connected()) {
      if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
        Serial.println("MQTT koblet opp!");
        delay(1000);
      } else {
        Serial.print("Feila, MQTT rc = ");
        Serial.println(client.state());
        snprintf(ntpMsg, 10, "%.1f", ntp);
        client.publish(errorNtpTopic, ntpMsg);
        Serial.print("ntpMsg: ");
        Serial.println(ntpMsg);
      }
    }
  }
  client.loop();

  if (ledState && (currentMillis - previousMillis >= runtime * 1000)) {
    digitalWrite(ssrPin, LOW);
    ledState = false;
    previousMillis = currentMillis;
    Serial.println("Vent ");
  }

  if (!ledState && (currentMillis - previousMillis >= waitTime * 1000)) {
    // Check if the current time is within the start and stop time range
    int currentHour = hour();
    int currentMinute = minute();
    if (currentHour > startHour || (currentHour == startHour && currentMinute >= startMinute)) {
      if (currentHour < stopHour || (currentHour == stopHour && currentMinute < stopMinute)) {
        digitalWrite(ssrPin, HIGH);
        ledState = true;
        previousMillis = currentMillis;
        //Serial.println("Forer koien");
        snprintf(materMsg, 10, "%.1f", forer);
        client.publish(materTopic, materMsg);
        Serial.print("Forer koien, materMSG: ");
        Serial.println(materMsg);
      }
    }
  }
}

you must power off, ok. but you not say why ?
pls, go to Arduino IDE, right click on text on select "Copy for Forum", come back to forum, press "edit post", delete entire code, right click and select "paste", press "save changes" field.

4 Likes

Thanks for info

You ask for reason I need to power off. Because, web server goes offline, and the feeder don't feed

Are you trying to call a new timestamp every microsecond? how quick will your server banned from ntp.org?

DHCP renewal causes failure elsewhere in the code? Maybe try a static IP and see if anything changes.

Why not use a RTC chip and update it say every week. Depends on your accuracy requirement. Some are good to a few seconds a month. From what I can determine if the internet goes down so does your system.

ESP32 has a built-in RTC. It can be set to periodically update from NTP in the background with no further action from the user and no additional libraries. The update period is set settable ... once every few hours is more than often enough. The update method can be set to a "smooth" mode so there are no big jumps after the update takes place and the time value from RTC readings is always monotonic. Finally, ESP32 supports standard POSIX time functions without any additional libraries.

1 Like

Thanks!

This is a good point, I will reduce the update interval and see what's happening.

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