使用NTP服务需要先安装 NTPClient 库,在库管理中搜索NTP进行下载
- 项目->加载库->管理库
- 搜索ntp,安装NTPClient库
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char *ssid = "abcd";
const char *password = "12345678";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000);
void setup(){
Serial.begin(9600);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
Serial.println("");
Serial.println(WiFi.localIP()); //打印出当前IP地址
timeClient.begin();
}
void loop() {
timeClient.update();
Serial.println(timeClient.getFormattedTime());
int hours = timeClient.getHours(); //获取小时
int minu = timeClient.getMinutes(); //获取分钟
int sece = timeClient.getSeconds(); //获取秒
Serial.printf("hour:%d minu:%d sece:%d\n", hours,minu,sece);
delay(10000);
}