【得捷电子Follow me第1期】任务3:Mu editor环境下联网及同步网络时间
[复制链接]
Pico W相比较标准Pico板子最大变化了是搭载了英飞凌(Infineon)CYW43439模块,使其具有了链接2.4G wifi的能力,并且未来有可能会支持蓝牙(期待)
因为树莓派底层micropython固件做了大量联网方面工作,将很多协议栈和函数都封装到了一起,所以我们用起来就简化成了很简单的几个函数,具体联网我不再赘述,直接上代码。
第一部分,联网测试代码:
import time
import network
import urequests
from machine import RTC
import ntptime
ssid = 'xxx'#wifi name
passwd = 'xxx'#wifi password
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid,passwd)
#try to connect wifi
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('wait for WiFi connection')
#oled.fill(0)
#oled.text('Wait WiFi',1,12,1)
#oled.show()
time.sleep(1)
#判定网络状态
if wlan.status() != 3:
raise RuntimeError('Connection faild')
else:
print('wifi connected')
status = wlan.ifconfig()
print('ip = '+status[0])
运行截图如下所示:
第二部分,WIFI联网,并且从NTP获取实时时间
import time
import network
import ntptime
import utime
ssid = 'xxx' # wifi name
passwd = 'xx' # wifi password
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, passwd)
# try to connect wifi
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('wait for WiFi connection')
time.sleep(1)
# 判定网络状态
if wlan.status() != 3:
raise RuntimeError('Connection faild')
else:
print('wifi connected')
status = wlan.ifconfig()
print('ip = '+status[0])
ntptime.host = "ntp.aliyun.com" # 使用阿里云NTP服务器
ntptime.timeout = 5 # 设置超时时间
sec = ntptime.time() # 获取实时时间
print(sec)
print(utime.localtime(sec+8*3600)) # 转换为北京时间,东八区
运行截图:
|