Pages: [1]   Go Down
Author Topic: Bekomme NTP nicht zum laufen, benötige Hilfe  (Read 590 times)
0 Members and 1 Guest are viewing this topic.
NRW
Offline Offline
Full Member
***
Karma: 1
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Ich habe einen Sketch gefunden, der die aktuelle Zeit von einem NTP-Server holt und dann in die RTC schreibt. http://playground.arduino.cc/Main/DS1307OfTheLogshieldByMeansOfNTP

Ich habe den Sketch auf mein Netzwerk angepasst. Die FritzBox, von der die Zeit geholt werden soll, hat die IP 192.168.1.1.
Der Ethernet Shield wird im Menü der FritzBox mit seiner IP angezeigt.
Ich habe es natürlich auch mit einigen andern NTP-Servern probiert. Unter anderem auch mit dem, der im anderen Sketch läuft.

Versuche ich es mit dem Beispiel-Sketch, der DHCP nutzt, bekomme ich sofort eine Uhrzeit angezeigt. Aber der andere Sketch will einfach nicht laufen. Könnte mal jemand drüber schauen und gucken, wo der Hase im Pfeffer liegen könnte. Die Fehlermeldung lautet "No UDP available .....".

Funktioniert (auch mit 192.168.1.1 - also der FritzBox):

Code:
/*

 Udp NTP Client
 
 Get the time from a Network Time Protocol (NTP) time server
 Demonstrates use of UDP sendPacket and ReceivePacket
 For more on NTP time servers and the messages needed to communicate with them,
 see http://en.wikipedia.org/wiki/Network_Time_Protocol
 
 Warning: NTP Servers are subject to temporary failure or IP address change.
 Plese check

    http://tf.nist.gov/tf-cgi/servers.cgi

 if the time server used in the example didn't work.

 created 4 Sep 2010
 by Michael Margolis
 modified 9 Apr 2012
 by Tom Igoe
 
 This code is in the public domain.

 */

#include <SPI.h>        
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

unsigned int localPort = 8888;      // local port to listen for UDP packets

IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov NTP server
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov NTP server

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

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(19200);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  // start Ethernet and UDP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }
  Udp.begin(localPort);
}

void loop()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server

    // wait to see if a reply is available
  delay(1000);  
  if ( Udp.parsePacket() ) {  
    // We've received a packet, read the data from it
    Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;  
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);              

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;    
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;  
    // print Unix time:
    Serial.println(epoch);                              


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');  
    if ( ((epoch % 3600) / 60) < 10 ) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ( (epoch % 60) < 10 ) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch %60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
{
  // 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();
}


« Last Edit: July 28, 2013, 10:28:15 am by Gelegenheitsbastler » Logged

Anfänger, der sich am Mega versucht. (Wegen Pin-Mangel bin ich vom Uno auf den Mega umgestiegen) Aktuelles Projekt: http://mfc-wittgenstein.

NRW
Offline Offline
Full Member
***
Karma: 1
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset



Funktioniert nicht:

Code:
/*
 * NAME: NTP2RTC
 * DATE: 2012-02-19
 *  URL: http://playground.arduino.cc/Main/DS1307OfTheLogshieldByMeansOfNTP
 *
 * PURPOSE:
 * Get the time from a Network Time Protocol (NTP) time server
 * and store it to the RTC of the adafruit logshield
 *
 * NTP is described in:
 * http://www.ietf.org/rfc/rfc958.txt (obsolete)
 * http://www.ietf.org/rfc/rfc5905.txt
 *
 * based upon Udp NTP Client, by Michael Margolis, mod by Tom Igoe
 * uses the RTClib from adafruit (based upon Jeelabs)
 * Thanx!
 * mod by Rob Tillaart, 10-10-2010
 *
 * This code is in the public domain.
 *
 */


// libraries for ethershield
#include <SPI.h>       
#include <Ethernet.h>
#include <EthernetUdp.h>        // New from IDE 1.0
#include <Wire.h>
#include <RTClib.h>

RTC_DS1307 RTC;

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // Use your MAC address
byte ip[] = {192, 168, 1, 121};                      // no DHCP so we set our own IP address
byte subnet[] = {255, 255, 255, 0};                // subnet mask
byte gateway[] = {192, 168, 1, 1};                 // internet access via router

unsigned int localPort = 8888;             // local port to listen for UDP packets

// find your local ntp server http://www.pool.ntp.org/zone/europe or
// http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers
byte timeServer[] = {192, 43, 244, 18}; // time.nist.gov NTP server
//byte timeServer[] = {192, 168, 1, 1};    // FritzBox
//byte timeServer[] = {130, 149, 17, 21};    // ntp irgendeiner TU. Aendert seine IP angeblich nie.
//byte timeServer[] = {128, 118, 25, 3};   // clock.psu.edu


//IPAddress timeServer(132, 163, 4, 101); //So stehts im funktionierenden Sketch




const int NTP_PACKET_SIZE= 48;             // NTP time stamp is in the first 48 bytes of the message

