|from machine import Pin|
|NTP_DELTA = 2208988800|
|host = "pool.ntp.org"|
|led = Pin("LED", Pin.OUT)|
|ssid = 'A NETWORK'|
|password = 'A PASSWORD'|
|NTP_QUERY = bytearray(48)|
|NTP_QUERY = 0x1B|
|addr = socket.getaddrinfo(host, 123)[-1]|
|s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)|
|res = s.sendto(NTP_QUERY, addr)|
|msg = s.recv(48)|
|val = struct.unpack("!I", msg[40:44])|
|t = val - NTP_DELTA|
|tm = time.gmtime(t)|
|machine.RTC().datetime((tm, tm, tm, tm + 1, tm, tm, tm, 0))|
|wlan = network.WLAN(network.STA_IF)|
|max_wait = 10|
|while max_wait > 0:|
|if wlan.status() < 0 or wlan.status() >= 3:|
|max_wait -= 1|
|print('waiting for connection...')|
|if wlan.status() != 3:|
|raise RuntimeError('network connection failed')|
|status = wlan.ifconfig()|
|print( 'ip = ' + status )|
Modified defines for local time and local NTP host
NTP_DELTA = 2208988800 - 3600 # subtract 1 hour = 3600 seconds to get GMT + 1 for Portugal
host = "pt.pool.ntp.org" # using host from Portugal
Jul 18, 2022
I'm getting an intermittent failure running the code :
ip = 192.168.3.58
Traceback (most recent call last):
File "", line 52, in
File "", line 24, in set_time
OSError: [Errno 110] ETIMEDOUT
Error message indicates its a time out but not sure what's causing the problem.
Jul 18, 2022
I had that error also. That is why I created a try..except block. See the OSError part of it.
I also created extra logic to call set_time() only at: a) start; b) once in an hour. For the rest every second a REPL print of some time.localtime() data. See the next screenshot at the change of an hour:
Added variable tm_gmtoff, offset of GMT for Portugal:
The original script does call set_time() just once. That is OK for an example as this is.
I have the experience that the RTC's of various microcontollers in time deviate from NTP time.
That is why I decided to call set_time() at intervals to synchronize the built-in RTC.
I am still working on the script to have it fit better to my ideas.
I have published my project on the micropython forum:
Dec 27, 2022
Modified defines for local time and local NTP host NTP_DELTA = 2208988800 - 3600 # subtract 1 hour = 3600 seconds to get GMT + 1 for Portugal host = "pt.pool.ntp.org" # using host from Portugal
This fixed it for me. Thank you! I had to do "+ 21_600" to get to North America Central Time. Thank you again!
Dec 30, 2022
Hi, using this script provoked the error "machine" is not defined (line 30)
I changed line 6 into: "import machine".
line 11 into led = machine.Pin("LED", machine.Pin.OUT).
Then the script ran OK.