509|0

250

帖子

5

TA的资源

纯净的硅(初级)

楼主
 

【得捷电子Follow me第4期】进阶任务:从NTP服务器同步时间 [复制链接]

 

本身我们的arduino上面就有NTP服务器获取时间的例程,所以我在基础上稍微修改了下,显示了日期和时间。

/*



 Udp NTP Client



 Get the time from a Network Time Protocol (NTP) time server

 Demonstrates use of UDP sendPacket and ReceivePacket

 For more on NTP time servers and the messages needed to communicate with them,

 see http://en.wikipedia.org/wiki/Network_Time_Protocol



 created 4 Sep 2010

 by Michael Margolis

 modified 9 Apr 2012

 by Tom Igoe

 modified 02 Sept 2015

 by Arturo Guadalupi



 This code is in the public domain.



 */



#include <SPI.h>

#include <Ethernet.h>

#include <EthernetUdp.h>



// Enter a MAC address for your controller below.

// Newer Ethernet shields have a MAC address printed on a sticker on the shield

byte mac[] = {

  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED

};



unsigned int localPort = 8888;       // local port to listen for UDP packets



const char timeServer[] = "ntp1.aliyun.com"; // time.nist.gov NTP server



const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message



byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets



// A UDP instance to let us send and receive packets over UDP

EthernetUDP Udp;



void setup() {

  // You can use Ethernet.init(pin) to configure the CS pin

  //Ethernet.init(10);  // Most Arduino shields

  //Ethernet.init(5);   // MKR ETH shield

  //Ethernet.init(0);   // Teensy 2.0

  //Ethernet.init(20);  // Teensy++ 2.0

  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet

  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  Ethernet.init(17);  // WIZnet W5100S-EVB-Pico W5500-EVB-Pico W6100-EVB-Pico



  // Open serial communications and wait for port to open:

  Serial.begin(9600);

  while (!Serial) {

    ; // wait for serial port to connect. Needed for native USB port only

  }



  // start Ethernet and UDP

  if (Ethernet.begin(mac) == 0) {

    Serial.println("Failed to configure Ethernet using DHCP");

    // Check for Ethernet hardware present

    if (Ethernet.hardwareStatus() == EthernetNoHardware) {

      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");

    } else if (Ethernet.linkStatus() == LinkOFF) {

      Serial.println("Ethernet cable is not connected.");

    }

    // no point in carrying on, so do nothing forevermore:

    while (true) {

      delay(1);

    }

  }

  Udp.begin(localPort);

}



void loop() {

  sendNTPpacket(timeServer); // send an NTP packet to a time server



  // wait to see if a reply is available

  delay(1000);

  if (Udp.parsePacket()) {

    // We've received a packet, read the data from it

    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer



    // the timestamp starts at byte 40 of the received packet and is four bytes,

    // or two words, long. First, extract the two words:



    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);

    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

    // combine the four bytes (two words) into a long integer

    // this is NTP time (seconds since Jan 1 1900):

    unsigned long secsSince1900 = highWord << 16 | lowWord;



    unsigned long n=0,d=0,total_d=0,rz=0;

    uint32_t p_year_total_sec;

    uint32_t r_year_total_sec;

    uint16_t y=0,r=0,yr=0;

    uint8_t yf=0;

    signed long long yd=0;



    Serial.print("Seconds since Jan 1 1900 = ");

    Serial.println(secsSince1900);



    // now convert NTP time into everyday time:

    Serial.print("Unix time = ");

    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:

    const unsigned long seventyYears = 2208988800UL;

    // subtract seventy years:

    unsigned long epoch = secsSince1900 - seventyYears;

    // print Unix time:

    Serial.println(epoch);



    // print the hour, minute and second:

    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)

   

    n = epoch;

    total_d = epoch/(86400);

    d=0;

    p_year_total_sec=86400*365;

    r_year_total_sec=86400*366;

    while(n>=p_year_total_sec) 

    {

      if((1970+r)%400==0 || ((1970+r)%100!=0 && (1970+r)%4==0))

      {

        n = n -(r_year_total_sec);

        d = d + 366;

      }

      else

      {

        n = n - (p_year_total_sec);

        d = d + 365;

      }

      r+=1;

      y+=1;

   

    }

   

    y += 1970;



    Serial.print(y); // print the year (86400 equals secs per day)

    Serial.print('/');



    yd=0;

    yd = total_d - d;

   

    yf=1;

    while(yd>=28) 

    {

       

        if(yf==1 || yf==3 || yf==5 || yf==7 || yf==8 || yf==10 || yf==12)

        {

          yd -= 31;

          if(yd<0)break;

          rz += 31;

        }

   

        if (yf==2)

        {

          if (y%400==0 || (y%100!=0 && y%4==0)) 

          {

            yd -= 29;

            if(yd<0)break;

            rz += 29;

          }

          else 

          {

            yd -= 28;

            if(yd<0)break;

            rz += 28;

          }

        } 

        if(yf==4 || yf==6 || yf==9 || yf==11 )

        {

          yd -= 30;

          if(yd<0)break;

          rz += 30;

        }

        yf += 1;

       

    }

   

    Serial.print(yf);

    Serial.print('/');



    yr = total_d-d-rz;

   

    yr += 1;

   



    Serial.print(yr); // print the day (86400 equals secs per day)

    Serial.print(' ');



    Serial.print((epoch  % 86400L) / 3600+8); // print the hour (86400 equals secs per day)

    Serial.print(':');

    if (((epoch % 3600) / 60) < 10) {

      // In the first 10 minutes of each hour, we'll want a leading '0'

      Serial.print('0');

    }

    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)

    Serial.print(':');

    if ((epoch % 60) < 10) {

      // In the first 10 seconds of each minute, we'll want a leading '0'

      Serial.print('0');

    }

    Serial.println(epoch % 60); // print the second

  }

  // wait ten seconds before asking for the time again

  delay(1000);

  Ethernet.maintain();

}



// send an NTP request to the time server at the given address

void sendNTPpacket(const char * 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();

}

最常用的国内NTP服务器

ntp1.aliyun.com

 

ntp.tencent.com

 

edu.ntp.org.cn

 

不修改服务器也是可以的。

 

 

其可以直接获取到时间

https://www.beijing-time.org/shijianchuo/

可以通过上面的时间戳通过网站验证我们转换是否正确。

 

北京时间加8小时既可。

 

 

 

 

点赞 关注
 
 

回复
举报
您需要登录后才可以回帖 登录 | 注册

随便看看
查找数据手册?

EEWorld Datasheet 技术支持

相关文章 更多>>
关闭
站长推荐上一条 1/6 下一条

 
EEWorld订阅号

 
EEWorld服务号

 
汽车开发圈

About Us 关于我们 客户服务 联系方式 器件索引 网站地图 最新更新 手机版

站点相关: 国产芯 安防电子 汽车电子 手机便携 工业控制 家用电子 医疗电子 测试测量 网络通信 物联网

北京市海淀区中关村大街18号B座15层1530室 电话:(010)82350740 邮编:100190

电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号 Copyright © 2005-2025 EEWORLD.com.cn, Inc. All rights reserved
快速回复 返回顶部 返回列表