happiness001 发表于 2024-6-6 09:28:14

单片机SNTP问题

void sendNTPpacket(IPAddress address) {
memset(packetBuffer, 0, ETHERNET_BUF_MAX_SIZE);
packetBuffer[0] = 0xE3;// LI, Version, Mode
packetBuffer[1] = 0;   // Stratum, or type of clock
packetBuffer[2] = 6;   // Polling Interval
packetBuffer[3] = 0xEC;// Peer Clock Precision
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
Udp.beginPacket(address, 123);//NTP requests are to port 123
Udp.write(packetBuffer, ETHERNET_BUF_MAX_SIZE);
Udp.endPacket();
}


void loop() {
delay(1000);
if (bStr)
{
    bStr = false;
    sendNTPpacket(IPAddress(198,120,0,100));//10秒执行一次
}
if (Udp.parsePacket()) {
    Udp.read(packetBuffer, ETHERNET_BUF_MAX_SIZE);
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);
    Serial.print("Unix time = ");
    const unsigned long seventyYears = 2208988800UL;
    unsigned long epoch = secsSince1900 - seventyYears;
    Serial.println(epoch);
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch % 86400L) / 3600);// print the hour (86400 equals secs per day)
    Serial.print(':');
    if (((epoch % 3600) / 60) < 10) {
      Serial.print('0');
    }
    Serial.print((epoch % 3600) / 60);// print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ((epoch % 60) < 10) {
      Serial.print('0');
    }
    Serial.println(epoch % 60);// print the second
    memset(packetBuffer, 0, ETHERNET_BUF_MAX_SIZE);
}
}
老是只能收到5 6个包,就不动了,怎么办?




页: [1]
查看完整版本: 单片机SNTP问题