ESP8266 获取 NTP 时间代码
时间: 2023-05-18 09:03:57 浏览: 99
获取NTP服务器授时中心时间源代码
以下是 ESP8266 获取 NTP 时间的代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
unsigned int localPort = 2390; // 本地端口号
IPAddress timeServer(129, 6, 15, 28); // NTP服务器地址
const int NTP_PACKET_SIZE = 48; // NTP数据包大小
byte packetBuffer[NTP_PACKET_SIZE]; // NTP数据包缓存
WiFiUDP udp; // UDP客户端
void setup() {
Serial.begin(115200);
WiFi.begin("SSID", "PASSWORD"); // 连接WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
udp.begin(localPort); // 开始UDP客户端
}
void loop() {
sendNTPpacket(timeServer); // 发送NTP数据包
delay(1000);
if (udp.parsePacket()) { // 如果收到UDP数据包
udp.read(packetBuffer, NTP_PACKET_SIZE); // 读取数据包
unsigned long secsSince1900;
// 将数据包中的时间戳转换为Unix时间戳
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
// 将Unix时间戳转换为本地时间
unsigned long epoch = secsSince1900 - 2208988800UL;
Serial.println(epoch);
}
}
void sendNTPpacket(IPAddress& address) {
memset(packetBuffer, 0, NTP_PACKET_SIZE); // 清空缓存
packetBuffer[0] = 0b11100011; // NTP头部
packetBuffer[1] = 0; // 精度
packetBuffer[2] = 6; // 间隔
packetBuffer[3] = 0xEC; // 版本号
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(address, 123); // 发送UDP数据包
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}
阅读全文