byte pb[NTP_PACKET_SIZE];                  // buffer to hold incoming and outgoing packets

//#if ARDUINO >= 100
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                // New from IDE 1.0
//#endif


///////////////////////////////////////////
//
// SETUP
//
void setup()
{
  Serial.begin(19200);
  Serial.println("NTP2RTC 0.5");

  // start Ethernet and UDP

  Ethernet.begin(mac, ip);         // For when you are directly connected to the Internet.
  Udp.begin(localPort);
  Serial.println("network ...");

  // init RTC
  Wire.begin();
  RTC.begin();
  Serial.println("rtc ...");
  Serial.println();
}

///////////////////////////////////////////
//
// LOOP
//
void loop()
{
  Serial.print("RTC before: ");
  PrintDateTime(RTC.now());
  Serial.println();

  // send an NTP packet to a time server
  sendNTPpacket(timeServer);

  // wait to see if a reply is available
  delay(1000);

  if ( Udp.available() ) {
    // read the packet into the buffer
//#if ARDUINO >= 100
    Udp.read(pb, NTP_PACKET_SIZE);      // New from IDE 1.0,
//#else
//    Udp.readPacket(pb, NTP_PACKET_SIZE);
//#endif

    // NTP contains four timestamps with an integer part and a fraction part
    // we only use the integer part here
    unsigned long t1, t2, t3, t4;
    t1 = t2 = t3 = t4 = 0;
    for (int i=0; i< 4; i++)
    {
      t1 = t1 << 8 | pb[16+i];     
      t2 = t2 << 8 | pb[24+i];     
      t3 = t3 << 8 | pb[32+i];     
      t4 = t4 << 8 | pb[40+i];
    }

    // part of the fractional part
    // could be 4 bytes but this is more precise than the 1307 RTC
    // which has a precision of ONE second
    // in fact one byte is sufficient for 1307
    float f1,f2,f3,f4;
    f1 = ((long)pb[20] * 256 + pb[21]) / 65536.0;     
    f2 = ((long)pb[28] * 256 + pb[29]) / 65536.0;     
    f3 = ((long)pb[36] * 256 + pb[37]) / 65536.0;     
    f4 = ((long)pb[44] * 256 + pb[45]) / 65536.0;

    // NOTE:
    // one could use the fractional part to set the RTC more precise
    // 1) at the right (calculated) moment to the NEXT second!
    //    t4++;
    //    delay(1000 - f4*1000);
    //    RTC.adjust(DateTime(t4));
    //    keep in mind that the time in the packet was the time at
    //    the NTP server at sending time so one should take into account
    //    the network latency (try ping!) and the processing of the data
    //    ==> delay (850 - f4*1000);
    // 2) simply use it to round up the second
    //    f > 0.5 => add 1 to the second before adjusting the RTC
    //   (or lower threshold eg 0.4 if one keeps network latency etc in mind)
    // 3) a SW RTC might be more precise, => ardomic clock :)


    // convert NTP to UNIX time, differs seventy years = 2208988800 seconds
    // NTP starts Jan 1, 1900
    // Unix time starts on Jan 1 1970.
    const unsigned long seventyYears = 2208988800UL;
    t1 -= seventyYears;
    t2 -= seventyYears;
    t3 -= seventyYears;
    t4 -= seventyYears;

    /*
    Serial.println("T1 .. T4 && fractional parts");
    PrintDateTime(DateTime(t1)); Serial.println(f1,4);
    PrintDateTime(DateTime(t2)); Serial.println(f2,4);
    PrintDateTime(DateTime(t3)); Serial.println(f3,4);
    */
    PrintDateTime(DateTime(t4)); Serial.println(f4,4);
    Serial.println();

    // Adjust timezone and DST... in my case substract 4 hours for Chile Time
    // or work in UTC?
    t4 -= (3 * 3600L);     // Notice the L for long calculations!!
    t4 += 1;               // adjust the delay(1000) at begin of loop!
    if (f4 > 0.4) t4++;    // adjust fractional part, see above
    RTC.adjust(DateTime(t4));

    Serial.print("RTC after : ");
    PrintDateTime(RTC.now());
    Serial.println();

    Serial.println("done ...");
    // endless loop
    while(1);
  }
  else
  {
    Serial.println("No UDP available .....");
  }
  // wait 1 minute before asking for the time again
  // you don't want to annoy NTP server admin's
  delay(6000);
}

///////////////////////////////////////////
//
// MISC
//
void PrintDateTime(DateTime t)
{
    char datestr[24];
    sprintf(datestr, "%04d-%02d-%02d  %02d:%02d:%02d  ", t.year(), t.month(), t.day(), t.hour(), t.minute(), t.second());
    Serial.print(datestr); 
}


// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(byte *address)
{
  // set all bytes in the buffer to 0
  memset(pb, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  pb[0] = 0b11100011;   // LI, Version, Mode
  pb[1] = 0;     // Stratum, or type of clock
  pb[2] = 6;     // Polling Interval
  pb[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  pb[12]  = 49;
  pb[13]  = 0x4E;
  pb[14]  = 49;
  pb[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
//#if ARDUINO >= 100
  // IDE 1.0 compatible:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(pb,NTP_PACKET_SIZE);
  Udp.endPacket();
//#else
//  Udp.sendPacket( pb,NTP_PACKET_SIZE,  address, 123); //NTP requests are to port 123
//#endif   

}
///////////////////////////////////////////
//
// End of program
//

Logged

Anfänger, der sich am Mega versucht. (Wegen Pin-Mangel bin ich vom Uno auf den Mega umgestiegen) Aktuelles Projekt: http://mfc-wittgenstein.

Germany
Offline Offline
Sr. Member
****
Karma: 1
Posts: 275
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,
also was mir auffällt, ist in Zeile 76 der GATEWAY eintrag fehlt !

Bei mir sieht es so aus :
Code:
Ethernet.begin(mac, ip, gateway);

Versuche das mal, ob sich was tut...
Logged

*greatz*

 CeTax

www dot blinkmann dot de


Germany S-H
Offline Offline
Edison Member
*
Karma: 117
Posts: 2440
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Funktioniert nicht:

Ja und?

Du bekommst mit der Ethernet-Library einen vollständig funktionierenden Code ("UdpNTPClient") mitgeliefert.

Warum baust Du Deinen Sketch nicht darauf auf?
Logged

NRW
Offline Offline
Full Member
***
Karma: 1
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

@Cetax: Auf das Gateway hatte ich auch so ziemlich als erstes getippt. Aber das war es nicht. Die Onlineverbindung ansich funktionierte ja auch.

@jurs: Das habe ich versucht, aber nicht hin bekommen. Daher mein Post.

Nach stundenlanger Suche und Rumprobieren habe ich es jetzt am laufen smiley Ich habe die beiden Sketche immer wieder verglichen. Denn so verschieden sind die ja nicht. Letztlich habe ich.

Code:
delay(1000);

  if ( Udp.available() ) {
    // read the packet into the buffer

durch

Code:
  delay(1000); 
  if ( Udp.parsePacket() ) { 
    // We've received a packet, read the data from it

ersetzt. Dann lief es endlich!

Frank
Logged

Anfänger, der sich am Mega versucht. (Wegen Pin-Mangel bin ich vom Uno auf den Mega umgestiegen) Aktuelles Projekt: http://mfc-wittgenstein.

NRW
Offline Offline
Full Member
***
Karma: 1
Posts: 129
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Jetzt habe ich aber noch ein anderes Problem. Ich möchte, dass Winter- und Sommerzeit automatisch umschalten. Dazu habe ich hier http://forum.arduino.cc/index.php/topic,40286.0.html#10 den folgenden Sketch gefunden:

Code:
int adjustDstEurope()
{
  // last sunday of march
  int beginDSTDate=  (31 - (5* year() /4 + 4) % 7);
  Serial.println(beginDSTDate);
  int beginDSTMonth=3;
  //last sunday of october
  int endDSTDate= (31 - (5 * year() /4 + 1) % 7);
  Serial.println(endDSTDate);
  int endDSTMonth=10;
  // DST is valid as:
  if (((month() > beginDSTMonth) && (month() < endDSTMonth))
      || ((month() == beginDSTMonth) && (day() >= beginDSTDate))
      || ((month() == endDSTMonth) && (day() <= endDSTDate)))
  return 7200;  // DST europe = utc +2 hour
  else return 3600; // nonDST europe = utc +1 hour
}

Wenn ich den aber kompiliere, gibt es immer wieder Fehlermeldungen. Woran liegt das und wie bekomme ich das gelöst?

Code:
NTP_auf_RTC_5_mit_DST_TZ.ino: In function ‘int adjustDstEurope()’:
NTP_auf_RTC_5_mit_DST_TZ:65: error: ‘year’ was not declared in this scope
NTP_auf_RTC_5_mit_DST_TZ:73: error: ‘month’ was not declared in this scope
NTP_auf_RTC_5_mit_DST_TZ:74: error: ‘day’ was not declared in this scope

Frank
Logged

Anfänger, der sich am Mega versucht. (Wegen Pin-Mangel bin ich vom Uno auf den Mega umgestiegen) Aktuelles Projekt: http://mfc-wittgenstein.

Germany S-H
Offline Offline
Edison Member
*
Karma: 117
Posts: 2440
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Wenn ich den aber kompiliere, gibt es immer wieder Fehlermeldungen. Woran liegt das und wie bekomme ich das gelöst?

Ich habe hier auch schon eine Sommerzeit-Funktion gepostet, gekapselt als Funktion mit genau definierten Übergabeparametern, die Du an die Funktion übergeben müßtest und dann einen boolean-Wert "true" oder "false" zurückbekommst:
http://forum.arduino.cc/index.php?topic=172044.msg1278536#msg1278536
Logged

Pages: [1]   Go Up
Jump to: