Difference between revisions of "Arduino: NTP Sync"

From OnnoWiki
Jump to navigation Jump to search
Line 19: Line 19:
 
  #include <Ethernet.h>
 
  #include <Ethernet.h>
 
  #include <EthernetUdp.h>
 
  #include <EthernetUdp.h>
#include <Dns.h>
 
 
   
 
   
 
  #define SD_CS 4
 
  #define SD_CS 4
Line 25: Line 24:
 
  // Ethernet library configuration
 
  // Ethernet library configuration
 
  byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
 
  byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
  IPAddress timeServer;
+
  IPAddress timeServer(203, 160, 128, 132) ;
 
+
 
  /* ALTER THESE VARIABLES AT YOUR OWN RISK */
 
  /* ALTER THESE VARIABLES AT YOUR OWN RISK */
 
  // local port to listen for UDP packets
 
  // local port to listen for UDP packets
Line 36: Line 35:
 
  // A UDP instance to let us send and receive packets over UDP
 
  // A UDP instance to let us send and receive packets over UDP
 
  EthernetUDP Udp;                   
 
  EthernetUDP Udp;                   
+
 
 
  boolean s_flag = false;
 
  boolean s_flag = false;
 
   
 
   
Line 43: Line 42:
 
   // disable SD SPI Chip Select
 
   // disable SD SPI Chip Select
 
   pinMode(SD_CS,OUTPUT);
 
   pinMode(SD_CS,OUTPUT);
  digitalWrite(SD_CS,HIGH);
 
 
   
 
   
 
   Serial.begin(9600);
 
   Serial.begin(9600);
Line 50: Line 48:
 
     Serial.println("DHCP config failed! ");
 
     Serial.println("DHCP config failed! ");
 
   }
 
   }
 
  DNSClient dns;
 
  dns.begin(Ethernet.dnsServerIP());
 
  dns.getHostByName("pool.ntp.org",timeServer); // at this point the function works
 
 
   Serial.print("NTP Server: ");
 
   Serial.print("NTP Server: ");
 
   Serial.println(timeServer);
 
   Serial.println(timeServer);
 
   
 
   
   setSyncInterval(5); // Set seconds between re-sync (5s for test only)
+
   setSyncInterval(5); // Set seconds between re-sync (5s for test only)  
 
   
 
   
 
   Udp.begin(localPort);
 
   Udp.begin(localPort);
Line 66: Line 60:
 
   setSyncProvider(getNtpTime);
 
   setSyncProvider(getNtpTime);
 
   Serial.print("Time Status after setSyncProvider:");
 
   Serial.print("Time Status after setSyncProvider:");
   Serial.println(timeStatus());  
+
   Serial.println(timeStatus());
 
   
 
   
 
   while(timeStatus()== timeNotSet)
 
   while(timeStatus()== timeNotSet)
Line 73: Line 67:
 
   MsTimer2::set(1000, update1s); // 1s period
 
   MsTimer2::set(1000, update1s); // 1s period
 
   MsTimer2::start();
 
   MsTimer2::start();
 +
 
  }
 
  }
 
+
 
  void loop() {
 
  void loop() {
 +
 
   if (s_flag){
 
   if (s_flag){
 
     s_flag=false;  
 
     s_flag=false;  
Line 81: Line 77:
 
   }
 
   }
 
  }  
 
  }  
+
 
 +
 
 
  void update1s(){
 
  void update1s(){
 
  // 1s is over flag
 
  // 1s is over flag
Line 118: Line 115:
 
      
 
      
 
     if ( Udp.parsePacket() ) {
 
     if ( Udp.parsePacket() ) {
       Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer
+
       Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer
 
   
 
   
 
       //the timestamp starts at byte 40, convert four bytes into a long integer
 
       //the timestamp starts at byte 40, convert four bytes into a long integer
Line 137: Line 134:
 
  //sendNTPpacket(IPAddress address)
 
  //sendNTPpacket(IPAddress address)
 
  {
 
  {
   memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0
+
   memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0  
 
   
 
   
 
   // Initialize values needed to form NTP request
 
   // Initialize values needed to form NTP request

Revision as of 17:33, 26 May 2018

Instal library

cd ~/Arduino/libraries/
wget https://github.com/PaulStoffregen/MsTimer2/archive/master.zip
unzip MsTimer2-master.zip
mv MsTimer2-master MsTimer2


Code

// NTP time issue
// IDE 1.0.3
// DHCP Server required
// Arduino Mega2560 + Ethernetshield for Mega with SD-slot

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

#define SD_CS 4

// Ethernet library configuration
byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
IPAddress timeServer(203, 160, 128, 132) ;

/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 8888;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;     
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE]; 
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                   
boolean s_flag = false;

void setup() {               

  // disable SD SPI Chip Select
  pinMode(SD_CS,OUTPUT);

  Serial.begin(9600);
  Serial.println("Wait for DHCP Server");
  if (Ethernet.begin(mac) == 0) {  // start Ethernet by DHCP conf.
    Serial.println("DHCP config failed! ");
  }
  Serial.print("NTP Server: ");
  Serial.println(timeServer);

  setSyncInterval(5); // Set seconds between re-sync (5s for test only) 

  Udp.begin(localPort);
  Serial.print("Time: ");
  Serial.println(getNtpTime());
  Serial.print("Time Status before setSyncProvider:");
  Serial.println(timeStatus());
  setSyncProvider(getNtpTime);
  Serial.print("Time Status after setSyncProvider:");
  Serial.println(timeStatus());

  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider

  MsTimer2::set(1000, update1s); // 1s period
  MsTimer2::start();

}

void loop() {

  if (s_flag){
    s_flag=false; 
    digitalClockDisplay();
  }
} 


void update1s(){
// 1s is over flag
  s_flag=true;
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(day());
  Serial.print(".");
  Serial.print(month());
  Serial.print(".");
  Serial.print(year());
  Serial.print(" ");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(" ");
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding
  // colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(500);
   
    if ( Udp.parsePacket() ) {
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer

     //the timestamp starts at byte 40, convert four bytes into a long integer
     unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
     unsigned long low = word(packetBuffer[42], packetBuffer[43]);
     // this is NTP time (seconds since Jan 1 1900
     unsigned long secsSince1900 = hi << 16 | low; 
     // Unix time starts on Jan 1 1970
     const unsigned long seventyYears = 2208988800UL;     
     unsigned long epoch = secsSince1900 - seventyYears;  // subtract 70 years, add Daylight Saving and Timezone adjust
     return epoch;
  }
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
//sendNTPpacket(IPAddress address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0 

  // Initialize values needed to form NTP request
  packetBuffer[0] = B11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum
  packetBuffer[2] = 6;     // Max Interval between messages in seconds
  packetBuffer[3] = 0xEC;  // Clock Precision
  // bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
  packetBuffer[12]  = 49;  // four-byte reference ID identifying
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52; 

  // send the packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer,NTP_PACKET_SIZE);
  Udp.endPacket();
}