W5100 NTP Client (and DHCP) Demo

In this tutorial we show how to get the time from a specificic NTP server with a W5100 shield.



Rightclick to see full picture The W5100 network shield can be bought on ebay for a few dollar.

You can download the library here.








For this tutorial we need also a DS1307 or DS3231 (which are significant better) which we connect to the i2c.

In the setup loop we try to get a dhcp adress. When succes the script tries to get a response from a designated time server. When succes the received ntp time will be set to the RTC module.
Also as the cherisch on a cake, i put a little function to adjust the timezone setting automaticly (Europe), which i find somewhere on the internet. Of course you can adjust the script to sync with a time server in the loop let's say by pressing a button.

w5100_ntp_client.ino

#include <math.h>
#include <OneWire.h>
#include <Wire.h> // Comes with Arduino IDE
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "RTClib.h" // Credit: Adafruit


RTC_DS1307 RTC;


/* ******** Ethernet Card Settings ******** */
// Set this to your Ethernet Card Mac Address
byte mac[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06
};

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
unsigned int ifacePort = 80; // port to webportal interface
EthernetServer server(ifacePort);

// NTP Client
unsigned int localPort = 8888; // local port to listen for UDP packets
IPAddress timeServer(194,109,6,2); //ntp.xs4all.nl but you can cange in any public 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;

long timeZoneOffset = 3600L; //Winter (original) time Europe
boolean networkConnection = true;


void setup() {
Serial.begin(9600);

// Instantiate the RTC
Wire.begin();
RTC.begin();


// Check if the RTC is running.
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running");
} else {
Serial.println("RTC present");
}


Serial.println(F("\n[testDHCP]"));

// Ethernet shield setup
int i = 1;
int DHCP = 0;
//Try to get dhcp settings 3 times before giving up
Serial.println("Trying to resolve DHCP 3 times.");
while( DHCP == 0 && i < 5){
Serial.print("Trying to resolve DHCP attempt nr. ");
Serial.println(i);

delay(1000);
DHCP = Ethernet.begin(mac);
i++;
}
if(!DHCP){
Serial.println("DHCP FAILED");
networkConnection = false;
delay(5000);



} else {
Udp.begin(localPort); //Net client added 10-11-2015
Serial.println("DHCP Success");
Serial.println(Ethernet.localIP());

uint32_t ipAddress = Ethernet.localIP();
uint8_t *ipPtr = (uint8_t*) &ipAddress;
String stripAddress = String(ipPtr[0], DEC) + "." + String(ipPtr[1], DEC) + "." + String(ipPtr[2], DEC) + "." + String(ipPtr[3], DEC);

//you can output this to lcd, oled or 7-segment
String ip0 = String(ipPtr[0], DEC);
String ip1 = String(ipPtr[1], DEC);
String ip2 = String(ipPtr[2], DEC);
String ip3 = String(ipPtr[3], DEC);
}
}


//Get time from DS3231
DateTime now = RTC.now();
unsigned long epoch = now.unixtime();


//If network connection is true, sync with ntp server
if (networkConnection) {epoch = getNtpTime();}
if (epoch == 0) {DateTime now = RTC.now(); epoch = now.unixtime();} //sync failed, use DS3231 time instead

//Check summer / winter time
if (adjustDstEurope()) {epoch = epoch + 3600; timeZoneOffset = 7200L;}
RTC.adjust(epoch);
now = RTC.now();

Serial.println(epoch);
} //End of setup


unsigned long getNtpTime()
{
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 timeFromNTP = highWord << 16 | lowWord;
const unsigned long seventyYears = 2208988800UL;
return timeFromNTP - seventyYears + timeZoneOffset;
}

}


// 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();
}


boolean adjustDstEurope()
{
// Get the current time
DateTime now = RTC.now();
// last sunday of march
int beginDSTDate= (31 - (5* now.year() /4 + 4) % 7);
int beginDSTMonth=3;
//last sunday of october
int endDSTDate= (31 - (5 * now.year() /4 + 1) % 7);
int endDSTMonth=10;
// DST is valid as:
if (((now.month() > beginDSTMonth) && (now.month() < endDSTMonth))
|| ((now.month() == beginDSTMonth) && (now.day() >= beginDSTDate))
|| ((now.month() == endDSTMonth) && (now.day() < endDSTDate)))
return true; // DST europe = GMT +2
else return false; // nonDST europe = GMT +1
}


void loop() {
// Get the current time
DateTime now = RTC.now();

unsigned long newHour = now.hour();
unsigned long newMinute = now.minute();
unsigned long newSecond = now.second();
unsigned long newYear = now.year();
unsigned long newMonth = now.month();
unsigned long newDay = now.day();

int hour1 = (newHour%10);
int hour10 = (newHour/10);
int minute1 = (newMinute%10);
int minute10 = (newMinute/10);
int second1 = (newSecond%10);
int second10 = (newSecond/10);
int year1 = (newYear%10);
int year10 = ((newYear/10)%10);
int year100 = ((newYear/100)%10);
int year1000 = (newYear/1000);
int month1 = (newMonth%10);
int month10 = (newMonth/10);
int day1 = (newDay%10);
int day10 = (newDay/10);


//Output to serial console, but you can use lcd, oled or 7-segment
Serial.print(hour10);
Serial.print(hour1);
Serial.print(":");
Serial.print(minute10);
Serial.print(minute1);
Serial.print(":");
Serial.print(second10);
Serial.print(second1);
Serial.print(" ");
Serial.print(day10);
Serial.print(day1);
Serial.print("-");
Serial.print(month10);
Serial.print(month1);
Serial.print("-");
Serial.print(year1000);
Serial.print(year100);
Serial.print(year10);
Serial.println(year1);

delay(1000);
}



Serial output