Desktop Widget
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Display Internet based Time (NTP)

Go down

Display Internet based Time (NTP) Empty Display Internet based Time (NTP)

Post by Admin Sat Jun 06, 2015 5:11 pm

Here an example which shows the time. The Hardware is a combination of ESP8266 and Arduino Mini Pro 3.3V

The Arduino manages the LED display and the ESP8266 the NTP time from the internet. Both is compiled and load up with the Arduino IDE. Take care that the arduino has all ESP linked GIOP as Input while you program the ESP8266

Display Internet based Time (NTP) Csc_2612

Arduino code
Code:

#include <SoftwareSerial.h>
#include <Time.h>
#include "U8glib.h"

#define DEBUG false
#define syncInterval 60 * 60 //Sekunden
//Hardware
#define GPIO2 3     //ESP8266
#define GPIO0 4     //ESP8266
#define espReset 7  //ESP8266
#define espRX 13    //ESP8266
#define espTX 12    //ESP8266
#define gint 2      //Interrupt gesture Sensor

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);  //https://code.google.com/p/u8glib/wiki/u8glib?tm=6

SoftwareSerial ESP(espTX, 70); // RX, TX

// Variables
boolean readyCharOk1 = false;
boolean readyCharOk2 = false;
boolean readyCharOk3 = false;
boolean readyCharOk4 = false;
boolean readyCharOk5 = false;
byte x;
byte secondOld = 61;
unsigned long epoch;

void setup() {
  pinMode(GPIO0,OUTPUT);
  digitalWrite(GPIO0,HIGH);
  pinMode(GPIO2,OUTPUT);
  digitalWrite(GPIO2,HIGH);
  pinMode(espReset,OUTPUT);
  
  Serial.begin(9600);
  ESP.begin(9600);
  
  initEsp();
}

void loop() {
  
  
  if (secondOld != second()) {
    secondOld = second();
    drawTime();
    if (ESP.available()) epoch = readEspSerial();
  }
}
void setStdFont() {
    //u8g.setFont(u8g_font_helvB14);
    u8g.setFont(u8g_font_fub14r);
}

void drawScreen(String x) {
  setStdFont();
  u8g.firstPage();  
  do {
    u8g.setPrintPos(0, 32);
    u8g.print(x);
  } while( u8g.nextPage() );
}

void drawTime() {
  u8g.firstPage();  
  do {
    u8g.setPrintPos(5, 45);
    u8g.setFont(u8g_font_fub25r);
    if (hour() < 10) u8g.print("  ");
    u8g.print(hour());
    u8g.print(":");
    u8g.setFont(u8g_font_fur14);
    u8g.print(" ");
    u8g.setFont(u8g_font_fub25r);
    if (minute() < 10) u8g.print("0");
    u8g.print(minute());
    u8g.setFont(u8g_font_fur14);
    u8g.print(" ");
    if (second() < 10) u8g.print("0");
    u8g.print(second());
  } while( u8g.nextPage() );
}
unsigned long readEspSerial() {
  unsigned long t = 0;
  byte x = 0;
  
  do {
    if (ESP.available()) {
      x = ESP.read();
      if (DEBUG) Serial.print(char(x));
      if ((x >= 48) && (x <= 57)) {
        t = 10*t + (x - 48);
      } // if zahl
    }  // if Daten an EPS
  } while (x!= 10);
  
  return t;
} // readEspSerial

boolean adjustDstEurope(unsigned long i)
{
 // last sunday of march
 int beginDSTDate=  (31 - (5* year(i) /4 + 4) % 7);
 int beginDSTMonth=3;
 //last sunday of october
 int endDSTDate= (31 - (5 * year(i) /4 + 1) % 7);
 int endDSTMonth=10;
 // DST is valid as:
 if (((month(i) > beginDSTMonth) && (month(i) < endDSTMonth))
     || ((month(i) == beginDSTMonth) && (day(i) >= beginDSTDate))
     || ((month(i) == endDSTMonth) && (day(i) <= endDSTDate)))
 return true;  // DST europe = utc +2 hour
 else return false; // nonDST europe = utc +1 hour
}

