ESP8266 and ESP32 are popular WiFi development boards. These single-board microcontrollers are supported by the MicroPython framework and are often used for the internet of things (IoT). Using MicroPython, ESP8266 and ESP32 can connect to the internet via WiFi and Ethernet. The MicroPython ports use Ethernet or the wireless local area network (WLAN).
In this article, we’ll discuss MicroPython’s network, which is useful for managing internet connections through MicroPython-supported ports. We’ll also discuss how MicroPython’s network module can be used to set up an internet connection on ESP8266 and ESP32 via WiFi.
Network module
MicroPython’s network module is written to configure WiFi connections. The module provides two WiFi interfaces: station and access point. The access-point interface is active by default.
- In the access-point interface, the ESP8266/ESP32 or any other MicroPython port acts as a WiFi access point for other devices to connect with an internet connection.
- In the station interface, the ESP8266/ESP32 or any other MicroPython port connects to the router for internet access.
The network module can be imported into a MicroPython script with this statement:
import network, time
The network module only provides network drivers and router configurations and is used to configure hardware network interfaces. A socket module is required to attain network services from the respective network interfaces. This means we can only use the network module to connect to the internet, manage the internet connection by configuring the router settings, and create an access point.
The network module provides no abstract Network Interface Card (NIC) class. Instead, it offers different network-interface classes implemented via the MicroPython ports for different hardware.
These network-interface classes include:
- The WLAN – for WiFi interfaces
- WLANWiPy – for WiPy-specific WiFi controls
- LAN – for Ethernet
- CC3K – for CC3000 WiFi modules
- WIZNET5K – for WIZnet5x00 WiFi mdules.
The network-interface classes are all designed for specific network hardware. A particular network-interface class has this constructor method: class network.AbstractNIC(id=None, …)
The constructor represents a network-interface object. The parameters passed depend on the specific network-interface class. If more than one interface of the same class is instantiated, the first parameter must be an “id.”
For example, the following constructor creates an object for the WiFi network interface:
nic = network.WLAN(network.STA_IF)
Regardless of the network-interface class, the network module provides the following methods…
AbstractNIC.active(): used to activate or deactivate a network interface. It takes a boolean argument. If passed as True as an argument, the respective network interface is activated. If passed as False as an argument, the respective network interface is deactivated. If the method is called without arguments, it returns to the current state of the given network interface.
Note: All of the other methods only work on the network interface only if this method is activated.
AbstractNIC.connect(): connects the interface to a network. This method must only be called for interfaces that are not always connected. The parameters passed depend on the network-interface class and/or the specific MicroPython port.
For example, the WiFi interface object requires that the SSID is passed as a parameter to connect to a network. If a single parameter is passed to this method, it’s always the identifier of the network services. Other parameters are keyword specific. They’re passed to specify alternative service identifier types or to provide additional connection parameters. For instance, the WiFi interface object might require a network password as an additional parameter.
AbstractNIC.disconnect(): disconnects the interface with the network.
AbstractNIC.isconnected(): verifies if the interface is connected to a network. If it returns as True, the interface is connected to the network. Otherwise, it returns False.
AbstractNIC.scan(): scans for available network services or connections. It returns a list of tuples that match any of the service parameters that are found. The format of the tuple depends on the specific network interface class. A tuple for a WiFi network object is as follows: (ssid, bssid, channel, RSSI, security, hidden). This method allows a filter to scan the results. It can be called to scan for a particular service, channel, or services of a particular set. The parameters set for the scan duration and other network parameters can also be passed as arguments.
AbstractNIC.status(): used to query the dynamic status information of a network. If the method is called without arguments, it returns the network link status. Otherwise, the parameter-specific network-interface class can be passed to retrieve specific information. For instance, passing “stations” as an argument to a WiFi access-point interface object returns a list of all the stations connected to that access point. Similarly, passing “RSSI” as an argument to a WiFi station interface returns RSSI (which is the received signal strength indicator) of the connected access point or router.
AbstractNIC.ifconfig(): used to set or get the IP-level network-interface parameters. These parameters include the IP address, subnet mask, gateway, and DNS server. If called without arguments, it returns the above parameters as a 4-tuple. To set the IP-level network-interface parameters, a 4-tuple with the above-mentioned parameters must be passed.
AbstractNIC.config(): used to set or query network or hardware-specific parameters. When called to set parameters, the parameters must be specified with keyword arguments. It’s possible to set multiple network or hardware-specific parameters in a single method call, where all parameters are passed as keyword-specific arguments. Only a single parameter can be queried in one method call.
A few valid examples of this method are:
ap_if.config(ssid=’My AP’)
ap_if.config(ssid=’My AP’, channel=11)
print(ap_if.config(‘channel’))
print(ap_if.config(‘ssid’))
These methods are available for all network-interface classes that include WLAN, WLANWiPy, LAN, CC3K, and WIZNET5K.
The network module also provides a method to set or get the WiFi mode. This method is network.phy_mode(). However, it’s only available for ESP8266. It can be passed as the arguments MODE_11B, MODE_11G, or MODE_11N to set the WiFi mode to IEEE 802.11b, IEEE 802.11g, or IEEE 802.11n, respectively. If called without arguments, it returns the current WiFi mode.
WLAN class
The WLAN class network module provides a driver for the WiFi network processors. The class is part of the network module. The constructor method is as follows:
class network.WLAN(interface_id)
The method creates a WiFi network-interface object. As mentioned, there are two types of WiFi interfaces supported in MicroPython: station and access point. This is a valid example for creating a WiFi station object:
import network
sta_if = network.WLAN(network.STA_IF)
Here’s a valid example for creating a WiFi access-point object:
import network
ap_if = network.WLAN(network.AP_IF)
The WiFi class of the network module provides these methods…
WLAN.active():used to activate or deactivate the WiFi network-interface object. If passed as True as an argument, the WiFi interface identified by the WLAN object is activated. If passed as False as an argument, the WiFi interface is deactivated. If called without arguments, the method returns to the current status of the WiFi network object.
WLAN.connect(ssid=None, key=None, *, bssid=None): used to connect with a WiFi router or access point. It takes SSID or BSSID from the available network service as an argument. The network key may be required to pass as an additional argument. If BSSID is passed, the network connection is restricted to the access point with the given MAC address. In this case, SSID must also be passed.
WLAN.disconnect(): disconnects the interface with the currently WIFI connection.
WLAN.scan(): available only for WiFi station objects. The method scans for the available WiFi and hidden networks provided the WLAN interface allows for it. It returns a list of tuples with information about the available WiFi access points. The values used for security are “0” for open WiFi network, “1” for WEP, “2” for WPA=PSK, “3” for WPA2-PSK, and “4” for WPA/WPA2-PSK. The values “0” and “1” indicate the visible and hidden WiFi access points, respectively.
WLAN.status(): returns the network link status.
The status can be:
- STAT_IDLE – there is no connection or activity.
- STAT_CONNECTING – the connection is in progress.
- STAT_WRONG_PASSWORD – the network connection failed due to an incorrect network key.
- STAT_NO_AP_FOUND – the network connection failed because no access point replied to the connection request.
- STAT_CONNECT_FAIL – the network connection failed due to another reason.
- STAT_GOT_IP – the network is successfully connected and the IP is obtained.
For the station object, the method can be called with the “RSSI” argument, which returns the received signal strength indicator for the given access point.
WLAN.isconnected(): for a WiFi station object, this method returns True if the port is connected to a WiFi access point, indicating that a valid IP address has been obtained. For the access-point WiFi object, the method returns True if at least one station is connected to the port that’s working as a WiFi access point.
WLAN.ifconfig():used to set or get the IP-level network-interface parameters. These parameters include IP address, subnet mask, gateway, and DNS server. If called without arguments, it returns the above parameters as a 4-tuple. To set the IP-level network-interface parameters, a 4-tuple with the above-mentioned parameters must be passed.
WLAN.config():used to set or get WiFi network-specific parameters. This is done by passing keyword arguments. These parameters are listed below…
Manually connecting to a WiFi network
It’s possible to manually connect ESP8266/ESP32 with a WiFi network using the Python command prompt. A manual connection can be made using the Python prompt of uPyCraft IDE or Thonny IDE. It can also work with a serial connection to a Python command prompt via a terminal program (like Putty).
We’ve configured a manual connection to a WiFi network for this project using uPyCraft IDE’s command console. To import the network module, use this command:
import network
Next, create a station WiFi object to connect the ESP8266/ESP32 board with a WiFi connection. Execute the following command in the uPyCraft console to create a station WiFi interface:
station = network.WLAN(network.STA_IF)
Activate the station WiFi interface by calling the WLAN.active() method. Execute the following command in UPyCraft’s console to activate the station WiFi interface:
station.active(True)
Once the WiFi interface is active, it can be connected to WiFi with the known SSID and network key. The network key will not be required if the WiFi connection is open. Execute this command in the UPyCraft console to connect with the available WiFi:
station.connect(<ssid>, <network_key>)
To verify if the network interface is successfully connected to a WiFi network, call the isconnected() method. Use this command in the UPyCraft console to verify the connection:
station.isconnected()
If the method returns True, the network interface is successfully connected to WiFi. Verify the IP-level parameters by calling the ifconfig() method. Execute the following command in UPyCraft’s console to view the IP-level network parameters, which include the IP address, subnet mask, gateway, and DNS server:
station.ifconfig()
The network interface can be disabled if required by calling the active() method. Use this command in the UPyCraft console to deactivate the WiFi network interface:
station.active(False)

