MicroPython tutorial, manage WiFi connection at startup on ESP8266 / ESP32

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

In this new tutorial dedicated to MicroPython firmware, we will learn how to connect an ESP8266 or ESP32 module to a WiFi network. At first, we will see how to connect manually using the REPL interpreter. Then we’ll see how to create a login script that automatically handles the connection when the module starts. If you are on Windows, I advise you to install and use the uPiCraft IDE presented previously. It is a code editor dedicated to the MicroPython language. uPiCraft can develop and manage its code on all development boards supported by MicroPython (pyboard, WiPy, ESP8266, ESP32, STM32 …). To make the MicroPython accessible to beginners, I used uPiCraft in all MicroPython tutorials. You can also use screen on macOS / Linux or Putty on Windows.

A little reading before you start

If you are new to MicroPython, I advise you to read these articles which will help you to take in hand this language:

Manual connection to a WiFi network from the REPL shell

Connect the ESP8266 / ESP32 card and run uPiCraft. Go to the Tools then Serial menu and choose the COM port to which the card is connected. Connect to the map to launch the REPL interpreter by clicking on the connection icon.

7 icone connexion serie

When REPL is started, the command prompt is symbolized by >>>. The files are listed under the Device in the left sidebar.

We start by importing the Network module

import network

The WLAN class of the network module contains all the network management methods. The ESP8266 / ESP module can act as an access point (network.AP_IF mode) or as a client (network.STA_IF mode). We will create an instance of the WiFi object of type network.STA_IF. run

station = network.WLAN(network.STA_IF)

The WiFi interface must then be enabled using the active method (True / False).

station.active(True)

All that remains is to connect to a WiFi network using the connect() method. The connect () method needs the network name as well as the password. In return, the function returns the IP address assigned by the DHCP server to the module.

>>> station.connect("nomReseau", "MoteDePasseReseau")
>>> stationscandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 8
cnt 

connected with X72, channel 1
dhcp client start...
.isip:192.168.1.81,mask:255.255.255.0,gw:192.168.1.1

There are several methods used to test (anywhere in your scripts) the state of the WiFi connection:

  • isconnected(), whether the module is connected to the network
  • ifconfig(), retrieves the IP address of the module, the IP address of the DHCP router

Assign a fixed IP to a MicroPython ESP8266 / ESP32 module

When there are many connected objects, it is best to assign a fixed IP address. It will be easier to access a WEB interface, carry out maintenance operations with WebREPL. For this, we use the ifconfig() method. The IP address, the subnet, the DHCP server and the DNS server are passed to him (the one of Google will do, 8.8.8.8). Then we connect with the method connect(ssid, password) simply.

>>> station.disconnect()
>>> station.status()
>>> station.ifconfig(('192.168.1.10', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
>>> station.connect()

There you go.

MicroPython script for automatic connection

Now, we just have to automate all that. We could just write the login code in the boot.py script. It is better to deport the code in a dedicated script. Maintenance will be easier and it will be easier to use in other scripts.

Create a new script and paste the code below. Modify the ip, subnet, gateway, dns, ssid and password constants. Save the script as ConnectWifi.py (for example)

def connect():
    import network
    
    ip        = '192.168.1.10'
    subnet    = '255.255.255.0'
    gateway   = '192.168.1.1'
    dns       = '8.8.8.8'
    ssid      = "yourSSID"
    password  =  "yourPassword"
 
    station = network.WLAN(network.STA_IF)
 
    if station.isconnected() == True:
        print("Already connected")
        return
 
    station.active(True)
    station.ifconfig((ip,subnet,gateway,dns))
    station.connect()
 
    while station.isconnected() == False:
        pass
 
    print("Connection successful")
    print(station.ifconfig())

def disconnect():
    import network
    station = network.WLAN(network.STA_IF)
    station.disconnect()
    station.active(False)

Upload the script to the map (Tools -> Download). From the REPL interpreter, execute import ConnectWifi  then ConnectWifi.connect() . The disconnect() method allows you to disconnect the WiFi module from your scripts. Now, we can very simply launch the WiFi connection from anywhere like this

import ConnectWifi
ConnectWiFi.connect()

For example, if you want to start the connection at startup, just open the boot.py script and add the two previous commands.

micropython connect wifi

Resources used to write this article:

  • https://docs.micropython.org/en/latest/esp8266/library/network.html#module-network
  • https://techtutorialsx.com/2017/06/01/esp32-micropython-connecting-to-a-wifi-network/
  • http://docs.micropython.org/en/v1.8.7/esp8266/esp8266/tutorial/network_basics.html
Click to rate this post!
[Total: 0 Average: 0]

Are you having a problem with this topic?

Maybe someone has already found the solution, visit the forum before asking your question
Ask your question

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

Did you like this project ? Don't miss any more projects by subscribing to our weekly newsletter!

We will be happy to hear your thoughts

      Leave a Reply

      DIY Projects