@makvr, SurferTim: The code or the address isn't the problem.
I aim is to put as much as possible in the library here I struggle. My code looks like this:
ntp.h:
/*
NTP - Libary to contact an NTP server and read the NTP signal
*/
// ensure this library description is only included once
#ifndef NTP_h
#define NTP_h
#include "Arduino.h"
#include <SPI.h>
#include <EthernetUdp.h>
#include <Dns.h>
class NTP
{
const char ntpServer[];
const int NTP_PACKET_SIZE;
public:
NTP();
void begin();
unsigned long NTP_server_answer();
private:
byte packetBuffer[ NTP_PACKET_SIZE];
IPAddress timeServer;
unsigned long sendNTPpacket(IPAddress& address);
};
#endif
NTP.ccp
/*
NTP - Libary to contact an NTP server and read the NTP signal
*/
#include "NTP.h"
// Constructor /////////////////////////////////////////////////////////////////
NTP::NTP():
char ntpServer[]("0.ch.pool.ntp.org"),
int NTP_PACKET_SIZE (48);
{
DNSClient DNS;
EthernetUDP Udp;
}
// Public Methods //////////////////////////////////////////////////////////////
void NTP::begin(IPAddress gateway)
{
DNS.begin(gateway);
Udp.begin(8888);
}
unsigned long NTP::NTP_server_answer() {
unsigned long epoch = 0;
DNS.getHostByName(ntpServer,timeServer);
sendNTPpacket(timeServer); // send an NTP packet to a time server
delay(1000);
if ( Udp.parsePacket() ) {
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;
epoch = secsSince1900 - 2208988800UL; // Heute
}
return epoch;
}
// Private Methods /////////////////////////////////////////////////////////////
unsigned long NTP::sendNTPpacket(IPAddress& address)
{
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(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}
and the test sketch:
#include <SPI.h>
#include <Ethernet.h>
#include <NTP.h>
IPAddress ip(192,168,0,205); // IBoard pro
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xA5 }; // IBoard pro
IPAddress gateway(192,168,0,2);
IPAddress subnet(255,255,255,0);
NTP Zeit;
void setup() {
Ethernet.begin(mac, ip, gateway, gateway, subnet);
Serial.begin(9600);
Zeit.begin();
Serial.println(Zeit.NTP_server_answer());
}
void loop() {
}