esp8266获取当前时间通过串口打印yyyymmdd hhmmss的格式给我代码
以下是ESP8266获取当前时间并通过串口打印“yyyy:mm:dd hh:mm:ss”的代码:
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <TimeLib.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
configTime(0, 0, "pool.ntp.org"); //获取网络时间
while (!time(nullptr)) {
delay(1000);
Serial.println("Waiting for NTP time sync...");
}
}
void loop() {
time_t now = time(nullptr);
if (now != 0) {
Serial.println("Current time is: ");
Serial.print(year(now));
Serial.print(":");
Serial.print(month(now));
Serial.print(":");
Serial.print(day(now));
Serial.print(" ");
Serial.print(hour(now));
Serial.print(":");
Serial.print(minute(now));
Serial.print(":");
Serial.println(second(now));
} else {
Serial.println("Failed to get NTP time");
}
delay(1000);
}
需要先连接到WiFi并获取网络时间,然后在loop循环中获取当前时间并通过串口打印。
原文地址: http://www.cveoy.top/t/topic/bfxF 著作权归作者所有。请勿转载和采集!