ESP32 MicroPython WiFi Testing

Development Steps:

  1. Connection Process

ESP32 MicroPython WiFi Testing

2. Core Functions

  • Station Mode (Connect to Router)
  • AP Mode (Create Hotspot)
  • Network Scanning
  • HTTP Requests
  • Socket Communication

Test Code:

1. Connect to WiFi (Station Mode)

import network
import time

# Configure WiFi
SSID ="your_wifi_ssid"
PASSWORD ="your_wifi_password"

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

if not sta_if.isconnected():
    print("Connecting to WiFi...")
    sta_if.connect(SSID, PASSWORD)

# Wait for connection
for _ in range(20):
    if sta_if.isconnected():
        break
    print(".", end="")
    time.sleep(1)

if sta_if.isconnected():
    print("\nConnected!")
    print("IP Address:", sta_if.ifconfig()[0])

sta_if.disconnect()

    time.sleep(1)

if not sta_if.isconnected():
    print("WiFi disconnect...")
else:
    print("\nConnection failed!")

2. Create Hotspot (AP Mode)

import network
import time

# Configure WiFi

# essid= "your_wifi_ssid"
# password= "your_wifi_password"

ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid="ESP32-AP", password="12345678", authmode=3)

print("Access Point active")
print("SSID:", ap.config("essid"))
print("IP Address:", ap.ifconfig()[0])

time.sleep(1)

if not ap.isconnected():
    print("WiFi disconnect...")
while not ap.isconnected():
        time.sleep(1)
print("Wait connect...")
else:
    print("\nConnection ok!")

3. Scan Nearby WiFi

import network
import time

def auth_types(code):
    return {
        0:"OPEN",
        1:"WEP",
        2:"WPA-PSK",
        3:"WPA2-PSK",
        4:"WPA/WPA2-PSK"
    }.get(code,"UNKNOWN")

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

nets = sta_if.scan()
print("{:<30} {:<5} {:<10} {:<15}".format("SSID","CH","RSSI","AUTH"))

for net in nets:
    ssid = net[0].decode('utf-8')
    ch = net[2]
    rssi = net[3]
    auth = net[4]
    print("{:<30} {:<5} {:<10} {:<15}".format(ssid, ch, rssi, auth_types(auth)))

4. HTTP Request Test

import network
import time

import urequests as requests



# Ensure connected to WiFi
url ="http://httpbin.org/get"

# WiFi configuration
WIFI_SSID ="your_wifi_name"
WIFI_PASSWORD ="your_wifi_password"

# Connect to WiFi function
def connect_wifi():
    # Create WLAN object and set to STA mode (client mode)
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    # Check if connected
    if wlan.isconnected():
        print("Connected to WiFi")
        print("Network configuration:", wlan.ifconfig())
        return wlan

    print(f"Trying to connect to {WIFI_SSID}...")
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)

    # Wait for connection
    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        time.sleep(1)

    # Check connection status
    if wlan.status() != 3:
        raise RuntimeError(f"WiFi connection failed, status code: {wlan.status()}")
    else:
        print("WiFi connected successfully")
        print("Network configuration:", wlan.ifconfig())
        return wlan

# HTTP request test function
def test_http_request():
    try:
        print("Sending HTTP request to httpbin.org...")
        response = requests.get('http://httpbin.org/get')
        print("Status code:", response.status_code)
        print("Response content:", response.text)
        response.close()
    except Exception as e:
        print(f"HTTP request failed: {e}")

# Main program
try:
    # Connect to WiFi
    wlan = connect_wifi()

    # Test HTTP request
    test_http_request()

except Exception as e:
    print(f"An error occurred: {e}")



5. Socket Client Example

import network
import time
import socket


# WiFi configuration
WIFI_SSID ="your_wifi_name"
WIFI_PASSWORD ="your_wifi_password"

# Configure server information
SERVER_IP ="192.168.1.100"
PORT = 8080


# Connect to WiFi function
def connect_wifi():
    # Create WLAN object and set to STA mode (client mode)
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    # Check if connected
    if wlan.isconnected():
        print("Connected to WiFi")
        print("Network configuration:", wlan.ifconfig())
        return wlan

    print(f"Trying to connect to {WIFI_SSID}...")
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)

    # Wait for connection
    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        time.sleep(1)

    # Check connection status
    if wlan.status() != 3:
        raise RuntimeError(f"WiFi connection failed, status code: {wlan.status()}")
    else:
        print("WiFi connected successfully")
        print("Network configuration:", wlan.ifconfig())
        return wlan

# HTTP request test function
def test_socket_client():
    try:
        s = socket.socket()
        s.connect((SERVER_IP, PORT))

        # Send data
        s.send(b"Hello from ESP32!")

        # Receive response
        data = s.recv(1024)
        print("Received:", data.decode())

        s.close()
    except Exception as e:
        print(f"HTTP request failed: {e}")

# Main program
try:
    # Connect to WiFi
    wlan = connect_wifi()

    # Test socket client
    test_socket_client()

except Exception as e:
    print(f"An error occurred: {e}")



ESP32 MicroPython WiFi Testing

Troubleshooting Common Issues:

  1. Connection Failed

  • Check SSID/password
  • Ensure the router supports 2.4GHz band
  • Increase connection timeout
  • Insufficient Memory

    • Use gc.collect() to manually reclaim memory
    • Avoid large buffers
  • Socket Error

    • Check firewall settings
    • Verify server IP and port
  • HTTP Request Failed

    • Using HTTPS requires installing certificates (recommended to use mip)
    • Increase timeout

    Tip: Use mip to install additional network libraries:

    import mip
    mip.install("urequests")
    

    References

    https://docs.micropython.org/en/latest/esp32/quickref.html#wlan

    http://www.micropython.com.cn/en/latest/esp32/quickref.html#networking

    https://developer.quectel.com/doc/quecpython/API_reference/zh/wifilib/WLAN.html

    Leave a Comment