RuiViana

Estudo_RTCs.ino

Nov 1st, 2021 (edited)
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.12 KB | None | 0 0
  1. #include <NTPClient.h>                  // Biblioteca do NTP  
  2. #include <ESP8266WiFi.h>                // Biblioteca do WiFi  
  3. #include <WiFiUdp.h>                    // Biblioteca do UDP  
  4. WiFiUDP UDP;                            // Instancia UDP
  5. NTPClient timeClient(UDP, "a.st1.ntp.br", -3 * 3600, 60000);  // Cria um objeto "NTP" e corrige fuso
  6. #include <Wire.h>                       // I2C library
  7. #include <LiquidCrystal_I2C.h>          // Biblioteca LCD I2C  
  8. //LiquidCrystal_I2C lcd(0x39,  2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Endereco LCD I2C  (Invertido)
  9. LiquidCrystal_I2C lcd(0x39,  2, 1, 0, 7, 6, 5, 4, 3, POSITIVE); // Endereco LCD I2C e pinos
  10. #include <RTClib.h>                     // RTC library
  11. RTC_DS3231 rtc;                         // Instancia RTC
  12. DateTime now;                           // variavel formato DateTime para RTC
  13. #include <Ticker.h>                     // Biblioteca Tiker
  14. Ticker flipper;                         // Instancia Tiker
  15.  
  16. #define SDA 0                           // SDA do bus I2C
  17. #define SCL 4                           // SCL do bus I2C
  18.  
  19. int segESP = 0;                         // Segundos gerados pelo ESP
  20. int segNTP = 0;                         // Segundos gerados pelo NTP
  21. int segRTC = 0;                         // Segundos gerados pelo RTC
  22. bool newSeg = false;                    // Controle de comparacao
  23. unsigned long horasTeste = 0;           // Contador de horas de teste
  24. //--------------------------------------------------------------
  25. void relogio()
  26. {
  27.   Serial.print("segNTP "); Serial.println(segNTP);    // Print
  28.   Serial.print("segRTC "); Serial.println(segRTC);    // Print
  29.   Serial.print("segESP "); Serial.println(segESP);    // Print
  30.   Serial.println(" ");                                // Print
  31.  
  32.   lcd.setCursor(0, 1);                                // Posicao linha
  33.   lcd.print(segNTP - segESP   );                      // Print diferenca entre segNTP e segESP
  34.   lcd.print("  ");                                    // Print
  35.   lcd.setCursor(4, 1);                                // Posicao linha
  36.   lcd.print(segRTC - segNTP );                        // Print diferenca entre segRTC e segNTP
  37.   lcd.setCursor(8, 1);                                // Posicao linha
  38.   lcd.print(horasTeste / 60 );                        // Print time atualizado
  39.   lcd.print("    ");                                  // Print
  40.   lcd.setCursor(14, 1);                               // Posicao linha
  41.   lcd.print(segNTP );                                 // Print Segundos do NTP
  42.   lcd.print("  ");                                    // Print
  43. }
  44. //-----------------------------------------------------------------------
  45. void flip() {
  46.   String tempSeg;                                           // Varavel de trabalho
  47.   ++segESP;                                                 // Incrementa segESP a cada segundo
  48.   if (segESP == 60)                                         // Completou 1 minuto
  49.   {
  50.     segESP = 0;                                             // Reincia segESP
  51.     horasTeste++;                                           // Incrementa contador (horas em minutos)
  52.   }
  53.   tempSeg = timeClient.getFormattedTime().substring(6);     // Busca segundo do NTP
  54.   segNTP = tempSeg.toInt();                                 // Converte para inteiro
  55.   newSeg = true;                                            // Informa que contou segundo;
  56. }
  57. //-----------------------------------------------------------------------
  58. void setup() {
  59.   Serial.begin(115200);                                     // Inicializa Serial
  60.   Wire.begin(SDA, SCL);                                     // Inicializa I2C
  61.   lcd.begin(16, 2);                                         // Inicializa LCD
  62.   lcd.clear();                                              // Limpa LCD
  63.  
  64.   lcd.setCursor(0, 0);                                      // Posicao linha
  65.   lcd.print("Synk relogios.");                              // Print time atualizado                                      
  66.  
  67.   lcd.setCursor(0, 1);                                      // Posicao linha
  68.   WiFi.begin(ssid, password);                               // Conecta na rede (Digitie aqui suas credenciais)
  69.   while ( WiFi.status() != WL_CONNECTED ) {                 // Enquanto nao conecta
  70.     delay ( 500 );                                          // Aguarda nova tentativa
  71.     Serial.print ( "." );                                   // Print
  72.     lcd.print(".");                                         // Print
  73.   }
  74.   Serial.println(" ");                                      // Print
  75.   Serial.print("Servidor iniciado com o IP \"");            // Print
  76.   Serial.print(WiFi.localIP());                             // Informe IP obtido pelo DHCP
  77.   Serial.println(" ");                                      // Print
  78.   timeClient.begin();                                       // Inicializa NTP
  79.   timeClient.update();                                      // Aguarda atualizacao
  80.   timeClient.forceUpdate();                                 // Forca atualizacao
  81.  
  82.   rtc.begin();                                              // Inicializa RTC
  83.  
  84.   lcd.clear();                                              // Limpa LCD
  85.   lcd.setCursor(0, 0);                                      // Posicao linha
  86.   lcd.print("ESP");                                         // Print titulo
  87.   lcd.print(" ");                                           // Print
  88.   lcd.print("RTC");                                         // Print titulo
  89.   lcd.print(" ");                                           // Print
  90.   lcd.print("HTst");                                        // Print titulo
  91.   lcd.print(" ");                                           // Print
  92.   lcd.print("Seg");                                         // Print titulo
  93.   lcd.print(" ");                                           // Print
  94.  
  95.   int oldTemp = 0;                                          // Variavel para ajudar na sincronizacao dos relogios
  96.   String tempSeg;                                           // Varavel de trabalho
  97.   flipper.attach(1, flip);                                  // Define tempo e nome da rotina de interrupt
  98.  
  99.   tempSeg = timeClient.getFormattedTime().substring(6);     // Busca segundo do NTP
  100.   segNTP = tempSeg.toInt();                                 // Converte para inteiro
  101.   oldTemp = segNTP;                                         // Salva o valor para comparacao
  102.   while (segNTP == oldTemp)                                 // Quamdo forem diferentes mudou o segundo em NTP
  103.   {
  104.     delay(10);                                              // Tempo para não travar o ESP
  105.     tempSeg = timeClient.getFormattedTime().substring(6);   // Busca segundo do NTP
  106.     segNTP = tempSeg.toInt();                               // Converte para inteiro
  107.   }
  108.  
  109.   if (segNTP == 0)                                          // Verifica se é final de contagm de segundo
  110.     segESP = 59;                                            // Recua 1 segundo para sincronizar
  111.   else                                                      // Ou em outros segundos
  112.     segESP = segNTP - 1;                                    // Recua 1 segundo para sincronizar
  113.  
  114.   rtc.adjust(DateTime(2021, 11, 01, 0, 0, segNTP));         // Atualiza os segundo do RTC3231
  115.   now = rtc.now();                                          // Le o RTC
  116.   tempSeg = now.second();                                   // Separa o segundo
  117.   segRTC = tempSeg.toInt();                                 // Converte para numero inteiro
  118. }
  119. //-----------------------------------------------------------------------
  120. void loop() {
  121.   if (newSeg == true)                                       // Se passou 1 segundo
  122.   {
  123.     String tempSeg;                                         // Varavel de trabalho
  124.     now = rtc.now();                                        // Le o RTC
  125.     tempSeg = now.second();                                 // Separa o segundo
  126.     segRTC = tempSeg.toInt();                               // Converte para numero inteiro
  127.     relogio();                                              // Compara e mostra
  128.     newSeg = false;                                         // Aguarda novo segundo
  129.   }
  130. }
  131.  
Add Comment
Please, Sign In to add comment