Last active
November 28, 2018 12:43
-
-
Save tranch/9278259fdef3a91952b9b1d9cc270b58 to your computer and use it in GitHub Desktop.
NTP time update for micropython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import ustruct | |
import time | |
from machine import RTC | |
# datetime.date(2000, 1, 1) - datetime.date(1900, 1, 1) | |
NTP_DELTA = 3155673600 | |
NTP_SERVER = '0.cn.pool.ntp.org' | |
def get_ntp_time(): | |
data = bytearray(48) | |
data[0] = 0x1B | |
val = 0 | |
addr = socket.getaddrinfo(NTP_SERVER, 123)[0][-1] | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
sock.sendto(data, addr) | |
data, addr = sock.recvfrom(2048) | |
val = ustruct.unpack("!12I", data)[10] | |
return val - NTP_DELTA | |
def sync(): | |
ts = get_ntp_time() | |
tm = time.localtime(ts) | |
rtc = RTC() | |
rtc.datetime(tm[0:3] + (0,) + tm[3:6] + (0,)) | |
if __name__ == '__main__': | |
sync() | |
print("Current time:", time.localtime()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment