Internet of Things (IoT) is a collective term for any devices that are connected to the Internet, and your Nano ESP32 is one of them. Using its built-in antenna, the board can connect and communicate over the Internet.
In this chapter, we are going to look into the essential steps needed to connect your board to a Wi-Fi® network, and how to make a test call to the Internet.
You will learn the following in this chapter:
This chapter introduces Internet & connectivity related code and concepts that may be a bit hard to learn and digest. You do NOT need to follow this chapter to succeed at making awesome MicroPython projects, but we encourage you to learn!
Internet of Things is a very vast area to explore, and in this chapter, we will focus on how to achieve a simple request to the Internet.
When working with IoT, there are a number of important factors to consider. For the sake of simplicity, we are going to divide them into two separate parts:
In this chapter, we will be using a number of new modules:
. These make it possible to connect, maintain the connection, and make requests to the Internet.
Connecting to Wi-Fi® is pretty straightforward concept, and is very similar to how we connect using our phones / computers.
With MicroPython, we can do it with just a few lines of code, seen in the script below:
1import network23WIFI_NETWORK='YOUR_NETWORK_NAME'4WIFI_PASSWORD='YOUR_NETWORK_PASSWORD'56wlan = network.WLAN(network.STA_IF)7wlan.active(True)8wlan.connect(WIFI_NETWORK, WIFI_PASSWORD)910print()11print("Connected to ",WIFI_NETWORK)
Here we simply add our network name/password, create the
object, set it to
to the Wi-Fi® network!
Once we are connected to the Wi-Fi® network, we can move on to make requests to the Internet!
Being connected to a Wi-Fi® network means we now have access to the Internet. We will now test out our connection, by making a request to a server!
To make a request, we need to use the
module, we can input a URL (and more information), to construct a request that is sent to a server. In this case, we will send a test request to google.com.
To do this, we need first to include the Wi-Fi® connection code we used in the previous example, and add a few more lines to make the request!
1import urequests2import network34# Request a random cat fact from the Meowfacts API5url = "https://meowfacts.herokuapp.com/"67WIFI_NETWORK='YOUR_NETWORK_NAME'8WIFI_PASSWORD='YOUR_NETWORK_PASSWORD'910wlan = network.WLAN(network.STA_IF)11wlan.active(True)12wlan.connect(WIFI_NETWORK, WIFI_PASSWORD)1314print()15print("Connected to ",WIFI_NETWORK)1617response = urequests.get(url)1819print(response.text)
What we just did, was to connect a server, and request something. This is one of the most common methods to exchange data over the Internet, and is a fundamental building block when working with IoT devices.
This exercise is optional, but will enable your board to connect to your Wi-Fi network automatically.
If you are planning to do a lot of IoT projects, you might want to make sure your board connects to your Wi-Fi® network automatically.
To do this, we can edit our
file. Remember, the code on this file is the first to be executed when our board is powered. To edit your
file, open the editor, and select the file from the list of files to the left.
Then, in the
file, we can past the Wi-Fi connection code that we just previously.
1"""2This code goes into "boot.py".3It will automatically run when4you start your board, and connects5to the Wi-Fi network specified.6"""78wlan = network.WLAN(network.STA_IF)9wlan.active(True)10wlan.connect(WIFI_NETWORK, WIFI_PASSWORD)1112print()13print("Connected to ",WIFI_NETWORK)
Remember now to also click the SAVE button in the editor. This will overwrite the existing
file with your new changes.
This example requires you to register an account at OpenWeather, and obtain something called an "API KEY".
In this exercise, we will be making a request to an API that provides weather data. We will see how we can manipulate the request to specify which city in the world we want the data from, and how to extract exactly what data we want from the request.
1. Register an account at OpenWeather.
2. Go to the API keys section, and create a new API key.
3. Open the code editor, and copy paste the following script to the
file. Notice that at the top of the code, we have an
variable. Paste your API key obtained from step 2 here.
Note that the example below does not have the Wi-Fi® code. If you followed the previous exercise, you do not need to manually enter your credentials anymore.
1"""2Simple GET request to OpenWeather.3This prints out the current temperature4of the city specified in the city_name5variable.6"""7import urequests89# URL, API key and name of city variables.10# Change the api_key and the city_name11url = "https://api.openweathermap.org/data/2.5/weather?q="12api_key = "YOUR_API_KEY"13city_name = "YOUR_CITY"1415# Here we build a request URL16response = urequests.get(url + city_name + "&appid=" + api_key)1718# Print out the complete response19print(response.text)20print()2122# Convert to a JSON object23response_data = response.json()2425# Access temperature object26temp_kelvin = response_data['main']['temp']2728# Because it is in kelvin, convert to celsius29temp_celsius = int(temp_kelvin) - 273.153031print("Temp (K):", temp_kelvin)32print("Temp (C):", temp_celsius)
Once we run the script, after a while, we should be receiving the response. This script is designed to:
We now have a device that is capable of accessing the weather from anywhere in the world!
In this exercise, we will make a request to something called an network time protocol (NTP) server.
As our board does not know the current time, it is necessary for it to make a request to a server that keeps track on it.
Open the code editor, and copy paste the following script to the
1import network, usocket, ustruct, utime23TIMESTAMP = 220898880045# Create new socket6client = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)7client.bind(("", 8080))8#client.settimeout(3.0)910# Get addr info via DNS11addr = usocket.getaddrinfo("pool.ntp.org", 123)1213# Send query14client.sendto('\x1b' + 47 * '\0', addr)15data, address = client.recvfrom(1024)1617# Print time18t = ustruct.unpack(">IIIIIIIIIIII", data) - TIMESTAMP19print ("Year:%d Month:%d Day:%d Time: %d:%d:%d" % (utime.localtime(t)[0:6]))2021# Close socket22client.close()
Then, click on the ”PLAY" symbol to run the script.
Note that this example is a little bit more advanced compared to the previous examples we have worked with. But in a nutshell, what happens is:
Congratulations, you have now successfully retrieved the latest time, meaning your board is in sync with the rest of the world!
In the exercises above, we retrieved weather data and current time. Combined, this makes for an excellent alarm clock that can keep track of time, set alarms and also give you weather updates!
If you want to make this, you should look into getting a display, in which you can print out the time, as well as a short weather summary, or an icon to represent what the weather is!
Below are some links that you may find useful:
In this chapter, we got a brief introduction to the Internet of Things (IoT), a collective term for devices connected to the Internet.
We learned how to:
IoT is a very broad field and you have only just discovered a fraction of it. MicroPython makes it easier for you to build projects that are in sync with the world.