I would like to synchonize my board with a NTP server and use a library for this. There are some libraries in the web but they have all the same problem: They use a fixed IP and as NTP servers change regularly my project want last for long =(
Therefore I put some code parts thogether I found on differnt places. Now I have a sketch which can resolve the DNS and works fine
Now comes my problem. I want to put this into a library and failed by far :0 :0 :0. I can built simple libraries and don't require a basic instruction but when the compiler comes where I need to initialize the DNS costructor : Error Error.......
Can some one help me? Here is my sketch:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>
DNSClient DNS;
char ntpServer[] = "0.ch.pool.ntp.org";
IPAddress timeServer;
EthernetUDP Udp;
const int NTP_PACKET_SIZE= 48;
byte packetBuffer[ NTP_PACKET_SIZE];
IPAddress ip(192,168,0,205);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xA5 };
IPAddress gateway(192,168,0,2);
IPAddress subnet(255,255,255,0);
void setup() {
Ethernet.begin(mac, ip, gateway, gateway, subnet);
Serial.begin(9600);
DNS.begin(gateway);
Udp.begin(8888);
Serial.println(NTP_server_answer());
}
void loop() {
}
unsigned long NTP_server_answer() {
unsigned long epoch = 0;
DNS.getHostByName(ntpServer,timeServer);
sendNTPpacket(timeServer);
delay(1000);
if ( 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;
epoch = secsSince1900 - 2208988800UL;
}
return epoch;
}
unsigned long sendNTPpacket(IPAddress& address)
{
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
Udp.beginPacket(address, 123);
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}