esp32-通过wifi使用timelib库同步时间(三)

库的安装

本文基于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 time
  Serial.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 0
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ---------*/

time_t getNtpTime()
{
  IPAddress ntpServerIP; // NTP server's ip address

  while (Udp.parsePacket() > 0)
    ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  // get a random server from the pool
  WiFi.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 buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 = (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 0
  memset(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, 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;
  // 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 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

实验结果如下

相关推荐

  1. ESP32常用之<WiFi.h>详解

    2024-04-21 03:02:05       34 阅读
  2. ESP32-WIFI(Arduino)

    2024-04-21 03:02:05       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 03:02:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 03:02:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 03:02:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 03:02:05       20 阅读

热门阅读

  1. Android JNI使用dlopen动态链接库

    2024-04-21 03:02:05       16 阅读
  2. Kibana启动报错:Kibana server is not ready yet

    2024-04-21 03:02:05       14 阅读
  3. konva.js 工具类

    2024-04-21 03:02:05       12 阅读
  4. 设计模式(分类)

    2024-04-21 03:02:05       12 阅读
  5. OpenXR API概览与核心组件解析

    2024-04-21 03:02:05       15 阅读
  6. NLP和LLMs: 理解它们之间的区别

    2024-04-21 03:02:05       14 阅读