esp8266获取时间的简单方法
时间: 2023-10-24 22:08:39 浏览: 133
可以使用NTP协议获取当前的时间。以下是使用Arduino IDE编写的ESP8266获取时间的示例代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
WiFiUDP udp;
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* ntpServerName = "pool.ntp.org";
const int timeZone = 8;
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(123);
Serial.println("UDP started");
setSyncInterval(300);
setSyncProvider(getNtpTime);
}
void loop() {
time_t now = time(nullptr);
if (now > 0) {
Serial.println(ctime(&now));
}
delay(1000);
}
time_t getNtpTime() {
IPAddress ntpServerIP;
WiFi.hostByName(ntpServerName, ntpServerIP);
Serial.print("NTP server IP address: ");
Serial.println(ntpServerIP);
byte packetBuffer[48];
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();
delay(1000);
int packetSize = udp.parsePacket();
if (packetSize == 0) {
Serial.println("No NTP packet received");
return 0;
}
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("NTP time: ");
Serial.println(epoch);
return epoch + timeZone * 3600;
}
```
这个示例代码将ESP8266连接到Wi-Fi网络,并使用NTP协议从ntpServerName变量指定的NTP服务器获取当前时间。获取时间的函数是`getNtpTime()`,它会返回从1970年1月1日0时0分0秒到现在的秒数。在`setup()`函数中,我们设置了时间同步间隔为300秒,并将`getNtpTime()`函数设置为时间同步提供程序。在`loop()`函数中,我们使用`time()`函数获取当前时间,并使用`ctime()`函数将其格式化为可读的字符串。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)