0

$USD

$USD
TUTORIALS ESP32ESP8266MicroPython

ESP32 / ESP8266 MicroPython Tutorial: Automatic connection to WiFi

DFRobot Jul 13 2017 2160

The objective of this MicroPython Tutorial 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 MicroPython Tutorial 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.

1  def connect():
2  #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.

1  import network
2  
3 ssid = "yourNetworkName"
4 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.

1  station = network.WLAN(network.STA_IF)

3   if station.isconnected() == True:
4   print("Already connected")
5   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.

1  station.active(True)
2  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 is connected 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


1 while station.isconnected() == False:
2  pass

4 print("Connection successful")
5 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.

1 def connect():
2    import network

4    ssid = "yourNetworkName"
5    password =  "yourNetworkPassword"
6
7    station = network.WLAN(network.STA_IF)

9    if station.isconnected() == True:
10  print("Already connected")
11  return
12
13    station.active(True)
14    station.connect(ssid, password)
15
16    while station.isconnected() == False:
17        pass
18
19    print("Connection successful")
20    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.
1  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:

1  import os
2  os.listdir()

As shown in figure 1, the file should be listed.
Figure 1 – Successful upload of the WiFi connect module.
Now, we simply import the module and call the connect function, as shown bellow.

1 import ConnectWiFi
2 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.

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.

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.

1 import ConnectWiFi
2 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.

1 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.

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.

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

NOTE: This article is written by Nuno Santos who is an kindly Electronics and Computers Engineer. live in Lisbon, Portugal. you could check the original article here.
He had written many useful tutorials and projects about ESP32, ESP8266, If you are interested, you could check his blog to know more.
DFRobot supply lots of esp32 arduino tutorials and esp32 projects for makers to learn.