【得捷电子Follow me第1期】第七贴:曲折的同步网络时间
[复制链接]
这个贴早就应该发了,只不过经过了一段不平常的弯路终于搞定了。
首先,同步网络时间必须得连上网:
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('TPLINK555', '12345678')
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
再联上WIFI的前提下可以手动同步了,也就是把程序上载到板子,然后用SHELL来运行程序。
import time
import utime
import machine
import ntptime
ntptime.NTP_DELTA = 3155644800
ntptime.host = 'ntp1.aliyun.com'
ntptime.settime()
print( time.localtime(time.time()))
rtc = machine.RTC()
while True:
t = rtc.datetime()
print(t)
time.sleep(5)
但到了这里,我的TONNY确提示找不到ntptime.py我又是在模块管理搜又是安装可是没有,于是我就用老办法直接找。也从网上找到了两个。但是上载到板子之后确时间总是不对。
我又把程序整合了一下:
import time
import network
ssid = 'TPLINK555'
password = '12345678'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print( 'ip = ' + status[0] )
import ntptime
def sync_ntp():
ntptime.NTP_DELTA = 3155644800#3155673600#3155644800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"
ntptime.settime() # 修改设备时间,到这就已经设置好了
sync_ntp()
# 已经设置好了,随便用
from machine import RTC
rtc = RTC()
print(rtc.datetime())
显示的时间还是不对。
。。。。。。。。。。。。。。。。。。。。。。。。。。
。。。。。。。。。。。。。。。。。。。。。。。。。。。。
愁死我了。。。。。。正当我想就这样在贴子说明一下得了。这时我看到了一个贴子:
micropython实现ntp获取网络时间(UTC+8)
https://blog.csdn.net/zld_555/article/details/106238482
上面有ntptime的原码。
我下来之后直接用它的ntptime.py,正常了,以下是结果:
得感谢发表那篇文章的网友。否则糊弄过去十年八年的都是它。
|