【得捷电子Follow me第1期】三:联网和时间同步 + ntp DELTA更新
[复制链接]
本帖最后由 sss421 于 2023-6-3 23:52 编辑
联网和时间同步内容在第一次公开课有比较 详细的介绍
wifi模块为板载模块,不需要硬件连接部分
wifi模块 连网部分实现如下:
import network
import time
ssid = 'XXX'
password = 'XXXXX'
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])
联网成功后会打印当前获得的IP
raw REPL; CTRL-B to exit
>OK
waiting for connection...
waiting for connection...
waiting for connection...
waiting for connection...
waiting for connection...
waiting for connection...
connected
ip = 192.168.2.115
下面是加上OLED的显示 代码
import network
import time
ssid = 'xxx'
password = 'xxx'
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 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"
ntptime.settime() # 修改设备时间,到这就已经设置好了
sync_ntp()
from machine import RTC
from time import sleep
i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000) # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0) # clear
oled.text("NTP Time!", 0, 0)
oled.show()
while True:
rtc = RTC()
print(rtc.datetime())
oled.fill(0) # clear
oled.text("NTP Time!", 0, 0)
s = ','.join(str(i) for i in rtc.datetime())
oled.text(s, 0, 16)
oled.show()
sleep(1)
最终效果:
waiting for connection...
waiting for connection...
connected
ip = 192.168.2.115
(2023, 6, 1, 3, 14, 55, 21, 0)
(2023, 6, 1, 3, 14, 55, 22, 0)
(2023, 6, 1, 3, 14, 55, 23, 0)
(2023, 6, 1, 3, 14, 55, 24, 0)
(2023, 6, 1, 3, 14, 55, 25, 0)
(2023, 6, 1, 3, 14, 55, 26, 0)
(2023, 6, 1, 3, 14, 55, 27, 0)
(2023, 6, 1, 3, 14, 55, 28, 0)
(2023, 6, 1, 3, 14, 55, 29, 0)
(2023, 6, 1, 3, 14, 55, 30, 0)
更新,发现UTC修改不生效了,在大佬协助下,发现是utptime库更新导致的
EPOCH_YEAR = utime.gmtime(0)[0]
if EPOCH_YEAR == 2000:
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 3155673600
elif EPOCH_YEAR == 1970:
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 2208988800
else:
raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
增加了对不同EPOCH_YEAR的支持,这就导致取巧的NTP_DELTA设置无效了
个性了ntptime库,增加了一个UTC_DELTA的变量,最终代码如下:
from ssd1306 import SSD1306_I2C
import network
import time
ssid = 'xxx'
password = 'xxxx'
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.UTC_DELTA = 28800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org"
ntptime.settime() # 修改设备时间,到这就已经设置好了
sync_ntp()
from machine import RTC,I2C,Pin
from time import sleep
i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000) # Grove - OLED Display 0.96" (SSD1315)
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0) # clear
oled.text("NTP Time!", 0, 0)
oled.show()
while True:
rtc = RTC()
print(rtc.datetime())
oled.fill(0) # clear
oled.text("NTP Time!", 0, 0)
s = ','.join(str(i) for i in rtc.datetime())
oled.text(s, 0, 16)
oled.show()
sleep(1)
修改后的ntptime.py
import utime
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"
# The NTP socket timeout can be configured at runtime by doing: ntptime.timeout = 2
timeout = 1
def time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(timeout)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
EPOCH_YEAR = utime.gmtime(0)[0]
if EPOCH_YEAR == 2000:
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 3155673600
elif EPOCH_YEAR == 1970:
# (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 2208988800
else:
raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
try:
UTC_DELTA
except NameError:
pass
else:
NTP_DELTA = NTP_DELTA - UTC_DELTA
return val - NTP_DELTA
# There's currently no timezone support in MicroPython, and the RTC is set in UTC time.
def settime():
t = time()
import machine
tm = utime.gmtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
|