Skip to content

Instantly share code, notes, and snippets.

@unforgiven512
Created July 18, 2019 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unforgiven512/94be78fbbc4741dab90447959b4a3880 to your computer and use it in GitHub Desktop.
Save unforgiven512/94be78fbbc4741dab90447959b4a3880 to your computer and use it in GitHub Desktop.
import utime
#import machine
from machine import RTC
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
## DETERMINE THE NTP DELTA
## =======================
## (date(2000, 1, 1) - date(1900, 1, 1)).days * 24 * 60 * 60
NTP_DELTA = 3155673600
## SET THE NTP HOST
## ================
## Some reputable hosts:
## - pool.ntp.org
## - 0.us.pool.ntp.org
## - 1.us.pool.ntp.org
## - time.nist.gov
## - time1.google.com
## - time2.google.com
#host = "pool.ntp.org"
#def ntp_print_warning(has_been_warned=False):
# print("The default time server used with settime() is pool.ntp.org and has no provision for changing it, short of manually editing the text file.")
def print_timeset_msg(time_was_set=True):
print("--- The time was successfully set via NTP ---")
def getntptime(ntphost):
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1b
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
s.close()
val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_DELTA
## NOTE: There's currently no timezone support in MicroPython!
## As a workaround, utime.localtime() will return UTC time
## as if it was a call to .gmtime() instead.
# This call to settime() is hardcoded to use "pool.ntp.org"
def settime(ntpserver="pool.ntp.org"):
# ntp_print_warning(False)
t = getntptime(ntpserver)
# import machine
# import utime
tm = utime.localtime(t)
tm = tm[0:3] + (0,) + tm[3:6] + (0,)
# machine.RTC().datetime(tm)
RTC().datetime(tm)
print_timeset_msg(True)
# This call to settime2 allows specification of the desired NTP server
def settime_advanced(myntphost):
t = getntptime(myntphost)
# import machine
# import utime
tm = utime.localtime(t)
tm = tm[0:3] + (0,) + tm[3:6] + (0,)
# machine.RTC().datetime(tm)
RTC().datetime(tm)
print_timeset_msg(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment