TolentinoCotesta

NTP ESP8266

Oct 11th, 2020 (edited)
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.27 KB | None | 0 0
  1. /*
  2.     This sketch shows how to use WiFi event handlers.
  3.  
  4.     In this example, ESP8266 works in AP mode.
  5.     Three event handlers are demonstrated:
  6.     - station connects to the ESP8266 AP
  7.     - station disconnects from the ESP8266 AP
  8.     - ESP8266 AP receives a probe request from a station
  9.  
  10.     Written by Markus Sattler, 2015-12-29.
  11.     Updated for new event handlers by Ivan Grokhotkov, 2017-02-02.
  12.     This example is released into public domain,
  13.     or, at your option, CC0 licensed.
  14. */
  15.  
  16. #include <ESP8266WiFi.h>
  17. #include <stdio.h>
  18. #include <time.h>
  19. #include <sys/time.h>  
  20. #include <PolledTimeout.h>
  21.  
  22. // Definizione del timezone e degli intervalli dell'ora legale
  23. #define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"
  24.  
  25. // struct dove memorizzare le informazioni realtive al timedate (giorno, ora, minuti,  etc etc )
  26. struct tm timeinfo;    // è definita in "time.h"
  27.  
  28. // timer con frequenza di 1Hz
  29. static esp8266::polledTimeout::periodicMs showTimeNow(1000);
  30.  
  31. #ifndef APSSID
  32. #define APSSID "xxxxxxx"
  33. #define APPSK  "xxxxxxx"
  34. #endif
  35.  
  36. const char* ssid     = APSSID;
  37. const char* password = APPSK;
  38.  
  39. WiFiEventHandler connectedHandler;
  40. WiFiEventHandler disconnectedHandler;
  41. WiFiEventHandler gotIpEventHandler;
  42.  
  43. void setup() {
  44.   Serial.begin(115200);
  45.   WiFi.begin(ssid, password);
  46.  
  47.   // Register event handlers.
  48.   // Callback functions will be called as long as these handler objects exist.
  49.   connectedHandler = WiFi.onStationModeConnected(&onConnected);
  50.   disconnectedHandler = WiFi.onStationModeDisconnected(&onDisconnected);
  51.   gotIpEventHandler = WiFi.onStationModeGotIP(&onStationGotIp);
  52. }
  53.  
  54. void onStationGotIp(const WiFiEventStationModeGotIP& evt) {
  55.   Serial.print("Station ip address: ");
  56.   Serial.println(WiFi.localIP());      
  57.   configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
  58. }
  59.  
  60.  
  61. void onConnected(const WiFiEventStationModeConnected& evt) {
  62.   Serial.print("ESP connected: ");
  63. }
  64.  
  65. void onDisconnected(const WiFiEventStationModeDisconnected& evt) {
  66.   Serial.print("ESP disconnected: ");
  67. }
  68.  
  69.  
  70. void showTime() {
  71.   time_t now = time(nullptr);
  72.   timeinfo = *localtime(&now);
  73.  
  74.   char buffer [40];
  75.   strftime (buffer,40,"%A, %D %T", &timeinfo);
  76.   Serial.println(buffer);
  77. }
  78.  
  79. void loop() {
  80.   if (showTimeNow)
  81.      showTime();
  82. }
  83.  
Add Comment
Please, Sign In to add comment