The HTU21 can measure temperature and humidity. For the air pressure, for example, we would also need a BMP280, or a BME280 for everything together. Of course, this raises the question of what the correct term should be: Let me measure or let me be measured? In this case, both are wrong, because today it is correct to say: let others measure.
These "others" operate a website with the URL openweathermap.org. From there you can get weather data from all over the world. The only requirement is a free registration. Then you get a 32-character key. This is used to feed the queries, which must also contain the location, the country code and the language. How this all works and what role the mammoth matrix display plays in this, you will learn in this blog post from the series
MicroPython on the ESP32 and ESP8266
The mammoth matrix display as weather ticker
You can find out more about the Mammut-Matrix-Display itself and the associated controller in the first part of this series. There you will find the schematic and a description of how the display works. Furthermore a MicroPython module for controlling the display was developed, which can and will be used in further projects, for example here.
In the second part was about the temperature and humidity sensor HTU21 alias SHT21. For its control also a MicroPython module was built. In addition, you will learn more about the operation of the I2C bus and it is shown how to make the bus signals visible with inexpensive means. The used 8-channel Logicanalyzer is perfectly suitable for this. Furthermore there is information about the CRC checksum calculation.
The radio transmission of the data to the display was the subject of the third part. The connection was made via WLAN, either via the access point of the router, or via the access point of the ESP32, which also controls the display. In addition, you can read here how to clone pixel character sets from Windows TTF character sets for OLED displays and of course also for mammoth matrix displays.
As for hardware, I only use an ESP32(S) and the matrix display in this episode. Of course, an HTU21 can also provide the in-house climate data in addition.
The texts to be displayed are all much longer than 16 characters, therefore the method roll() is used. The display should consist of at least 8 to 12 elements because of readability.
Weather ticker - 182 x 8 - matrix
according to demand
Plywood strips 5x 25cm ... for display mounting
The circuit is very simple and therefore well suited for beginners. The schematic shows an optional HTU21 alias SHT21. You will learn everything you need to know about its usage in the 2nd part .
Illustration 1: SHT21-Thermo+Hydrometer with ESP32
As 5V supply for several 8x8 elements a power supply with sufficient current reserves should be used. For this I use a module with step-down converter, which can supply up to 2A (3A for a short time). With variable input voltage from 6 to about 20V the output is set to 5V with the trim pot.
Illustration 2: Power supply with buck converter on my carrier board.
For the development of projects I designed a base board for this purpose, provided it with a tube socket at the input and a USB-A socket at the output and mounted the whole thing on a plexiglass base plate.
An account at Open Weather
For an account at Open Weather go to their website How to Start.
Illustration 3: How to start
Click on here (red arrow) and enter your data in the form below.
Illustration 4: Create new account
Declare that you are not a robot and submit the registration.
Illustration 5: Create account
You want to know what you want to use Open Weather for. If you do not want to commit, select other. To finish click Save.
Illustration 6: How to use
After that there is a welcome message. email@example.com is a fake address. Requests to this mail account will certainly not be answered. If you want to acknowledge the confirmation link, you should of course have entered your mail address.
Illustration 7: Confirmation mail
A click on API keys will show you your APPID. Copy it to a safe place and have the code ready, we will need it shortly.
Illustration 8: Copy and save API key
For flashing and programming the ESP32:
Used firmware for the ESP32:
Please choose a stable version
ESP32 with 4MB Version 1.18 Status 03/25/2022
The MicroPython programs for the project:
matrix8x8.py Driver module for the MAX7219
possibly sht21.py Driver module for the GY-21 module
Possibly shtdisplay.py Thermo- Hygrometer Software with Writer
possibly shtdisplay+.py Thermo- Hygrometer Software with Writer
writer.py The driver for the display with the new character sets.
ocr8.py narrow character set
openweathermap.py Service software for the blog
MicroPython - Language - Modules and programs
MicroPython is an interpreter language. The main difference to the Arduino IDE, where you always and only flash whole programs, is that you only need to flash the MicroPython firmware once at the beginning to the ESP32, so that the controller understands MicroPython instructions. You can use Thonny, µPyCraft or esptool.py to do this. For Thonny, I have described the process here .
Once the firmware is flashed, you can casually talk to your controller one-on-one, test individual commands, and immediately see the response without having to compile and transfer an entire program first. In fact, that's what bothers me about the Arduino IDE. You simply save an enormous amount of time if you can do simple tests of the syntax and the hardware up to trying out and refining functions and whole program parts via the command line in advance before you knit a program out of it. For this purpose I also like to create small test programs from time to time. As a kind of macro they summarize recurring commands. From such program fragments sometimes whole applications are developed.
If you want the program to start autonomously when the controller is switched on, copy the program text into a newly created blank file. Save this file as boot.py in the workspace and upload it to the ESP chip. The program will start automatically at the next reset or power-on.
Manually, programs are started from the current editor window in the Thonny IDE via the F5 key. This is quicker than clicking on the Start button, or via the menu Run. Only the modules used in the program must be in the flash of the ESP32.
In between times Arduino IDE again?
If you want to use the controller together with the Arduino IDE again later, simply flash the program in the usual way. However, the ESP32/ESP8266 will then have forgotten that it ever spoke MicroPython. Conversely, any Espressif chip that contains a compiled program from the Arduino IDE or the AT firmware or LUA or ... can easily be flashed with the MicroPython firmware. The process is always like here described.
The connection to Open Weather
Before we start with the program, let's test the connection to Open Weather. Do you have your APPID handy? Yes, then please start a browser, if not already running, and enter the following URL. Before sending the request, you have to replace the xxxxx.. with your APPID.
And off you go. The result should look something like this if you have selected the JSON tab.
Illustration 9: Weather Berlin
If you click on raw data it looks like this.
Illustration 10: Raw data
We now use the clear JSON notation in the browser to prepare the data from Open Weather's response for our display. By the way, more information about the individual fields can be found at this URL:
We start in the program with various imports. Program lines, which refer to the HTU21 I comment out. Import lines, which refer specifically to the project, I have formatted bold.
Imports for network connection and working with server connections follow.
The class network contains the methods for connecting to the local network, socket provides methods for the TCP connection to the Open Weather Server. With requests we establish the connection and receive the response. json provides methods for conveniently parsing the response, as we saw above. Without this module, we would have to write our own parser, which would be far more costly.
The following four lines are self-explanatory. Of course you have to enter your own credentials here and adapt the IP address for the ESP32 to your network infrastructure.
I explain the flash button of the ESP32 module as an emergency brake. I use it, if nothing else helps to get out of the mainloop, especially if the program in the production system is called as boot.py runs autonomously. How this works with autostart is explained in the Software chapter.
We define a location name, a country code and set the APPID. For the x-e please put again your APPID. The list of wind directions helps us to output the direction instead of degrees, using the direction acronyms. And it is enough if we start a query to the server every 5 minutes.
Then we determine the type of the used controller and after that we set the GPIO pins for the SPI bus, which we need for output to the display.
I tell the program that I am using 16 display elements and with the SPI bus object, the GPIO pin for the chip select line and the number of units I instantiate the mammoth matrix display object d. The Writer object w is used to display your own character sets. How these are derived from Windows character sets and used is described in part 3 of this series.
We define two functions. hexMac() takes the byte sequence from nic.config('mac') and makes it a normal string for the return. This information is needed to enable access for our client station in the router. Please consult the manual of your WLAN router for this setting.
TimeOut() is a function that defines another function in its function body. This function compare() uses the value of the pass parameter t and the variable startwhich is declared outside compare() but used inside the function. TimeOut() returns a reference to compare(), not a value. compare() is a so-called closure and this has the advantage that variables keep their value between the calls to compare(), while local variables are normally killed when the function exits. I like to use the closure as a non-blocking software timer.
The connectStatus dictionary allows the output of the WLAN connection status in plain text.
The AP interface is not needed, so we turn it off as a precaution before it gets into mischief. This happens from time to time.
The Station Interface is instantiated and disabled first. Then we get the MAC and output it.
Now the STA interface is activated, we set a static IP address. This simultaneously disables the DHCP client, which would obtain the IP address from the WLAN router. For a client, a static IP is not absolutely necessary, but it makes troubleshooting easier if something is not running as desired.
Further up you have your Credentials are specified with which a connection to the router is now to be established.
Normally there is no connection to the access point yet. But we are cautious people and therefore we query the state first after the run index n has been initialized with 1.
So normally we end up in the while-loop, which is run until the connection is established. As long as this is not the case, one more point is sent to the display every second. Usually 2 to 3 points are used. If there are more than ten dots, you can assume that there is a problem. The connection status is displayed as a number in the terminal. The Dict connectStatus tells you the cause.
You can also use the run index to abort the contact attempt to this router after a certain time and either display the error message in plain text, or try to connect to an alternative access point.
I follow the first approach.
Then the socket object s is instantiated. The parameters socket.SOCK_STREAM and socket.AF_INET build a TCP interface based on the IPv4 address-family. When calling the method setsockopt() method, the parameter socket.SO_REUSEADDR ensures that the same socket data, IP address and port number, can be reused after a restart without a reset without causing an error.
The method bind() binds the port number in myPort to the IP address set in the WLAN part. Finally, the timeout of 5 ms ensures that the receive loop of the socket does not block the flow of the main loop. If this were the case, then for example the roll() command could not be executed in the foreground. Sending messages to the Open Weather server and receiving them from it are therefore rather secondary matters and are governed by the timer mentioned above. We will come to that in a moment.
The next three lines set the URL for the API of the Open Weather Server, send the request, get the response at the same time and start the timer for the next such event.
At this point, a note on the location specification is appropriate. In the sample code, one of the postal codes of Regensburg is used, zip=93047. Alternatively, the city name can be used for larger cities. For Nuremberg, the same place would be: q=Nuremberg. You can test this out if you use the content of owmurl in the terminal and enter the string as URL in the browser. Instead of the x-e there should be your APPID.
Sending the request to the server and receiving its response is all very compact in this line.
requests.get() returns a reponse object containing some data fields and the method json() method, which we will use for parsing in a moment.
Illustration 11: Inner workings of the response object
I'm just finishing up the timer, then it's off to the main loop. measure contains a reference to the function compare() inside TimeOut(). measure can therefore be called as a function. With the call of measure() I actually call compare(). The closure compare() returns True if the timer has expired. Then we start a new request and restart the timer.
Because we are curious, we will print the text of the response object.
The order in decoding the JSON code is arbitrary and only based on the name of the pairs. Thus, the pair name: "Regensburg" is found at the very bottom of the row. weather_data.json().get('name') returns the value "Regensburg".
Some of the pairs are indented, for example at the name sys (Illustration 6). If we look at the raw text, we see that a whole dict is assigned to the name sys.
To access the country identifier DE, a staged query is required.
The query for the weather description is particularly interesting. The name weather is assigned a list (square brackets) whose zeroth element we must address in order to access main and description.
The composite text is output at the terminal and sent to the matrix display with the command roll() command.
In the dict main contains the data for temperature, relative humidity and air pressure. These are also to be queried in two stages. The temperatures in Kelvin must be converted into Celsius values. The degree range for the Kelvin scale is the same as for Celsius, only 273.15 has to be subtracted.
The format strings for the output of the temperature values are interesting. Since no names are used for formatting, the automatic assignment applies according to the order of the parameters. The output is a floating point number (f) with at least 5 characters width and one digit after the decimal point. The situation is similar for air pressure and relative humidity.
For wind, direction and speed are interesting. The speed is converted into km/h as an integer. The direction comes in degrees from 0° (north) over 90° (east), 180° (south) and 270° (west). The index into the list defined at the beginning wr is calculated on the basis of a 22.5° grid.
Furthermore, a warning for gusts (gust) of more than 40km/h is useful. This is done by a centered flashing message at the end of the while block, if the gust speed exceeds 40km/h.
The key query completes the while loop.
Depending on which API is used by Open Weather, other services can be used if they are included in the Free Plan, i.e. free, no-cost access. Scroll down the page https://openweathermap.org/api follow the links, feel free to experiment a bit here. For example, this would be a request for a 7-day forecast.
Enter the line along with your APPID in the browser and look at the output in the JSON folder first before you get to picking apart the message. The request uses the one-call API. The location information here is in latitude and longitude. If you don't know the values for your location, just ask Google maps.
Illustration 12: Location coordinates latitude and longitude
In the list daily the days are numbered from 0 (today) to 7 (in a week). Warning messages are in the list alerts. Help pages are available for each API, describing the various parameters of the call and the fields in the response string. For the One-Call API, this is the page: https://openweathermap.org/api/one-call-api.
All requests also return different times, current time, sunrise, sunset... The Unix time stamps give the number of seconds since 01/01/1970 0:0:0,0. But the time epoch of MicroPython on the ESP32 ports starts only on 01.01.2000. To get the correct time-date-combination it needs two corrections, 946681200 has to be subtracted and during daylight saving time 3600 has to be added. Then can be calculated with time.localtime() the correct time can be output.
This could then look like this with the last specified request.
With this you are well equipped for all eventualities and you can use the services of Open Weather intensively. I wish you much success and pleasure!