Outils pour utilisateurs

Outils du site


issue175:micro-ci_micro-la

It’s November and I can’t believe we’ve already gone through eight MicroThis MicroThat articles. We’ve all come a long way in our understanding of microcontrollers and MicroPython. Back in part 4 (FCM#170), we covered a number of small parts of a large project using the ESP32. Due to a number of things, the article that I wanted to present didn't work out, so I will move a project from my “stuff to do” list. With any luck, I will be able to present it next month.

Nous sommes en novembre et je n'arrive pas à croire que nous ayons déjà pu lire huit articles de Micro-ci Micro-là. Nous avons tous parcouru un long chemin dans notre compréhension des microcontrôleurs et de MicroPython. Dans la partie 4 (FCM #170), nous avons couvert un certain nombre de petites parties d'un grand projet utilisant l'ESP32. En raison d'un certain nombre de choses, l'article que je voulais présenter n'a pas pu être réalisé ; je vais donc repositionner le projet dans ma liste des « choses à faire ». Avec un peu de chance, je pourrai le présenter le mois prochain.

A while ago, I had an idea about creating a number of standalone temperature sensors for each room in our apartment. The problem (like most apartments) is that the central heating and air conditioning thermostat is placed in an area that really bears no resemblance to the actual needs of the various rooms in the apartment. One room (the living area, where I spend 80% of my waking time) is ice cold all the time – at least to me. Summer or winter, it doesn’t matter. It’s ALWAYS cold. The farthest bedroom is always hot. Since we have decided that we will be moving to a house sooner than later, it would be helpful to have these standalone modules in each room of the house so we can glance at the display and see what the room temperature is at any time. The devices are built with the ESP8266, a DHT22 temperature/humidity sensor and a 128×32 SSD1306 display. The overall cost of a single unit is about $6.00 USD, since I bought all the parts in bulk a number of months ago. Eventually, each unit can have a code upgrade to enable it to talk to a MQTT server running somewhere in the house and have all the temperatures to display on a monitor. Now that you know the idea behind the project, you will recognize that we have already dealt with various parts of this project before. So, let’s jump right into the project.

*Il y a quelque temps, j'ai eu l'idée de créer un certain nombre de capteurs de température autonomes pour chaque pièce de notre appartement. Le problème (comme dans la plupart des appartements) est que le thermostat du chauffage central et de la climatisation est placé à un endroit qui ne correspond pas vraiment aux besoins réels des différentes pièces de l'appartement. Une pièce (le salon, où je passe 80 % de mon temps éveillé) est glacée en permanence, du moins pour moi. Que ce soit en été ou en hiver, ça ne change rien ; il fait TOUJOURS froid. La chambre la plus éloignée est toujours chaude. Puisque nous avons décidé de déménager dans une maison tôt ou tard, il serait utile d'avoir ces modules autonomes dans chaque pièce de la maison afin de pouvoir jeter un coup d'œil à l'écran et voir la température de la pièce à tout moment. Les appareils sont construits avec l'ESP8266, un capteur de température/humidité DHT22 et un écran 128 x 32 SSD1306. Le coût total d'une seule unité est d'environ 6 dollars américains, puisque j'ai acheté toutes les pièces en gros il y a quelques mois. À terme, chaque unité pourra avoir une mise à jour du code pour lui permettre de parler à un serveur MQTT fonctionnant quelque part dans la maison et avoir toutes les températures à afficher sur un moniteur. Maintenant que vous connaissez l'idée derrière le projet, vous reconnaîtrez que nous avons déjà traité diverses parties de ce projet auparavant. Donc, sautons directement dans le projet.

Here is the breadboard layout of the project. Please notice that I used a 128×64 SSD1306 in the diagram, but the code will work with the smaller display. Just be sure that you get the pinout for whichever OLED that you are using in your project to properly line with the wiring. Sometimes the pins are different from one manufacturer to another. Now we’ll look into the code. The main file will be named boot.py, and therefore every time the device is booted or reset, the program will start. This is what we want since we won’t be using a computer with Thonny to control it once we get ready to deploy it. Once we plug it in, the program should start running.

Voici le schéma de la plaque d'essai du projet. Veuillez noter que j'ai utilisé un SSD1306 128 x 64 dans le diagramme, mais le code fonctionnera avec un écran plus petit. Assurez-vous simplement que vous obtenez le brochage, quel que soit l'OLED que vous utilisez dans votre projet, pour l'aligner correctement avec le câblage. Parfois, les broches sont différentes d'un fabricant à l'autre.

Maintenant, nous allons nous pencher sur le code.

Le fichier principal sera nommé boot.py, et donc chaque fois que le dispositif est démarré ou réinitialisé, le programme démarrera. C'est ce que nous voulons puisque nous n'utiliserons pas d'ordinateur avec Thonny pour le contrôler une fois que nous serons prêts à le déployer. Une fois que nous l'aurons branché, le programme devrait commencer à fonctionner.

Here’s the import section… from machine import Pin from time import sleep import dht from ssd1306_setup import WIDTH, HEIGHT, setup from writer import Writer # import font10 import font6 You should have all of the support files from previous projects. The DHT library is part of the ESP8266 Micropython library. Just in case, I’ve included all the files that you need in the repository for this project. You’ll find the link at the end of this article. Next we have the setup section. Here, we set up the DHT temperature sensor and the OLED device. sensor = dht.DHT22(Pin(14)) ssd = setup(False, False) # wri = Writer(ssd, font10) wri = Writer(ssd, font6) Writer.set_textpos(ssd, 0, 0)

Voici la section d'importation :

from machine import Pin from time import sleep import dht from ssd1306_setup import WIDTH, HEIGHT, setup from writer import Writer # import font10 import font6

Vous devriez avoir tous les fichiers de support des projets précédents. La bibliothèque DHT fait partie de la bibliothèque Micropython ESP8266. Juste au cas où, j'ai inclus tous les fichiers dont vous avez besoin dans le dépôt de ce projet. Vous trouverez le lien à la fin de cet article.

Ensuite, nous avons la section de configuration. Ici, nous configurons le capteur de température DHT et le dispositif OLED.

sensor = dht.DHT22(Pin(14)) ssd = setup(False, False) # wri = Writer(ssd, font10) wri = Writer(ssd, font6) Writer.set_textpos(ssd, 0, 0)

Notice that I’ve commented out the use of the font10 file. I find that the font6 is clear enough to see from about 3-4 feet, which should be enough. Use whichever font file you find better for your application. Now we get to the main loop of the program (top right). We start a “forever” loop, use a try|except call (just in case the sensor fails to read), and use a sleep(2) statement to give the DHT22 a two-second delay before we query it. This is the minimum “safe” time, since the DHT22 is a little slower than some of the more expensive Temperature sensors. We then call the measure method to get the temperature and humidity values, and place them into temporary variables. As I’ve often said, my old brain can’t think in Celsius temperatures. I convert it to Farenheit and then send the values (both temperature and humidity) to the OLED display, and finally call the show method of the SSD library. We end with the ‘except’ portion of the code to try to recover politely.

Remarquez que j'ai commenté l'utilisation du fichier de la police 10. Je trouve que la police 6 est suffisamment claire pour être vue à 90 cm ou plus, ce qui devrait être suffisant. Utilisez le fichier de police qui vous semble le mieux adapté à votre application.

Nous arrivons maintenant à la boucle principale du programme (en haut à droite). Nous démarrons une boucle « éternelle », utilisons un appel try|except (juste au cas où le capteur n'arrive pas à lire), et utilisons une instruction sleep(2) pour donner au DHT22 un délai de deux secondes avant de l'interroger. Il s'agit du délai minimum « sûr », car le DHT22 est un peu plus lent que certains capteurs de température plus coûteux. Nous appelons ensuite la méthode measure pour obtenir les valeurs de température et d'humidité et nous les plaçons dans des variables temporaires. Comme je l'ai souvent dit, mon vieux cerveau ne peut pas penser en températures Celsius. Je les convertis en Farenheit, puis j'envoie les valeurs (température et humidité) à l'écran OLED, et enfin j'appelle la méthode show de la bibliothèque SSD. Nous terminons par la partie « except » (excepté) du code pour essayer de nous rétablir proprement.

That’s the entirety of the boot.py code. Now we’ll take a quick look at the ssd1306_setup.py file. You should remember that this is part of the writer library that Peter Hinch wrote. We used the writer library back in issue #172 (article part 6). As I usually do, I’ll start with the import and global setup sections. import machine from machine import Pin from ssd1306 import SSD1306_SPI, SSD1306_I2C WIDTH = const(128) HEIGHT = const(64) # HEIGHT = const(32)

C'est l'intégralité du code de boot.py. Maintenant nous allons jeter un coup d'œil rapide au fichier ssd1306_setup.py. Vous devez vous rappeler qu'il fait partie de la bibliothèque writer que Peter Hinch a écrite. Nous avons utilisé cette bibliothèque dans le numéro 172 (article partie 6). Comme je le fais habituellement, je vais commencer par les sections d'importation et de configuration globale.

import machine from machine import Pin from ssd1306 import SSD1306_SPI, SSD1306_I2C

WIDTH = const(128) HEIGHT = const(64) # HEIGHT = const(32)

You will want to make sure that the WIDTH and HEIGHT constants are the same for your display (see below). I commented out the last HEIGHT line, since I have both 128×64 and 128×32 SSD1306 displays around, and want to be able to swap quickly. Just so you know, if you are using a 128×64 SSD1306, you can still set the HEIGHT to 32. It shouldn’t matter having a larger display using a smaller HEIGHT value. It doesn’t work the other way around though. The original code was written for the Pyboard microcontroller, so I’ve removed that code from that shown below, but it still is in the repository file. Notice that I’ve commented out the original setup function definition and replaced the soft parameter set to False. This keeps us from using the software I2C library. I have done that, since we’re be forcing the I2C pins to SDA on pin 4 and SCL to pin 5. I’ve included the SPI code here, just to provide you a landmark for the code.

Vous devez vous assurer que les constantes WIDTH (largeur) et HEIGHT (hauteur) sont les mêmes pour votre écran (voir ci-dessous). J'ai commenté la dernière ligne HEIGHT, car j'ai à la fois des écrans SSD1306 128 x 64 et 128 x 32, et je veux être capable de les échanger rapidement. Pour votre information, si vous utilisez un SSD1306 128 x 64, vous pouvez toujours régler HEIGHT sur 32. Le fait d'avoir un écran plus grand en utilisant une valeur HEIGHT plus petite ne devrait pas avoir d'importance. Mais cela ne fonctionne pas dans l'autre sens. Le code original a été écrit pour le microcontrôleur Pyboard, donc j'ai enlevé ce code de celui montré ci-dessous, mais il est toujours dans le fichier du dépôt. Remarquez que j'ai commenté la définition de la fonction setup originale et remplacé la valeur du paramètre soft par False. Cela nous empêche d'utiliser la bibliothèque logiciel I2C. Je l'ai fait, puisque nous allons forcer les broches I2C à SDA sur la broche 4 et SCL sur la broche 5. J'ai inclus le code SPI ici, juste pour vous fournir un point de repère pour le code.

This is to make sure that we all use the same pin values for the I2C. You will probably get a depreciation warning (I’m not using the ESP8266 Micropython firmware 1.16 from 2021-06-18), and usually you can just ignore the warning for now. All the other code files are support files. You should have them from the previous projects, but I’ve included them in the github repository. You can find it at https://github.com/gregwa1953/FCM-175_MicroThisMicroThat. Ensure you place them all on your ESP8266 board. I’ve kept the article for this month fairly short, since my Python article ran so long. I want to make sure that the other authors have room for their good work. Until next time, as always; stay safe, healthy, positive and creative!

C'est pour s'assurer que nous utilisons tous les mêmes valeurs de broches pour l'I2C. Vous obtiendrez probablement un avertissement de dépréciation (je n'utilise pas le firmware ESP8266 Micropython 1.16 du 2021-06-18), et vous pouvez généralement ignorer cet avertissement pour le moment.

Tous les autres fichiers de code sont des fichiers de support. Vous devriez les avoir dans les projets précédents, mais je les ai inclus dans le dépôt github. Vous pouvez le trouver à https://github.com/gregwa1953/FCM-175_MicroThisMicroThat. Assurez-vous de les placer tous sur votre carte ESP8266.

J'ai gardé assez court l'article de ce mois-ci, puisque mon article sur Python était si long. Je veux m'assurer que les autres auteurs ont de la place pour leur bon travail.

Jusqu'à la prochaine fois, comme toujours, restez en sécurité, en bonne santé, positif et créatif !

issue175/micro-ci_micro-la.txt · Dernière modification : 2021/12/03 18:27 de andre_domenech