Screenshot of a manual connection to a WiFi network using ESP8266.
Connecting with a function call
A WiFi connection can be configured by a function call using a MicroPython script. The same commands used for the manual WiFi connection are also used for a function call — except that the commands are encapsulated in a function body with validation at different points.
Below is a typical example of a function for setting up a WiFi connection using MicroPython’s supported ports, including ESP8266 and ESP32.
import network
station = network.WLAN(network.STA_IF)
def connect(id, pswd):
ssid = id
password = pswd
if station.isconnected() == True:
print(“Already connected”)
return
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print(“Connection successful”)
print(station.ifconfig())
You’ll note that we have declared the station object as a global variable. This will help us to create a function to disconnect the WiFi network whenever required.
Here’s an example of a function for deactivating a WiFi connection:
def disconnect():
if station.active() == True:
station.active(False)
if station.isconnected() == False:
print(“Disconnected”)
This MicroPython script is a valid example for connecting and disconnecting ESP8266/ESP32 to a WiFi connection:
import network
station = network.WLAN(network.STA_IF)
def connect(id, pswd):
ssid = id
password = pswd
if station.isconnected() == True:
print(“Already connected”)
return
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print(“Connection successful”)
print(station.ifconfig())
def disconnect():
if station.active() == True:
station.active(False)
if station.isconnected() == False:
print(“Disconnected”)
connect(“NUA”, “***********”)
disconnect()
“NUA” is the name/SSID of the WiFi network in the above script. Beside the SSID is its network password or network key. You must pass the SSID and network key of the WiFi connection in the script to connect ESP8266/ESP32 to the internet.

