使用 NTP 服务器让 ESP32 同步闪烁 LED 的时间

Having ESP32 synchronized time for blinking LED using NTP sever

我想每 5 秒使 ESP32 板载 LED(引脚 2)闪烁一次。我已经设置了一个程序来设置 NTP 服务器的时间。将相同代码加载到 3 个不同的 ESP32 后,LED 每 5 秒闪烁一次,但不是同时闪烁。这是硬件问题还是我的代码不正确? (另外,有没有更简单的方法来做到这一点?)。提前致谢!

#include <WiFi.h>
#include <TimeLib.h>

// Wifi Credentials
const char* ssid       = "OhanaAhimsa";
const char* password   = "Fam2021Wow!";

//NTP Sever initalization
const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

// start now time variable in seconds
//int time_now = now();
//int second ();

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);

  // initialize digital pin LED_BUILTIN as an output.
  pinMode(2, OUTPUT);

// Connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");
  
  //init and get the time
 configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}
  
void loop() {

 // if (now() > time_now) {

    // Reset the time_now to now
  //  time_now = now();
    
    // print out seconds:
  // Serial.println(time_now);
   Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    // Sets the LED on or off depending on time_now being pair or odd
    digitalWrite(2, second() % 5);
  }

void printLocalTime(){
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  Serial.print("Day of week: ");
  Serial.println(&timeinfo, "%A");
  Serial.print("Month: ");
  Serial.println(&timeinfo, "%B");
  Serial.print("Day of Month: ");
  Serial.println(&timeinfo, "%d");
  Serial.print("Year: ");
  Serial.println(&timeinfo, "%Y");
  Serial.print("Hour: ");
  Serial.println(&timeinfo, "%H");
  Serial.print("Hour (12 hour format): ");
  Serial.println(&timeinfo, "%I");
  Serial.print("Minute: ");
  Serial.println(&timeinfo, "%M");
  Serial.print("Second: ");
  Serial.println(&timeinfo, "%S");

  Serial.println("Time variables");
  char timeHour[3];
  strftime(timeHour,3, "%H", &timeinfo);
  Serial.println(timeHour);
  char timeWeekDay[10];
  strftime(timeWeekDay,10, "%A", &timeinfo);
  Serial.println(timeWeekDay);
  Serial.println();
}

您没有等到从 NTP 服务器检索到时间,也没有将时间设置到 TimeLib 中。

添加

  time_t now = time(nullptr);
  while (now < SECS_YR_2000) { // wait until time is retrieved
    delay(100);
    now = time(nullptr);
  }
  setTime(now); // sets the time in TimeLib

使用 setSyncProvidersetSyncInterval 您可以设置 TimeLib 以定期与 ESP32 RTC(从 NTP 设置)同步。请参阅 TimeLib 的示例。