esp8266如何获取形如2019-03-05 015312的时间
ESP8266可以通过以下步骤获取形如“2019-03-05 01:53:12”的时间:
-
连接到Wi-Fi网络并获取当前时间。可以使用NTP协议来获取网络时间,也可以使用自己的服务器或其他时间源。
-
将获取到的时间转换成字符串。可以使用strftime函数将时间格式化为需要的字符串格式。
-
将字符串转换成时间结构体。可以使用strptime函数将字符串转换成tm结构体。
-
可以使用tm结构体的成员变量来获取需要的时间信息,如年、月、日、小时、分钟、秒等。
示例代码如下:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <time.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* ntpServerName = "pool.ntp.org";
const int timeZone = 8;
WiFiUDP Udp;
unsigned int localPort = 8888;
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");
Udp.begin(localPort);
Serial.println("UDP started");
setSyncProvider(getNtpTime);
setSyncInterval(300);
}
void loop() {
time_t now = time(nullptr);
char timeStr[20];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localtime(&now));
Serial.println(timeStr);
delay(1000);
}
time_t getNtpTime() {
IPAddress ntpServerIP;
while (Udp.parsePacket() > 0); // discard any previously received packets
Serial.println("Transmit NTP Request");
WiFi.hostByName(ntpServerName, ntpServerIP);
sendNTPPacket(ntpServerIP);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
byte packetBuffer[NTP_PACKET_SIZE];
Udp.read(packetBuffer, NTP_PACKET_SIZE);
unsigned long secsSince1900 = (unsigned long)packetBuffer[40] << 24 |
(unsigned long)packetBuffer[41] << 16 |
(unsigned long)packetBuffer[42] << 8 |
(unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
delay(10);
}
Serial.println("No NTP Response :-(");
return 0;
}
void sendNTPPacket(IPAddress& address) {
byte packetBuffer[NTP_PACKET_SIZE];
memset(packetBuffer, 0, NTP_PACKET_SIZE);
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
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
Udp.beginPacket(address, 123);
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
注意:以上代码使用了NTP协议来获取网络时间,需要连接到Wi-Fi网络,并且需要访问外部时间服务器。如果使用自己的服务器或其他时间源,请相应修改代码。
原文地址: https://www.cveoy.top/t/topic/bfk1 著作权归作者所有。请勿转载和采集!