A screenshot of the result after uploading and running the above script in UPyCraft for ESP8266.
Automatically connecting to a WiFi network
ESP8266/ESP32 can be configured to automatically connect to WiFi. This can be done by adding the commands for connecting with a WiFi network in the boot.py file. The boot.py file is always run first when ESP8266/ESP32 or any MicroPython port is booted up.
Add the below code at the end of the boot.py file and re-upload the boot.py to ESP8266/ESP32:
import network
station = network.WLAN(network.STA_IF)
if station.isconnected() == True:
print(“Already connected”)
station.active(True)
station.connect(“NUA”, “***********”)
while station.isconnected() == False:
pass
print(“Connection successful”)
print(station.ifconfig())
Once again, “NUA” is the name/SSID of the WiFi network. Beside the SSID is its network password or network key. You must pass the SSID and network key of the WiFi connection in the script to connect ESP8266/ESP32 to the internet.

The modified boot.py file.
The WiFi connection can be verified in the main execution script using this code snippet…
import network
station = network.WLAN(network.STA_IF)
if station.isconnected() == True:
print(“Connected to WiFi!”)
print(station.ifconfig())
In the main script, the WiFi connection can be deactivated using this code snippet…
if station.active() == True:
station.active(False)
if station.isconnected() == False:
print(“Disconnected”)

The main execution script, which verifies the default WiFi connection setup upon boot-up and deactivates it if active.
Here is a screenshot of the result when uploading and running the modified boot.py file.
Conclusion
MicroPython provides a network module to connect with different mediums. A commonly used network interface is WiFi. MicroPython ports — including ESP32 and ESP8266 — can be configured as a WiFi station and WiFi access points when using the MicroPython firmware.
Typically, ESP32/ESP8266 must be configured as a WiFi station for the internet of things to properly connect to WiFi and communicate with an IoT/Cloud platform or service. Afterward, the socket module can be used to execute various internet protocols and access network services.
It’s possible to manually connect ESP32/ESP8266 or any MicroPython port to a WiFi network by using the main execution script. The connection to a WiFi network can also be automated by modifying the boot.py file.
You may also like:
Filed Under: Featured Contributions
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.