编写程序使用esp8266获取时间
时间: 2023-07-30 13:06:12 浏览: 128
esp8266-12E程序time程序(直接在esp8266上进行烧写)
可以使用ESP8266连接到NTP服务器获取时间。以下是一些基本的代码示例:
```C++
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Define NTP Servers:
IPAddress timeServerIP; // NTP server IP address
const char* ntpServerName = "pool.ntp.org";
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Set NTP server IP address
WiFi.hostByName(ntpServerName, timeServerIP);
}
void loop() {
// Send an NTP request to the time server
sendNTPpacket(timeServerIP);
// Wait for response
delay(1000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("No packet yet");
}
else {
Serial.print("Packet received, length=");
Serial.println(cb);
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE);
// The timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, extract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// Combine the four bytes (two words) into a long integer
unsigned long secsSince1900 = highWord << 16 | lowWord;
// Subtract seventy years (1970-1900) to get Unix time
const unsigned long seventyYears = 2208988800UL;
unsigned long epoch = secsSince1900 - seventyYears;
// Print the Unix time:
Serial.print("Unix time = ");
Serial.println(epoch);
}
}
// Send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address) {
// Set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
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
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// Send NTP request
udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}
```
这段代码会连接到Wi-Fi网络,然后从NTP服务器获取当前时间并将其显示在串口终端上。你需要替换代码中的Wi-Fi凭证和NTP服务器名称以适应你的环境。
阅读全文