ESP32 / ESP8266 MicroPython: Automatic connection to WiFi

The objective of this post is to explain how to connect automatically to a WiFi network on MicroPython, without needing to insert all the individual commands in the prompt. The procedure was tested on both the ESP32 and the ESP8266.


Introduction

The objective of this post is to explain how to connect automatically to a WiFi network on MicroPython, without needing to insert all the individual commands in the prompt. The procedure was tested on both the ESP32 and the ESP8266. The prints are from the tests on the ESP32. Note that messages that are automatically printed on the ESP8266 are different from the ones on the ESP32, so the results will be different from the screenshots of this tutorial. Nevertheless, it will work the same way.

We will check two approaches, one that requires importing a function from a module and executing it whenever needed to connect to the WiFi network, and another one that is fully automatic and connects the board to the WiFi network after booting.

Please note that both solutions require the upload of files to MicroPython’s file system. You can consult this previous tutorial for a detailed explanation. Also, for an explanation on how to manually connect to a WiFi network, check this tutorial. All the steps are important since we are only basically encapsulating them in a function of a module.

 

Connection on module call

In this first section we will explain how to connect to the WiFi network automatically upon calling a function defined in a module. This is useful if we don’t always want to connect to the WiFi network every time we use the ESP32 / ESP8266. So, it gives us control to decide when to do it.

To implement this method, we will define a simple Python function to implement the connection procedure. We will call this function connect.

def connect():
#Python code goes here

Then, we will import the network module, which is needed to access the functionality to connect to a WiFi network. To facilitate things, we will also store our network credentials (ssid and password) on two variables.

import network

ssid = "yourNetworkName"
password = "yourNetworkPassword"

Next, we get an instance of the station WiFi interface and store it on a variable. We will then check if we are already connected to a WiFi network. If so, we will print a warning and finish the execution.

station = network.WLAN(network.STA_IF)

if station.isconnected() == True:
	print("Already connected")
	return

If we are not yet connected, then we activate the network interface and perform the actual connection, using the credentials stored in the previously declared variables.

station.active(True)
station.connect(ssid, password)

Since the connection may take a while, we will do an active wait until we are connected, by checking the output of the isconnected method. Note that the pass statement is required just because of the Python syntax, since it does nothing.

Also take in consideration that for the sake of simplicity we will be infinitely waiting for the connection, so if for example the WiFi credentials are wrong, the module will hang infinitely trying to connect. Naturally, for a more robust real case scenario, we would need to implement some kind of timeout mechanism.

In the end, we will print a success message and the WiFi configurations

while station.isconnected() == False:
	pass

print("Connection successful")
print(station.ifconfig())

The full code for the module can be seen bellow. Save the file in a directory of your choice, with a .py extension. You can name it as you like, but for this tutorial we will call it ConnectWiFi.py.

def connect():
	import network

	ssid = "yourNetworkName"
	password =  "yourNetworkPassword"

	station = network.WLAN(network.STA_IF)

	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())

Finally, to upload the code, just open the command line, navigate to the directory where you stored the file and hit the following command, changing COM5 by the serial port where your device is.

ampy --port COM5 put ConnectWiFi.py

Now, connect to the Python prompt using a software of your choice. In this tutorial we will be using Putty. There, to confirm that the new file was correctly uploaded, hit the following commands:

import os
os.listdir()

As shown in figure 1, the file should be listed.

ESP32 ESP8266 MicroPython upload File for Wifi

Figure 1 – Successful upload of the WiFi connect module.

Now, we simply import the module and call the connect function, as shown bellow.

import ConnectWiFi
ConnectWiFi.connect()

The result is shown in figure 2. Note that our success message is shown at the end, indicating that we are now connected.

ESP32 ESP8266 Automatic WiFi connection via module

Figure 2 – Output of the connect function call.

Just to confirm our safeguard is working well, you can try to call the connect function again. It should now return a message indicating that we are already connected, as defined in the code. Check this on figure 3.

ESP8266 ESP32 MicroPython Already Connected to WiFi

Figure 3 – Warning message when calling the function after being connected to the WiFi network.


Automatic connection

Before going to the implementation, we need to first analyse a particularity of MicroPython which is related to some boot scripts.

So, as we have seen in some previous tutorials, our MicroPython installation has a boot.py file in the file system. This is a particular file that runs when the board powers [1]. It already has some low level code, which we should not remove.

As indicated in the MicroPython documentation shown here, we could use this file to put our code to connect to the WiFi network, which would be executed when the board was powered on.

Nevertheless, we will follow a different approach. So, besides the boot.py, if a file called main.py exists on the file system, it will run after the completion of the boot.py script [1]. So, we will create it and use it to automatically connect to the WiFi network upon booting. Note that it can be used to implement other kind of code for our application. Also, since it is not mandatory, we can play with it without worrying.

Now, to implement the automatic connection, we will reuse the previous module. So, start by creating a file called main.py. As stated before, it needs to be called this way this time (as opposed to the name of the module we defined before), or it won’t automatically execute.

There, just put the importation of the ConnectWiFi module and the call to the connect function, just the same way we did manually.

import ConnectWiFi
ConnectWiFi.connect()

Now, load the file to the file system with the command bellow (don’t forget to change COM5 by your device port). If you are still connected via Putty or other software, you need to close the connection first or this will fail.

ampy --port COM5 put main.py

Now reconnect back to the Python prompt. You can confirm the successful upload of the file with the os.listdir() call we did before.

Note that nothing is supposed to happen, since MicroPython was already running. To check if our main.py is connecting the board to the WiFi network as specified, just reset your ESP32 / ESP8266, with the prompt open. It should now reboot and execute our function, as shown in figure 4.

ESP32 ESP8266 MicroPython automatic connection to WiFi

Figure 4 – Automatic connection after boot.

We can confirm that we are connected by importing the ConnectWiFi module and trying to call the connect function. It should return the “Already connected” warning, as shown in figure 5.

ESP32 ESP8266 MicroPython Already connected WiFi

Figure 5 – Warning on trying to connect again to the WiFi network.


Related Content

 

Related Posts

 

References 

[1] https://learn.adafruit.com/micropython-basics-load-files-and-run-code/boot-scripts

Advertisements
This entry was posted in ESP32, ESP8266 and tagged , , , , . Bookmark the permalink.

6 Responses to ESP32 / ESP8266 MicroPython: Automatic connection to WiFi

  1. Pingback: ESP32 / ESP8266 MicroPython: HTTP GET Requests | techtutorialsx

  2. Pingback: ESP32 / ESP8266 MicroPython: HTTP POST Requests | techtutorialsx

  3. Pingback: ESP32 Arduino: Getting started with WiFi | techtutorialsx

  4. Pingback: ESP32 MicroPython: HTTP Webserver with Picoweb | techtutorialsx

  5. Pingback: ESP32 MicroPython: Changing the HTTP response content-type of Picoweb route | techtutorialsx

  6. Pingback: ESP32 Picoweb: Serving JSON content | techtutorialsx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s