time_t getTimeFromEsp() {
  time_t epoch;
  digitalWrite(GPIO2,HIGH);
  epoch = readEspSerial();
  digitalWrite(GPIO2,LOW);
    
  if (adjustDstEurope(epoch)) epoch = epoch + (2 * 3600);
    else epoch = epoch + 3600;

  return epoch;
}

void initEsp() {
  digitalWrite(GPIO2,HIGH);
  delay(50);
  drawScreen("Reset ESP");
  digitalWrite(espReset,LOW);
  delay(100);
  digitalWrite(espReset,HIGH);

  drawScreen("Wait for WiFi");
  while (!(readyCharOk1 && readyCharOk2 && readyCharOk3 && readyCharOk4 && readyCharOk5)) {
    if (ESP.available()) {
      x = ESP.read();
      if (DEBUG) Serial.print(char(x));
      if (char(x) == 'R') readyCharOk1 = true;
      if (char(x) == 'E') readyCharOk2 = true;
      if (char(x) == 'A') readyCharOk3 = true;
      if (char(x) == 'D') readyCharOk4 = true;
      if (char(x) == 'Y') readyCharOk5 = true;
    }
  } //while
  do {
    if (ESP.available()) x = ESP.read();
    } while (x!= 10);

  drawScreen("WiFi Ready");
  if (DEBUG) Serial.println();
  if (DEBUG) Serial.println();
  
  epoch = readEspSerial();
  digitalWrite(GPIO2,LOW);
  if (epoch != 0) setTime(epoch);
  
  drawScreen("Wait for NTP");
  setSyncProvider(getTimeFromEsp);
  setSyncInterval(syncInterval);
}

ESP code
Code:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
//
#define DEBUG true
#define periode 1000*10
//WiFi
char ssid[] = "Rohan";  //  your network SSID (name)
char pass[] = "Good Morning... Darling! @224477%";       // your network password
//NTP
unsigned int localPort = 2390;      // local port to listen for UDP packets
IPAddress timeServer(129, 6, 15, 28); // time.nist.gov 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
WiFiUDP udp;

void setup()
{
  pinMode(2,INPUT);
  Serial.begin(9600);
  if (DEBUG) Serial.println();
  if (DEBUG) Serial.println();

  // We start by connecting to a WiFi network
  if (DEBUG) Serial.print("Connecting to ");
  if (DEBUG) Serial.println(ssid);
  WiFi.begin(ssid, pass);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if (DEBUG) Serial.print(".");
  }
  if (DEBUG) Serial.println("");
  if (!DEBUG) Serial.println("WIFI READY");
  if (DEBUG) Serial.println("WiFi connected");
  if (DEBUG) Serial.println("IP address: ");
  if (DEBUG) Serial.println(WiFi.localIP());

  if (DEBUG) Serial.println("Starting UDP");
  udp.begin(localPort);
  if (DEBUG) Serial.print("Local port: ");
  if (DEBUG) Serial.println(udp.localPort());
}

void loop()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(1000);
  
  int cb = udp.parsePacket();
  if (!cb) {
    if (DEBUG)Serial.println("no packet yet");
  }
  else {
    if (DEBUG) Serial.print("packet received, length=");
    if (DEBUG) Serial.println(cb);
    // 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 secsSince1900 = highWord << 16 | lowWord;
    if (DEBUG) Serial.print("Seconds since Jan 1 1900 = " );
    if (DEBUG) Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    if (DEBUG) 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 the hour, minute and second:
    if (DEBUG) Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    if (DEBUG) Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    if (DEBUG) Serial.print(':');
    if ( ((epoch % 3600) / 60) < 10 ) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      if (DEBUG) Serial.print('0');
    }
    if (DEBUG) Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    if (DEBUG) Serial.print(':');
    if ( (epoch % 60) < 10 ) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      if (DEBUG) Serial.print('0');
    }
    if (DEBUG) Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(periode);
  do {
    delay(50);
  } while (!digitalRead(2));
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
{
  if (DEBUG) Serial.println("sending NTP packet...");
  // 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();
}

The ug8 library for the OLED display can be found here:
https://code.google.com/p/u8glib/

Admin
Admin

Posts : 7
Join date : 2015-06-02

https://desktopwidget.board-directory.net

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum