Post links and attach files for documentation here, also chat about these docs freely

User avatar
By KDB
#66938 I want to get the time from a time server. No example of the internet is running. It seems that UDP doesn't work. Has somebody an example ? Thanks. Klaus-Dieter
User avatar
By martinayotte
#66945
Code: Select all  const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
  byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
  const unsigned long seventyYears = 2208988800UL;
  WiFiUDP udp;
  IPAddress ntphostip;
  WiFi.hostByName("time.nist.gov", ntphostip);
  String str = "NTP IPAddr : ";
  str += ntphostip.toString();
  Serial.println(str);
  udp.begin(2390);
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  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
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  udp.beginPacket(ntphostip, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
  delay(2000);
  int cb = udp.parsePacket();
  if (!cb) {
    Serial.println("no NTP response");
  }
  else {
    Serial.print("packet received, length=");
    Serial.println(cb);
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);
    Serial.print("Unix time (seconds since 1970) = ");
    Serial.println(secsSince1900 - seventyYears);