ropg / ezTime

ezTime — pronounced "Easy Time" — is a very easy to use Arduino time and date library that provides NTP network time lookups, extensive timezone support, formatted time and date strings, user events, millisecond precision and more.
MIT License
336 stars 93 forks source link

SetEvents not working as expected #77

Closed stephensaid closed 4 years ago

stephensaid commented 4 years ago

Firstly, thank you for this library. I am finding it very useful in my current project.

I must be doing something very wrong as my setEvent is not working as expected. I have here an example sketch which should output to Serial a message every 10 seconds.

Any help is greatly appreciated.

#include <ezTime.h>
#include <WiFi.h>

// Wifi credentials
const char* wifiSsid     = "SSID";
const char* wifiPassword = "Wifi_password";

int weatherUpdateFrequency = 10000; // 10 seconds
Timezone myTZ;

void setup() {
  Serial.begin(115200);

  Start_WiFi();
  getInternetTime();

  Serial.print("weatherUpdateFrequency: ");
  Serial.println( weatherUpdateFrequency );

  Serial.print("now(): ");
  Serial.println( now() );

  setEvent(updateWeather, now() + weatherUpdateFrequency);
}

void loop() {
  delay(2000);
  Serial.print("now(): ");
  Serial.println( now() );
  events();
}

void updateWeather() {
  Serial.println("Weather updated");
  setEvent(updateWeather, now() + weatherUpdateFrequency);
}

void getInternetTime() {
  waitForSync();
  myTZ.setLocation(F("mt"));
  Serial.print("Updated internet time: ");
  Serial.println(myTZ.dateTime());
  void setInterval(uint16_t hour = 1); // update internet time every 1 hour
}

int Start_WiFi() {
  int connAttempts = 0;
  Serial.println("\r\nConnecting to: " + String(wifiSsid));
  WiFi.begin(wifiSsid, wifiPassword);

  while ( WiFi.status() != WL_CONNECTED ) {
    unsigned long t = millis();
    while (millis() < t + 500) {  }
    Serial.print(".");
    if (connAttempts > 20) {
      Serial.println("\r\nWiFi failed to connect.");
      return -5;
    }
    connAttempts++;
  }

  Serial.println("\r\nWiFi Connected.");
  return 1;
}
stephensaid commented 4 years ago

OK. Two things:

  1. I did something very stupid. This line

    int weatherUpdateFrequency = 10000; // 10 seconds

    should read:

    int weatherUpdateFrequency = 10; // 10 seconds
  2. Unless now() is prefixed by timezone ( myTZ.now(); ) or the time zone is set to default (myTZ.setDefault(); ), the setEvent was being set in the past (if set to 10 seconds) or in the unexpected future giving the impression that is not working.

If the setEvent is set in the past, then it fires continuously... of course, that is because we are resetting the event in the past again when firing the function being called.

A combination of the above two solved my issue.