esp8266时钟代码
时间: 2023-05-25 13:05:21 浏览: 156
以下是一个 ESP8266 的时钟代码示例,可以在 Arduino IDE 中使用。在此示例中,将 ESP8266 连接到互联网,并使用简单的 HTTP 请求从一个在线时钟 API 获取时间。
```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "your_SSID"; // WIFI SSID
const char* password = "your_PASSWORD";// WIFI PASSWORD
const char* host = "worldtimeapi.org"; // API host
const char* endpoint = "/api/ip"; // API endpoint
const int httpPort = 80;
void setup() {
Serial.begin(9600);
delay(10);
// Connect to WIFI
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Make a HTTP request
WiFiClient client;
HTTPClient http;
if (http.begin(client, host, httpPort, endpoint)) {
Serial.println("HTTP request started");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println("HTTP request done");
Serial.println(payload);
// Extract current time from the API response
int index = payload.indexOf("currentDateTime") + 18;
String datetime = payload.substring(index, index+19);
Serial.println("Current time: " + datetime);
// Display time on Serial Monitor
Serial.print("Hours: ");
Serial.println(datetime.substring(11, 13));
Serial.print("Minutes: ");
Serial.println(datetime.substring(14, 16));
Serial.print("Seconds: ");
Serial.println(datetime.substring(17, 19));
} else {
Serial.println("HTTP request failed");
}
http.end();
} else {
Serial.println("Unable to connect");
}
delay(1000);
}
```
请确保将代码中的 WIFI SSID 和密码更改为您自己的网络凭据。 运行此代码后,在串行监视器窗口中就会显示当前时间。例如,如果当前时间是下午 2:30,它将显示以下输出:
```
Current time: 2021-10-16T14:30:45
Hours: 14
Minutes: 30
Seconds: 45
```
阅读全文