2. 设置 WiFi 连接
首先,需要连接到 WiFi 网络。可以使用 network 模块进行 WiFi 连接,并捕获可能发生的异常。
import network
import time
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(ssid, password)
start_time = time.time()
while not wlan.isconnected():
if time.time() - start_time > 10:
print("Failed to connect to WiFi")
return False
time.sleep(1)
print("WiFi connected:", wlan.ifconfig())
return True
# 示例调用
ssid = "your_SSID"
password = "your_password"
connect_to_wifi(ssid, password)
3. 使用 HTTP 请求进行通信
使用 urequests 模块进行 HTTP 请求,同时捕获可能的异常,例如网络连接错误、超时等。
import urequests
def get_data_from_server(url):
try: