Skip to content

Instantly share code, notes, and snippets.

@anecdata
Last active March 20, 2021 21:48
Show Gist options
  • Save anecdata/a7e1d3884a2373b5c6528b0136ead2f9 to your computer and use it in GitHub Desktop.
Save anecdata/a7e1d3884a2373b5c6528b0136ead2f9 to your computer and use it in GitHub Desktop.
NTP ESP32-S2
import wifi
import socketpool
import struct
import time
import sys
from secrets import secrets
NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00
packet = bytearray(48)
# connect to wifi
print("Connecting to Wifi")
wifi.radio.connect(secrets["ssid"], secrets["password"])
pool = socketpool.SocketPool(wifi.radio)
loop = 0
while True:
loop += 1
print(loop, end=" ")
# make socket
print("Creating socket")
with pool.socket(pool.AF_INET,pool.SOCK_DGRAM) as sock:
start = time.monotonic()
sock.settimeout(5)
# Fill packet
packet[0] = 0b00100011 # Not leap second, NTP version 4, Client mode
try:
print("Sending packet")
sock.sendto(packet, ("pool.ntp.org", 123))
size, address = sock.recvfrom_into(packet)
print("Received packet")
seconds = struct.unpack_from("!I", packet, offset=len(packet) - 8)[0]
print("Address:", address)
print("Time:", time.localtime(seconds - NTP_TO_UNIX_EPOCH))
print("Duration", time.monotonic() - start)
except OSError as e:
sys.print_exception(e)
print()
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment