Chapter 21 WiFi Working Modes

In this chapter, we’ll focus on the WiFi infrastructure for ESP32-WROVER.

ESP32-WROVER has 3 different WiFi operating modes: station mode, AP mode and AP+station mode. All WiFi programming projects must be configured with WiFi operating mode before using WiFi, otherwise WiFi cannot be used.

Project 21.1 Station mode

Component List

ESP32-WROVER x1

Chapter01_00

Micro USB Wire x1

Chapter08_00

Component knowledge

Station mode

When ESP32 selects Station mode, it acts as a WiFi client. It can connect to the router network and communicate with other devices on the router via WiFi connection. As shown below, the PC is connected to the router, and if ESP32 wants to communicate with the PC, it needs to be connected to the router.

../../../_images/Chapter32_00.png

Circuit

Connect Freenove ESP32 to the computer using the USB cable.

../../../_images/Chapter32_01.png

Code

Move the program folder “Freenove_Super_Starter_Kit_for_ESP32/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.

Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “21.1_Station_mode” and double click “Station_mode.py”.

21.1_Station_mode

../../../_images/Chapter32_12.png

Because the names and passwords of routers in various places are different, before the Code runs, users need to enter the correct router’s name and password in the box as shown in the illustration above.

After making sure the router name and password are entered correctly, compile and upload codes to ESP32-WROVER, wait for ESP32 to connect to your router and print the IP address assigned by the router to ESP32 in “Shell”.

../../../_images/Chapter32_13.png

The following is the program code:

 1import time
 2import network
 3
 4ssidRouter     = '********' #Enter the router name
 5passwordRouter = '********' #Enter the router password
 6
 7def STA_Setup(ssidRouter,passwordRouter):
 8    print("Setup start")
 9    sta_if = network.WLAN(network.STA_IF)
10    if not sta_if.isconnected():
11        print('connecting to',ssidRouter)
12        sta_if.active(True)
13        sta_if.connect(ssidRouter,passwordRouter)
14        while not sta_if.isconnected():
15            pass
16    print('Connected, IP address:', sta_if.ifconfig())
17    print("Setup End")
18
19try:
20    STA_Setup(ssidRouter,passwordRouter)
21except:
22    sta_if.disconnect()

Import network module.

1import network

Enter correct router name and password.

1ssidRouter     = '********' #Enter the router name
2passwordRouter = '********' #Enter the router password

Set ESP32 in Station mode.

1sta_if = network.WLAN(network.STA_IF)

Activate ESP32’s Station mode, initiate a connection request to the router and enter the password to connect.

1while not sta_if.isconnected():
2    pass

Print the IP address assigned to ESP32-WROVER in “Shell”.

1print('Connected, IP address:', sta_if.ifconfig())

Reference

Class network

Before each use of network , please add the statement “ import network “ to the top of the python file.

WLAN(interface_id): Set to WiFi mode.

network.STA_IF: Client, connecting to other WiFi access points.

network.AP_IF: Access points, allowing other WiFi clients to connect.

active(is_active): With parameters, it is to check whether to activate the network interface; Without parameters, it is to query the current state of the network interface.

scan(ssid, bssid, channel, RSSI, authmode, hidden): Scan for wireless networks available nearby (only scan on STA interface), return a tuple list of information about the WiFi access point.

bssid: The hardware address of the access point, returned in binary form as a byte object. You can use ubinascii.hexlify() to convert it to ASCII format.

authmode: Access type

AUTH_OPEN = 0

AUTH_WEP = 1

AUTH_WPA_PSK = 2

AUTH_WPA2_PSK = 3

AUTH_WPA_WPA2_PSK = 4

AUTH_MAX = 6

Hidden: Whether to scan for hidden access points

False: Only scanning for visible access points

True: Scanning for all access points including the hidden ones.

isconnected(): Check whether ESP32 is connected to AP in Station mode. In STA mode, it returns True if it is connected to a WiFi access point and has a valid IP address; Otherwise it returns False.

connect(ssid, password): Connecting to wireless network.

ssid: WiFiname

password: WiFipassword

disconnect(): Disconnect from the currently connected wireless network.

Project 21.2 AP mode

Component List & Circuit

Component List & Circuit are the same as in Section 23.1.

Component knowledge

AP mode

When ESP32 selects AP mode, it creates a hotspot network that is separate from the Internet and waits for other WiFi devices to connect. As shown in the figure below, ESP32 is used as a hotspot. If a mobile phone or PC wants to communicate with ESP32, it must be connected to the hotspot of ESP32. Only after a connection is established with ESP32 can they communicate.

../../../_images/Chapter32_04.png

Circuit

Connect Freenove ESP32 to the computer using the USB cable.

../../../_images/Chapter32_01.png

Code

Move the program folder “Freenove_Super_Starter_Kit_for_ESP32/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.

Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “21.2_AP_mode”. and double click “AP_mode.py”.

21.2_AP_mode

../../../_images/Chapter32_14.png

Before the Code runs, you can make any changes to the AP name and password for ESP32 in the box as shown in the illustration above. Of course, you can leave it alone by default.

Click “Run current script”, open the AP function of ESP32 and print the access point information.

../../../_images/Chapter32_15.png

Turn on the WiFi scanning function of your phone, and you can see the ssid_AP on ESP32, which is called “WiFi_Name” in this Code. You can enter the password “12345678” to connect it or change its AP name and password by modifying Code.

../../../_images/Chapter32_16.png

The following is the program code:

 1import network
 2
 3ssidAP         = 'WiFi_Name' #Enter the router name
 4passwordAP     = '12345678'  #Enter the router password
 5
 6local_IP       = '192.168.1.10'
 7gateway        = '192.168.1.1'
 8subnet         = '255.255.255.0'
 9dns            = '8.8.8.8'
10
11ap_if = network.WLAN(network.AP_IF)
12
13def AP_Setup(ssidAP,passwordAP):
14    ap_if.ifconfig([local_IP,gateway,subnet,dns])
15    print("Setting soft-AP  ... ")
16    ap_if.config(essid=ssidAP,authmode=network.AUTH_WPA_WPA2_PSK, password=passwordAP)
17    ap_if.active(True)
18    print('Success, IP address:', ap_if.ifconfig())
19    print("Setup End\n")
20
21try:
22    AP_Setup(ssidAP,passwordAP)
23except:
24    print("Failed, please disconnect the power and restart the operation.")
25    ap_if.disconnect()

Import network module.

1import network

Enter correct AP name and password.

1ssidAP         = 'WiFi_Name' #Enter the router name
2passwordAP     = '12345678'  #Enter the router password

Set ESP32 in AP mode.

1ap_if = network.WLAN(network.AP_IF)

Configure IP address, gateway and subnet mask for ESP32.

1ap_if.ifconfig([local_IP,gateway,subnet,dns])

Turn on an AP in ESP32, whose name is set by ssid_AP and password is set by password_AP.

1ap_if.config(essid=ssidAP,authmode=network.AUTH_WPA_WPA2_PSK, password=passwordAP)
2ap_if.active(True)

If the program is running abnormally, the AP disconnection function will be called.

1ap_if.disconnect()

Reference

Class network

Before each use of network , please add the statement “ import network “ to the top of the python file.

WLAN(interface_id): Set to WiFi mode.

network.STA_IF: Client, connecting to other WiFi access points

network.AP_IF: Access points, allowing other WiFi clients to connect

active(is_active): With parameters, it is to check whether to activate the network interface; Without parameters, it is to query the current state of the network interface

isconnected(): In AP mode, it returns True if it is connected to the station; otherwise it returns False.

connect(ssid, password): Connecting to wireless network

ssid: WiFiname

password: WiFipassword

config(essid, channel): To obtain the MAC address of the access point or to set the WiFi channel and the name of the WiFi access point.

ssid: WiFi account name

channel: WiFichannel

ifconfig([(ip, subnet, gateway, dns)]): Without parameters, it returns a 4-tuple (ip, subnet_mask, gateway, DNS_server); With parameters, it configures static IP.

ip: IPaddress

subnet_mask: subnet mask

gateway: gateway

DNS_server: DNSserver

disconnect(): Disconnect from the currently connected wireless network

status(): Return the current status of the wireless connection

Project 21.3 AP+Station mode

Component List

ESP32-WROVER x1

Chapter01_00

Micro USB Wire x1

Chapter08_00

Component knowledge

AP+Station mode

In addition to AP mode and station mode, ESP32 can also use AP mode and station mode at the same time. This mode contains the functions of the previous two modes. Turn on ESP32’s station mode, connect it to the router network, and it can communicate with the Internet via the router. At the same time, turn on its AP mode to create a hotspot network. Other WiFi devices can choose to connect to the router network or the hotspot network to communicate with ESP32.

Circuit

Connect Freenove ESP32 to the computer using the USB cable.

../../../_images/Chapter32_08.png

Code

Move the program folder “Freenove_Super_Starter_Kit_for_ESP32/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.

Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “21.3_AP+STA_mode”and double click “AP+STA_mode.py”.

21.3_AP+STA_mode

../../../_images/Chapter32_17.png

It is analogous to project 21.1 and project 21.2. Before running the Code, you need to modify ssidRouter, passwordRouter, ssidAP and passwordAP shown in the box of the illustration above.

After making sure that the code is modified correctly, click “Run current script” and the “Shell” will display as follows:

../../../_images/Chapter32_18.png

Turn on the WiFi scanning function of your phone, and you can see the ssidAP on ESP32.

../../../_images/Chapter32_19.png

The following is the program code:

 1import network
 2
 3ssidRouter     = '********' #Enter the router name
 4passwordRouter = '********' #Enter the router password
 5
 6ssidAP         = 'WiFi_Name'#Enter the AP name
 7passwordAP     = '12345678' #Enter the AP password
 8
 9local_IP       = '192.168.4.150'
10gateway        = '192.168.4.1'
11subnet         = '255.255.255.0'
12dns            = '8.8.8.8'
13
14sta_if = network.WLAN(network.STA_IF)
15ap_if = network.WLAN(network.AP_IF)
16
17def STA_Setup(ssidRouter,passwordRouter):
18    print("Setting soft-STA  ... ")
19    if not sta_if.isconnected():
20        print('connecting to',ssidRouter)
21        sta_if.active(True)
22        sta_if.connect(ssidRouter,passwordRouter)
23        while not sta_if.isconnected():
24            pass
25    print('Connected, IP address:', sta_if.ifconfig())
26    print("Setup End")
27
28def AP_Setup(ssidAP,passwordAP):
29    ap_if.ifconfig([local_IP,gateway,subnet,dns])
30    print("Setting soft-AP  ... ")
31    ap_if.config(essid=ssidAP,authmode=network.AUTH_WPA_WPA2_PSK, password=passwordAP)
32    ap_if.active(True)
33    print('Success, IP address:', ap_if.ifconfig())
34    print("Setup End\n")
35
36try:
37    AP_Setup(ssidAP,passwordAP)    
38    STA_Setup(ssidRouter,passwordRouter)
39except:
40    sta_if.disconnect()
41    ap_if.disconnect()