库的安装
本文基于platformIO,安装较为简单如下图
实例代码
完整代码如下,如果时间获取超时请使用time1.aliyun.com获取时间。
/** Time_NTP.pde* Example showing time sync to NTP time source** This sketch uses the Ethernet library*/#include <WiFi.h>
#include <TimeLib.h>
#include <WiFiUdp.h>struct config_type
{char stassid[32]; // 定义配网得到的WIFI名长度(最大32字节)char stapsw[64]; // 定义配网得到的WIFI密码长度(最大64字节)
};
//---------------修改此处""内的信息--------------------
// 如开启WEB配网则可不用设置这里的参数,前一个为wifi ssid,后一个为密码
config_type wificonf = {{"PDCN"}, {"1234567890"}};
// NTP Servers:
static const char ntpServerName[] = "time1.aliyun.com"; // 阿里云的时间服务器
/* NTP设置 */
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming & outgoing packets
const int timeZone = 8; // 时区WiFiUDP Udp;
unsigned int localPort = 8888; // local port to listen for UDP packets/*申明函数*/
time_t getNtpTime();
char *num_week(uint8_t dayofweek, int Mode); // 计算星期
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);void setup()
{Serial.begin(115200);delay(250);Serial.println("TimeNTP Example");Serial.print("Connecting to ");Serial.println(wificonf.stassid);WiFi.begin(wificonf.stassid, wificonf.stapsw);while (WiFi.status() != WL_CONNECTED){delay(500);Serial.print(".");}Serial.print("本地IP:");Serial.println(WiFi.localIP());Serial.println("启动UDP");Udp.begin(localPort);Serial.print("本地端口号: ");Serial.println(Udp.remotePort());Serial.println("waiting for sync");setSyncProvider(getNtpTime);setSyncInterval(300);
}void loop()
{//now();digitalClockDisplay();delay(1000);
}/*
@功能:判断星期并赋值
*/
char week1[10], week2[8], week3[3], week4[4];
char *num_week(uint8_t dayofweek, int Mode)
{switch (dayofweek){case 1:strcpy(week1, "Sunday");strcpy(week2, "周日");strcpy(week3, "Su");strcpy(week4, "日");break;case 2:strcpy(week1, "Monday");strcpy(week2, "周一");strcpy(week3, "Mo");strcpy(week4, "一");break;case 3:strcpy(week1, "Tuesday");strcpy(week2, "周二");strcpy(week3, "Tu");strcpy(week4, "二");break;case 4:strcpy(week1, "Wednesday");strcpy(week2, "周三");strcpy(week3, "We");strcpy(week4, "三");break;case 5:strcpy(week1, "Thursday");strcpy(week2, "周四");strcpy(week3, "Th");strcpy(week4, "四");break;case 6:strcpy(week1, "Friday");strcpy(week2, "周五");strcpy(week3, "Fr");strcpy(week4, "五");break;case 7:strcpy(week1, "Saturday");strcpy(week2, "周六");strcpy(week3, "Sa");strcpy(week4, "六");break;default:strcpy(week1, "NO");strcpy(week2, "无");strcpy(week3, "NO");strcpy(week4, "无");break;}switch (Mode){case 1:return week1;break;case 2:return week2;break;case 3:return week3;break;case 4:return week4;break;}
}void digitalClockDisplay()
{// digital clock display of the timeSerial.print(year());Serial.print("/");Serial.print(month());Serial.print("/");Serial.print(day());Serial.print(" ");Serial.print(hour());printDigits(minute());printDigits(second());Serial.print(" 星期");Serial.print(num_week(weekday(), 4));Serial.println();
}void printDigits(int digits)
{// utility for digital clock display: prints preceding colon and leading 0Serial.print(":");if (digits < 10)Serial.print('0');Serial.print(digits);
}/*-------- NTP code ---------*/time_t getNtpTime()
{IPAddress ntpServerIP; // NTP server's ip addresswhile (Udp.parsePacket() > 0); // discard any previously received packetsSerial.println("Transmit NTP Request");// get a random server from the poolWiFi.hostByName(ntpServerName, ntpServerIP);Serial.print(ntpServerName);Serial.print(": ");Serial.println(ntpServerIP);sendNTPpacket(ntpServerIP);uint32_t beginWait = millis();while (millis() - beginWait < 1500){int size = Udp.parsePacket();if (size >= NTP_PACKET_SIZE){Serial.println("Receive NTP Response");Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the bufferunsigned long secsSince1900;// convert four bytes starting at location 40 to a long integersecsSince1900 = (unsigned long)packetBuffer[40] << 24;secsSince1900 |= (unsigned long)packetBuffer[41] << 16;secsSince1900 |= (unsigned long)packetBuffer[42] << 8;secsSince1900 |= (unsigned long)packetBuffer[43];return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;}}Serial.println("No NTP Response :-(");return 0; // return 0 if unable to get the time
}// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{// set all bytes in the buffer to 0memset(packetBuffer, 0, NTP_PACKET_SIZE);// Initialize values needed to form NTP request// (see URL above for details on the packets)packetBuffer[0] = 0b11100011; // LI, Version, ModepacketBuffer[1] = 0; // Stratum, or type of clockpacketBuffer[2] = 6; // Polling IntervalpacketBuffer[3] = 0xEC; // Peer Clock Precision// 8 bytes of zero for Root Delay & Root DispersionpacketBuffer[12] = 49;packetBuffer[13] = 0x4E;packetBuffer[14] = 49;packetBuffer[15] = 52;// all NTP fields have been given values, now// you can send a packet requesting a timestamp:Udp.beginPacket(address, 123); // NTP requests are to port 123Udp.write(packetBuffer, NTP_PACKET_SIZE);Udp.endPacket();
}
实验结果如下