任务4:连接WiFi网络
这个任务利用了ESP32的强大网络功能了,为了测试WiFi就需要请上跟信号有关的天线,将其接到模块上的IPEX座了。
以目前ESP32的强大生态来讲,真的很轻而易举。包括官方也提供了连接指定AP的参考,如下:
import network
import urequests
import utime as time
# Network settings
wifi_ssid = "Your Own SSID"
wifi_password = "Your Own Password"
def scan_and_connect():
station = network.WLAN(network.STA_IF)
station.active(True)
print("Scanning for WiFi networks, please wait...")
for ssid, bssid, channel, RSSI, authmode, hidden in station.scan():
print("* {:s}".format(ssid))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
print()
while not station.isconnected():
print("Connecting...")
station.connect(wifi_ssid, wifi_password)
time.sleep(10)
print("Connected!")
print("My IP Address:", station.ifconfig()[0])
# Execute the functions
scan_and_connect()
其中的wifi_ssid和wifi_password需要改成对应的WiFi名称和密码,运行之后就会开始扫描WiFi网络
扫描结束之后则开始连接到前面定义的wifi_ssid所在的网络,并输出如下提示。
在路由器也可看到对应的设备
接下来我们使用NTP服务更新本地时间来测试网络联通
代码中使用 ntptime.settime() 从服务器同步本地时间,然后每一秒获取本地时间戳,再将其转换,并在打印串口以及OLED上面时间当前日期和时间。
由此也增加了前面任务中的OLED功能,在开始阶段显示任务内容,并在时间戳更新中显示当前日期和时间
执行后在打印串口可以卡到时间的更新
而在OLED上,可以看到启动任务内容提示
以及时间同步成功之后,本地时间的更新
功能完整代码如下,其中的wifi_ssid和wifi_password需要替换成自己的对应值
import network
import urequests
#import utime as time
import ntptime
from machine import Pin, SoftI2C
import ssd1306
import utime
i2c = SoftI2C(scl=Pin(7), sda=Pin(6))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 清空屏幕,并显示任务要求
oled.fill(0)
oled.text("Task 4:", 10, 25)
oled.text("WiFi Network", 10, 40)
oled.show()
# Network settings
wifi_ssid = "your ssid"
wifi_password = "your password"
def scan_and_connect():
station = network.WLAN(network.STA_IF)
station.active(True)
print("Scanning for WiFi networks, please wait...")
for ssid, bssid, channel, RSSI, authmode, hidden in station.scan():
print("* {:s}".format(ssid))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
print()
while not station.isconnected():
print("Connecting...")
station.connect(wifi_ssid, wifi_password)
time.sleep(10)
print("Connected!")
print("My IP Address:", station.ifconfig()[0])
# Execute the functions
scan_and_connect()
# 从时间服务器获取时间
ntptime.settime()
while True:
# 获取当前时间戳,此处加了8小时的时区差
current_time = utime.time() + 8 * 60 * 60
print("Current Time:", current_time)
# 将时间戳转换为本地时间
local_time_value = utime.localtime(current_time)
print("Local Time:", local_time_value)
# 根据日期时间转换,便于打印和显示
local_data = "{:02d}-{:02d}-{:02d}".format(local_time_value[0], local_time_value[1], local_time_value[2])
local_time = "{:02d}:{:02d}:{:02d}".format(local_time_value[3], local_time_value[4], local_time_value[5])
print(local_data)
print(local_time)
# 更新显示内容
oled.fill(0)
oled.text(local_data, 10, 25)
oled.text(local_time, 10, 40)
oled.show()
# 延时1秒
utime.sleep(1)