Wireless Network Example Tutorial#
Overview#
This tutorial will guide you on how to use MicroPython’s network module in CanMV for basic wireless network (WiFi) operations, including connecting to a wireless access point (AP) as a station (STA) and creating your own access point (AP).
sta_test(): Demonstrates how to connect to a wireless network as a station (STA), including checking the current connection status, scanning available networks, connecting to a specific AP, viewing IP configuration, and disconnecting.
ap_test(): Shows how to configure and start a wireless access point (AP), including setting the SSID, channel, and password, and checking the AP’s configuration and status.
Interface Invocation and Function Description#
sta_test#
network.WLAN(id): Initializes a WLAN object, whereidbeing 0 represents STA mode.sta.active(bool): Activates or deactivates STA mode. PassTrueto activate, passFalseto deactivate. If called without parameters, it returns the current activation status.sta.status(): Returns the current status of the STA, such as whether it is connected to an AP.sta.connect(ssid, password): Attempts to connect to an AP with the specified SSID and password. This method does not return a direct result of whether the connection is successful, but you can obtain the connection status by checkingsta.status()orsta.isconnected().sta.ifconfig(): Returns the IP configuration information of the STA, such as IP address, subnet mask, gateway, and DNS server.sta.isconnected(): ReturnsTrueif the STA is connected to an AP, otherwise returnsFalse.sta.disconnect(): Disconnects the STA from the current AP.
Complete Example#
import network
import time
SSID = "TEST"
PASSWORD = "12345678"
sta = network.WLAN(network.STA_IF)
sta.connect(SSID, PASSWORD)
timeout = 10 # 单位:秒
start_time = time.time()
while not sta.isconnected():
if time.time() - start_time > timeout:
print("连接超时")
break
time.sleep(1) # 请稍等片刻再连接
print(sta.ifconfig())
print(sta.status())
# 这里的断开网络,只是一个测试。实际应用可不断开
sta.disconnect()
print("断开连接")
print(sta.status())
ap_test#
network.WLAN(network.AP_IF): Initialize a WLAN object and set it to AP mode.ap.active(bool): Activate or deactivate AP mode. PassTrueto activate andFalseto deactivate. When called without parameters, it returns the current activation status.ap.config(ssid=None, password=None, channel=None, ...): Configure AP parameters such as SSID, password, channel, etc. When called without any parameters, it returns the current configuration.ap.config(key): Ifkeyis the string representation of a configuration item such as'ssid'or'channel', it returns the value of that configuration item.ap.status(): Returns the current status of the AP.
Complete Example#
import network
def ap_test():
ap=network.WLAN(network.AP_IF)
#Configure and create ap
ap.config(ssid='k230_ap_wjx', key='12345678')
#View ap information
print(ap.info())
#View ap status
print(ap.status())
ap_test()
For specific interface definitions, please refer to network
