Which Library for Time operations?

Hallo, I want to run code like this:


  if ((hour() > 19) && (minute() == 0))
  {
    digitalWrite(16, HIGH);
  }

  if ((hour() == 11) && (minute() == 0))
  {
    digitalWrite(16, LOW);
  }

I tried to use timelib.h which doesn't work for me (I read the docu on github) because hour is always zero

#include <TimeLib.h>


void setup() {
  Serial.begin(115200);
  pinMode(16, OUTPUT); 
}

void loop() {

  Serial.println("The time is:");
  Serial.print(hour()); 
  Serial.print(":");
  Serial.print(minute());
 

  if ((hour() == 20) && (minute() == 0))
  {
    digitalWrite(16, HIGH);
  }

  if ((hour() == 11) && (minute() == 0))
  {
    digitalWrite(16, LOW);
  }

delay(30000);

}


and RTClib.h which seems to need tons of code which I don't understand.

Is there an easy way to read the hour?

Do you have a RTC chip ?

No (I use an ESP8266 board). I guess I have to read the time via Wifi, right?

If you have an ESP, the official time library is already available, and it's preferred. It will save you a lot of headaches to use it, it handles NTP itself too. Check out your ESP libraries, there are example sketches there like "SimpleTime".

1 Like

I got it with the library NTPClient.h (official).

#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>

const char *ssid     = "WLAN-MS";
const char *password = ".................";

WiFiUDP ntpUDP;


// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);

// You can specify the time server pool and the offset, (in seconds)
// additionally you can specify the update interval (in milliseconds).
// NTPClient timeClient

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());
  
  timeClient.begin();
  
  pinMode(16, OUTPUT); 
}

void loop() {
  
  timeClient.update();


  int stunde = timeClient.getHours() + 1;

  Serial.println(stunde);

  if (stunde < 20 && stunde > 10)
  {
    digitalWrite(16, LOW);
    Serial.print("Should be off");
  }
  else 
  {
    digitalWrite(16, HIGH);
    Serial.print("Should be on");
  }

delay(30000);
}


You are using a single & for a and. You need two of those.

if (apples && fruit)
if (pears and edible)
1 Like

https://arduino.stackexchange.com/questions/85403/error-using-ntpclientlib-h/85405#85405

Thanks!

time.h uses that library and any functions that it needs from there. So you don't need it.

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