ESP8266 获取网络时间
时间: 2023-05-17 22:06:15 浏览: 188
可以使用 NTP 协议获取网络时间,具体实现可以参考以下代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiUDP udp;
unsigned int localPort = 8888;
char packetBuffer[48];
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);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
sendNTPpacket();
delay(1000);
if (udp.parsePacket()) {
udp.read(packetBuffer, 48);
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = highWord << 16 | lowWord;
const unsigned long seventyYears = 2208988800UL;
unsigned long epoch = secsSince1900 - seventyYears;
Serial.print("Unix time: ");
Serial.println(epoch);
}
}
}
void sendNTPpacket() {
IPAddress ntpServerIP(129, 6, 15, 28);
memset(packetBuffer, 0, 48);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(ntpServerIP, 123);
udp.write(packetBuffer, 48);
udp.endPacket();
}
阅读全文