Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
char ssid[] = "************";
char pass[] = "**************";
unsigned int localPort = 2390;
IPAddress timeServer(129, 6, 15, 28);
const int NTP_PACKET_SIZE = 48;
byte packetBuffer[ NTP_PACKET_SIZE];
WiFiUDP udp;
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
udp.begin(localPort);
}
void loop()
{
sendNTPpacket(timeServer);
delay(1000);
int cb = udp.parsePacket();
udp.read(packetBuffer, NTP_PACKET_SIZE);
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;
unsigned long epoch = secsSince1900 - seventyYears;
int stund = (epoch % 86400L) / 3600 + 1;
int minut = (epoch % 3600) / 60;
int sekunde = epoch % 60;
String stunde = String(stund);
String minutestring = String(minut);
if(minut < 10)
{
minutestring = "0" + minutestring;
}
Serial.println(stunde);
Serial.println("|");
Serial.println(minutestring);
Serial.println("|");
Serial.println(sekunde);
Serial.println("|");
delay(10000);
}
unsigned long sendNTPpacket(IPAddress& address)
{
//Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment