micropython之NTP授时
闲着有空研究了一下micropython的NTP授时,结果发现比起arduino什么的很简单,发个帖子简单分享一下!首先要你要知道什么是NTP,不懂得可以去百度一下,毕竟度娘讲的比咱专业。:lol
准备:
硬件
我用的是openioe esp8266,这个不重要,能跑micropython即可,比如DF家的firebeetle也很好~
软件
uPyCraft V0.22
不得不说这款IDE跟micropython搭配起来就是好用!:lol
代码:
import usocket as socket
import ustruct as struct
import time
import network
from machine import Pin,I2C
import ssd1306
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
lcd=ssd1306.SSD1306_I2C(128,64,i2c)
NTP_DELTA = 3155673600
host = "cn.pool.ntp.org"#国内的NTP时间服务器
SSID="yourssid"
PASSWORD="yourpassword"
wlan=None
s=None
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
wlan.disconnect()
wlan.connect(ssid,passwd)
while(wlan.ifconfig()=='0.0.0.0'):
time.sleep(1)
return True
connectWifi(SSID,PASSWORD)
def time():
NTP_QUERY = bytearray(48)
NTP_QUERY = 0x1b
addr = socket.getaddrinfo(host, 123)[-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)
return val - NTP_DELTA
if __name__=='__main__':
t = time()
import utime
tm = utime.localtime(t)
tm = tm + (0,) + tm + (0,)
print(tm)
year=tm
print(year)
mouth=tm
day=tm
hour=tm
sencod=tm
if 16<=hour<24:#ntp授时获取的是格林尼治时间 这里我们转换为我们东8区的时间
day=day+1
hour=hour+8
min=tm
if hour>24:
hour=hour-24
print(mouth)
print(day)
print(hour)
print(min)
print(sencod)
运行演示:
上传代码
运行结果:
小结:
NTP授时在计算机等科学领域十分重要,尤其对时间精度要求比较高的场所,用micropython来获取网络时间很简单,还可以在此基础上扩展一下,比如做个NTP小时钟什么的,可以自动更新时间,岂不是省去了很多麻烦?写到这,很简单的一个应用,有兴趣的可以尝试一下!
示例地址:https://github.com/micropython/micropython/blob/ddf0b7dbc3843f2025da5a4cc1b588340c4aad13/esp8266/modules/ntptime.py
一楼给自己:lol 好专业的帖子 帮顶
页:
[1]