Categories
ESP32 Python

MicroPython connect to wireless network

In our previous post we uploaded a python script to the ESP32 to run on boot. This time we will connect the ESP32 to our wireless network.

Firstly I am going to create a config.py file to store any configuration parameters we are going to use. In this case we simply have the SSID and password defined in here.

ssid='ssidname'
password='password'

Next I create a file called wifi.py, this contains the code to connect the ESP32 to the wireless network. We want to import our config.py and the network python module.

import config
import network

print("Connecting to wifi...")
# Activate the station interface
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
# Connect to your wifi network
sta_if.connect(config.ssid, config.password)
# Wait until the wireless is connected
while not sta_if.isconnected():
    pass
# Print out the network configuration received from DHCP
print('network config:', sta_if.ifconfig())

The comments in the code should explain what we are doing here, but essentially we activate the interface, connect to the wifi, wait until it is connected, then print out the IP details received from DHCP.

Now we need to upload the two python files to the ESP32 using ampy via serial, making sure wifi.py is uploaded as main.py so it is executed upon device boot.

ampy --delay 1 --port /dev/cu.usbserial-0001 put config.py 
ampy --delay 1 --port /dev/cu.usbserial-0001 put wifi.py /main.py

Now monitoring the serial console, we should see the ESP32 return valid IP details once it connects to the wireless network.

MicroPython connect to wifi
MicroPython connected to wifi

Leave a Reply

Your email address will not be published. Required fields are marked *