Set time over wifi

So I made this and it works. (Danish btw)

#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Button.h> 
#include <TimeLib.h>
#include <TimeAlarms.h>

AlarmId id;

int ventetidSekunder = 31;
 
const char* ssid = "xxxxxxxxxxxxx";
const char* password = "xxxxxxxxxxxxxxxx";
const char* server = "api.thingspeak.com";
String apiKey = "TNT9988Xxxxxxxxx";

#define DHTPIN 4        // D2 på NodeMCU
#define MAALER_PIN 5    // D1 på NodeMCU   
#define RESET_PIN 2     // D4 på NodeMCU
#define PULLUP true        
#define INVERT true
#define DEBOUNCE_MS 0  
int lysPin = A0;        // A0 på NodeMCU

int lysStyrke = 0;
int tip = 0;   
float millimeter = 0; 
unsigned long time_now = 0;

Button maaler(MAALER_PIN, PULLUP, INVERT, DEBOUNCE_MS); 
Button reset(RESET_PIN, PULLUP, INVERT, DEBOUNCE_MS); 
 
DHT dht(DHTPIN, DHT22, 11);

WiFiClient client;

void setup() {                
  Serial.begin(115200);
  setTime(20,14,45,8,19,18); 
  Alarm.alarmRepeat(13,1,40, Nulstil); 
  dht.begin();

WiFi.hostname("Vejrstation");  
WiFi.begin(ssid, password);
 
Serial.print("Forbinder til ");
Serial.print(ssid);
   
WiFi.begin(ssid, password);
   
while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("");
  Serial.println(" forbundet");
  
}
 
 
void loop() {
if(millis() > time_now + ventetidSekunder * 1000){
        time_now = millis();
            int sensorValue = digitalRead(D0);
  lysStyrke = analogRead(lysPin);   
  float h = dht.readHumidity();
  float f = dht.readTemperature(true);
  float t = (((f-32)*5)/9);
  
  if (client.connect(server,80)) {  
    String postStr = apiKey;
           postStr +="&field1=";
           postStr += String((float)t);
           postStr +="&field2=";
           postStr += String((int)h);
           postStr +="&field3=";
           postStr += String((int)lysStyrke);
           postStr +="&field4=";
           postStr += String((float)millimeter,1);
 
     client.print("POST /update HTTP/1.1\n"); 
     client.print("Host: api.thingspeak.com\n"); 
     client.print("Connection: close\n"); 
     client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n"); 
     client.print("Content-Type: application/x-www-form-urlencoded\n"); 
     client.print("Content-Length: "); 
     client.print(postStr.length()); 
     client.print("\n\n"); 
     client.print(postStr);
           
 
     Serial.print("Temperatur: ");
     Serial.print(t,1);
     Serial.print(" grader celcius, luftfugtighed: "); 
     Serial.print(h,1);
     Serial.print("%, lysstyrke: ");
     Serial.print(lysStyrke);
     Serial.print(" og regn: ");
     Serial.print(millimeter,1);
     Serial.println(" ... Send til Thingspeak");   
  }
  client.stop();
          Serial.print("Venter i ");
          Serial.print(ventetidSekunder);
          Serial.println(" sekunder, før der uploades igen...");
   }
maaler.read();                   
if (maaler.wasPressed()) {     
  tip++; 
  delay(20);
  }
millimeter = tip * 0.2794;

reset.read();                   
if (reset.wasPressed()) {     
  tip = 0; 
  }

Alarm.delay(0);
   
}

void Nulstil() {
tip = 0;
}

As I wrote, it works. BUT… there’s nothing good about ‘hard’ setting the time when it’s already all over the internet. On any reboot I will send my weather thingy back in time and out of sync with midnight when I want my variable reset.

How will I ever put an internet time into

setTime(20,14,45,8,19,18);

instead of lame numbers?

You need something like this:

#include <TimeLib.h>          //https://github.com/PaulStoffregen/Time //Time Library - Time-master
#include <ESP8266WiFi.h>      //https://github.com/esp8266/Arduino/releases/tag/2.3.0-rc2
#include <WiFiUdp.h>          //https://github.com/esp8266/Arduino/releases/tag/2.3.0-rc2
WiFiUDP udp;
const char* ntpServerName = "time.nist.gov";
const unsigned int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE];

unsigned long PROcheck;
char CHARstring[4000];


void setup(){
  
}
void loop(){
  if(year() == 1970 && millis() - PROcheck > 4800){
    PROcheck = millis();
    SetTime();
  }

}

void SetTime() {
  Serial.println("Contacting NTP server ...");
  //get a random server from the pool
  IPAddress timeServerIP;
  WiFi.hostByName(ntpServerName, timeServerIP);
  
  Serial.println("timeServerIP = ");
  Serial.println(timeServerIP);
  Serial.println("END");
  sendNTPpacket(timeServerIP); delay(500);// send an NTP packet to a time server
  //return;
  int cb = udp.parsePacket();
  if (!cb) {
     Serial.println("No answer from NTP ...");
  } else {
    Serial.println("Got Time!");
    ///*
    //sync_t = true;
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    Serial.println("Contacting NTP ...");
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord  = word(packetBuffer[42], packetBuffer[43]);
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    const unsigned long seventyYears = 2208988800UL;// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    unsigned long epoch = secsSince1900 - seventyYears; // subtract seventy years (UNIX time)

    setTime(epoch);
    adjustTime(3600*-5);
    setTime(hour(), minute(), second(), day(), month(), year());
    //DSTcheck();
    //LoadDATE();
    unsigned long MYtime = now();
    memset(CHARstring, '\0', sizeof(CHARstring)-1);
    strcpy(CHARstring, String(MYtime).c_str());
    //SendToMega('U');
    memset(packetBuffer,'\0', sizeof(packetBuffer));
  }
}
unsigned long sendNTPpacket(IPAddress& address) { // for get time
  // send an NTP request to the time server at the given address
  memset(packetBuffer, 0, NTP_PACKET_SIZE);   // set all bytes in the buffer to 0
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;             // LI, Version, Mode
  packetBuffer[1] = 0;                     // Stratum, or type of clock
  packetBuffer[2] = 6;                    // Polling Interval
  packetBuffer[3] = 0xEC;                // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  udp.beginPacket(address, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
}