在单片机开发过程中(基于树莓派的嵌入式可忽略),我们经常会遇到设置好的时间由于断电或其他原因不得不重新设置。
闲来无事波波就补充一篇Arduino利用Esp8266同步NTP服务器时间的笔记吧。
在本篇笔记中我们需要用到一个NTP类库,下载地址>>NTPclient-3.2.0.zip
代码片段:
- #include <ESP8266WiFi.h>
- #include <NTPClient.h>
- #include <WiFiUdp.h>
- const char *ssid = "WIFI信道";
- const char *password = "WIFI密码";
- WiFiUDP ntpUDP;
- NTPClient timeClient(ntpUDP, "pool.ntp.org");
- String weekDays[7]={"Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};
- //Month names
- String months[12]={"January", "February", "March", "April","May", "June", "July", "August", "September", "October", "November", "December"};
- void setup() {
- // Initialize Serial Monitor
- Serial.begin(115200);
- // Connect to Wi-Fi
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- // Initialize a NTPClient to get time
- timeClient.begin();
- //设置偏移时间(以秒为单位)以调整时区,例如:
- // GMT +1 = 3600
- // GMT +8 = 28800
- // GMT -1 = -3600
- // GMT 0 = 0
- timeClient.setTimeOffset(28800);
- }
- void loop() {
- timeClient.update();
- //获取时间戳
- unsigned long epochTime = timeClient.getEpochTime();
- Serial.print("Epoch Time: ");
- Serial.println(epochTime);
- //转化为当前时间
- String formattedTime = timeClient.getFormattedTime();
- Serial.print("Formatted Time: ");
- Serial.println(formattedTime);
- int currentHour = timeClient.getHours();
- Serial.print("Hour: ");
- Serial.println(currentHour);
- int currentMinute = timeClient.getMinutes();
- Serial.print("Minutes: ");
- Serial.println(currentMinute);
- int currentSecond = timeClient.getSeconds();
- Serial.print("Seconds: ");
- Serial.println(currentSecond);
- String weekDay = weekDays[timeClient.getDay()];
- Serial.print("Week Day: ");
- Serial.println(weekDay);
- //Get a time structure
- struct tm *ptm = gmtime ((time_t *)&epochTime);
- int monthDay = ptm->tm_mday;
- Serial.print("Month day: ");
- Serial.println(monthDay);
- int currentMonth = ptm->tm_mon+1;
- Serial.print("Month: ");
- Serial.println(currentMonth);
- String currentMonthName = months[currentMonth-1];
- Serial.print("Month name: ");
- Serial.println(currentMonthName);
- int currentYear = ptm->tm_year+1900;
- Serial.print("Year: ");
- Serial.println(currentYear);
- //Print complete date:
- String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
- Serial.print("Current date: ");
- Serial.println(currentDate);
- Serial.println("");
- delay(2000);
- }
关于时间的同步问题我们可以设置成Arduino启动时自动同步一次,也可以设置定时同步。至于怎么同步就不再赘述了。