Wi-Fi Connection ================ This example demonstrates how to connect mPython IoT to a Wi-Fi network using the MicroPython ``network`` module. This is the first step for all IoT applications. .. Attention:: mPython IoT only supports 2.4 GHz Wi-Fi (IEEE 802.11b/g/n) and does not support the 5 GHz band. Basic Principle --------------- mPython IoT connects to a wireless router as a client in STA (Station) mode. Use ``network.WLAN(network.STA_IF)`` to create a wireless network interface object, activate it, and then call ``connect()`` to join the specified hotspot. Connection Example ------------------ The following code connects to Wi-Fi and prints the obtained IP address:: import network import time sta = network.WLAN(network.STA_IF) # Create STA interface object sta.active(True) # Activate Wi-Fi interface if not sta.isconnected(): # If not yet connected sta.connect('your_ssid', 'your_password') # Connect to the specified hotspot print('Connecting to Wi-Fi ...') while not sta.isconnected(): # Wait for connection time.sleep(0.5) print('Wi-Fi connected!') print('IP address: ', sta.ifconfig()[0]) print('Subnet mask: ', sta.ifconfig()[1]) print('Gateway: ', sta.ifconfig()[2]) print('DNS: ', sta.ifconfig()[3]) Replace ``your_ssid`` and ``your_password`` with your actual Wi-Fi network name and password. Example with Timeout and Reconnection ------------------------------------- In real projects, the network may be unstable. The following example adds a connection timeout check to prevent the program from waiting indefinitely:: import network import time def connect_wifi(ssid, password, timeout=10): sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect(ssid, password) start = time.time() while not sta.isconnected(): if time.time() - start > timeout: print('Connection timed out, please check Wi-Fi name and password') return False time.sleep(0.5) print('Wi-Fi connected, IP: ', sta.ifconfig()[0]) return True connect_wifi('your_ssid', 'your_password') .. Hint:: After a successful connection, the Wi-Fi status LED changes from blinking to solid on. Use this to visually determine the device network status. Related Documentation --------------------- - :doc:`../2_software/2_3_wifi_config` - :doc:`3_2_mqtt`