【得捷电子Follow me第1期】 任务3:同步网络时间
[复制链接]
本帖最后由 dql2016 于 2023-4-12 11:47 编辑
学习network模块用法,掌握连接网络、查看网络参数等用法,实现通过网络同步系统时间。
官方文档里面介绍了网络模块的使用方法
https://datasheets.raspberrypi.com/picow/connecting-to-the-internet-with-pico-w.pdf
连接网络
简单方法
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('dql', 'dql123456')
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
效果
查看参数
import network
import time
import ubinascii
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('dql', 'dql123456')
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting to connect:")
time.sleep(1)
print(wlan.ifconfig())
mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode()
print(mac)
print(wlan.config('channel'))
print(wlan.config('essid'))
print(wlan.config('txpower'))
效果
连接网络判断
import time
import network
ssid = 'dql'
password = '123456dql'
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] )
# Connect to another network
wlan.disconnect();
wlan.connect('Other Network', 'The Other Password')
效果
ntp获取时间
import time
import utime
import machine
import ntptime
ntptime.NTP_DELTA = 3155644800 # 可选 UTC+8偏移时间(秒),不设置就是UTC0
ntptime.host = 'ntp1.aliyun.com' # 可选,ntp服务器,默认是"pool.ntp.org" 这里使用阿里服务器
ntptime.settime() # 修改设备时间
print( time.localtime(time.time()))
rtc = machine.RTC()
while True:
t = rtc.datetime()
print(t[0])
print(t[1])
print(t[2])
time.sleep(1)
效果
|