Ethernet Shield Network Time Protocol ( NTP ) Client

Query a Network Time Protocol ( NTP ) server using UDP.

In this example, you will use your Ethernet Shield and your Arduino to query a Network Time Protocol ( NTP ) server. This way, your Arduino can get time from Internet.

Hardware Required

Circuit

The Ethernet shield allows you to connect a WIZNet Ethernet controller to Arduino boards via SPI bus. It uses ICSP header pins and pin 10 as chip select for SPI connection to Ethernet controller chip. Later models of Ethernet shield also have an SD Card on board. Digital pin 4 is used to control chip select pin on SD card.

The shield should be connected to a network with an Ethernet cable. You will need to change network settings in program to correspond to your network.

Image developed using Fritzing . For more circuit examples, see Fritzing project page

In above image, Arduino board would be stacked below Ethernet shield.

Schematic

The schematic for this tutorial.

Code

/*H*******************************************************
 Udp NTP Client
 Get time from a Network Time Protocol ( NTP ) time server
 Demonstrates use of UDP sendPacket and ReceivePacket
 For more on NTP time servers and messages needed to communicate with them,
 see http://en.wikipedia.org/wiki/Network_Time_Protocol
 created 4 Sep 2010 by Michael Margolis
 modified 9 Apr 2012 by Tom Igoe
 modified 02 Sept 2015 by Arturo Guadalupi
 This code is in public domain.
 ********************************************************/
#include 
#include 
#include 

//************************* DEFINES ************************************
#define  BAUD 9600

//************************* PROTOTYPES ************************************

//************************* VARIABLES ************************************
EthernetUDP Udp;
// MAC ADDR FOR CONTROLLER, NEWER ETHERNET SHIELDS HAVE MAC ADDR ON STICKER
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
unsigned int localPort = 8888;       // LOCAL PORT TO LISTEN FOR UDP PACKETS
const char timeServer[] = "time.nist.gov"; // TIME.NIST.GOV NTP SERVER
const int NTPPKTSIZ = 48; // NTP time stamp in msg first 48 bytes 
byte PktBuff[NTPPKTSIZ]; // INCOMING AND OUTGOING PACKETS

/*F********************************************************************
*
**********************************************************************/
void 
setup( ) 
{
	// You can use Ethernet.init( pin ) to configure CS pin
	//Ethernet.init( 10 );  // Most Arduino shields
	//Ethernet.init( 5 );   // MKR ETH shield
	//Ethernet.init( 0 );   // Teensy 2.0
	//Ethernet.init( 20 );  // Teensy++ 2.0
	//Ethernet.init( 15 );  // ESP8266 with Adafruit Featherwing Ethernet
	//Ethernet.init( 33 );  // ESP32 with Adafruit Featherwing Ethernet
	Serial.begin( BAUD );         // OPEN SERIAL COMM, WAIT FOR PORT TO OPEN
	while( !Serial ) 
	{ ; } // WAIT FOR SERIAL PORT TO CONNECT. NEEDED FOR NATIVE USB PORT ONLY
	if( Ethernet.begin( mac ) == 0 )                // START ETHERNET AND UDP
	{
		Serial.println( "Failed to configure Ethernet using DHCP" );
		// Check for Ethernet hardware present
		if( Ethernet.hardwareStatus( ) == EthernetNoHardware ) 
			Serial.println( "Ethernet shield not found,can't run without hdw" );
		else if( Ethernet.linkStatus( ) == LinkOFF ) 
			Serial.println( "Ethernet cable is not connected." );
		// NO POINT IN CARRYING ON, SO DO NOTHING FOREVERMORE
		while( true ) 
			delay( 1 );
	}
	Udp.begin( localPort );
}
/*F********************************************************************
*
**********************************************************************/
void 
loop( ) 
{
	sendNTPpacket( timeServer );          // SEND AN NTP PACKET TO TIME SERVER
	delay( 1000 );                    // WAIT TO SEE IF A REPLY IS AVAILABLE
	if( Udp.parsePacket( ) ) 
	{                                // RECEIVED A PACKET, READ DATA FROM IT
		Udp.read( PktBuff, NTPPKTSIZ );                // READ PACKET INTO BUFFER
		// timestamp starts at byte 40 of received packet and is four bytes,
		// or two words, long. First, extract two words:
		unsigned long highWord = word( PktBuff[40], PktBuff[41] );
		unsigned long lowWord = word( PktBuff[42], PktBuff[43] );
		// combine 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 hour, minute and second:
		Serial.print( "The UTC time is " ); // UTC time at Greenwich Meridian ( GMT )
		Serial.print( ( epoch  % 86400L ) / 3600 ); // print hour ( 86400 equals secs per day )
		Serial.print( ':' );
		if( ( ( epoch % 3600 ) / 60 ) < 10 ) {
		// In first 10 minutes of each hour, we'll want a leading '0'
		Serial.print( '0' );
		}
		Serial.print( ( epoch  % 3600 ) / 60 ); // print minute ( 3600 equals secs per minute )
		Serial.print( ':' );
		if( ( epoch % 60 ) < 10 ) {
		// In first 10 seconds of each minute, we'll want a leading '0'
		Serial.print( '0' );
		}
		Serial.println( epoch % 60 ); // print second
	}
	// wait ten seconds before asking for time again
	delay( 10000 );
	Ethernet.maintain( );
}
/*F********************************************************************
* send an NTP request to time server at given address
**********************************************************************/
void 
sendNTPpacket( const char *address ) 
	{
	// set all bytes in buffer to 0
	memset( PktBuff, 0, NTPPKTSIZ );
	// Initialize values needed to form NTP request
	// ( see URL above for details on packets )
	PktBuff[0] = 0b11100011;   // LI, Version, Mode
	PktBuff[1] = 0;     // Stratum, or type of clock
	PktBuff[2] = 6;     // Polling Interval
	PktBuff[3] = 0xEC;  // Peer Clock Precision
	// 8 bytes of zero for Root Delay & Root Dispersion
	PktBuff[12]  = 49;
	PktBuff[13]  = 0x4E;
	PktBuff[14]  = 49;
	PktBuff[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( PktBuff, NTPPKTSIZ );
	Udp.endPacket( );
}

Last revision 2018/09/07 by SM