ESP8266 SHT21 sensor
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ntp.cpp 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <WiFiUdp.h>
  4. #include "config.h"
  5. #include "ntp.h"
  6. //#define DEBUG
  7. IPAddress timeServerIP;
  8. byte ntpPacketBuffer[NTP_PACKET_SIZE];
  9. WiFiUDP ntp;
  10. unsigned long lastNTP = 0; // timer for retries
  11. unsigned long timestamp = 0; // received epoch time
  12. unsigned long timeReceived = 0; // systick matching received epoch
  13. static void sendNTPpacket(IPAddress& address) {
  14. #ifdef DEBUG
  15. Serial.println("Sending NTP packet...");
  16. #endif
  17. memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
  18. ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
  19. ntpPacketBuffer[1] = 0;
  20. ntpPacketBuffer[2] = 6;
  21. ntpPacketBuffer[3] = 0xEC;
  22. ntpPacketBuffer[12] = 49;
  23. ntpPacketBuffer[13] = 0x4E;
  24. ntpPacketBuffer[14] = 49;
  25. ntpPacketBuffer[15] = 52;
  26. ntp.beginPacket(address, NTP_PORT_TO);
  27. ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
  28. ntp.endPacket();
  29. }
  30. void ntpInit(void) {
  31. ntp.begin(NTP_PORT_FROM);
  32. WiFi.hostByName(NTP_SERVER_NAME, timeServerIP);
  33. lastNTP = millis();
  34. sendNTPpacket(timeServerIP);
  35. }
  36. void ntpRun(void) {
  37. // Retry if we haven't received an answer soon enough
  38. if ((timestamp == 0) && ((millis() - lastNTP) > NTP_RETRY_TIMEOUT)) {
  39. #ifdef DEBUG
  40. Serial.println("NTP packet retry...");
  41. #endif // DEBUG
  42. WiFi.hostByName(NTP_SERVER_NAME, timeServerIP);
  43. lastNTP = millis();
  44. sendNTPpacket(timeServerIP);
  45. }
  46. // Process received response
  47. if (ntp.parsePacket() >= NTP_PACKET_SIZE) {
  48. ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);
  49. unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
  50. unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
  51. unsigned long secsSince1900 = highWord << 16 | lowWord;
  52. const unsigned long seventyYears = 2208988800UL;
  53. unsigned long epoch = secsSince1900 - seventyYears;
  54. timestamp = epoch;
  55. timeReceived = millis();
  56. #ifdef DEBUG
  57. Serial.print("Got NTP time: ");
  58. Serial.println(epoch);
  59. #endif // DEBUG
  60. }
  61. }