Outils pour utilisateurs

Outils du site


issue176:micro

First, I want to wish all our readers a very happy holiday season. No matter what you wish to celebrate, please do so safely! Yes, we are going to talk about more graphics for our MicroController projects. Yet again, we will be using the SSD-1306 for the display, and, for the microcontroller this time, we’ll go back to our ESP-32 generic. Now, the reason for this article is to take “standard” graphics and convert them into something that can be displayed on a 2-color (black and white) SSD-1306 OLED display. It is not as straightforward as one would expect. We’ll need to use GIMP or PhotoShop to do the conversion which is not terribly difficult, but there are some steps involved that you will need to pretty much follow in the order as presented to accomplish this very important step. We’ll also need to use the mpfshell utility we discussed back in FCM#174 (part 8 of the Micro This Micro That series) to transfer the image files to the microcontroller. The version we used then was 0.9.2.

Tout d'abord, je tiens à souhaiter à tous nos lecteurs de très bonnes fêtes de fin d'année. Peu importe ce que vous souhaitez célébrer, faites-le en toute sécurité !

Oui, nous allons parler encore d'affichages pour nos projets de microcontrôleurs. Une fois de plus, nous utiliserons le SSD-1306 pour l'écran et, pour le microcontrôleur, nous reviendrons cette fois à notre ESP-32 générique.

La raison de cet article est de prendre des fonctions graphiques « standards » et de les convertir en quelque chose qui peut être affiché sur un écran OLED SSD-1306 bicolore (noir et blanc). Ce n'est pas aussi simple qu'on pourrait le croire. Nous devrons utiliser GIMP ou PhotoShop pour effectuer la conversion, ce qui n'est pas très difficile, mais il y a quelques étapes à suivre, dans l'ordre présenté, pour accomplir cette étape très importante. Nous devrons également utiliser l'utilitaire mpfshell dont nous avons parlé dans le FCM n°174 (partie 8 de la série Micro-ci Micro_là) pour transférer les fichiers images vers le microcontrôleur. La version utilisée à l'époque était la 0.9.2.

Before we actually get started, I need to thank Martin Fitzpatrick for the wonderful writeup on using PBM files and the micropython code to support it. His website is https://www.mfitzp.com/tutorials/displaying-images-oled-displays/ . The first thing that we need to have is some image files. I’m going to use weather icons that I found at https://iconstore.co/icons/rns-weather-icons/. The download file contains monochrome images in many formats. For ease of use, I decided to use the images in the PNG folder. The 70 images are monochrome PNG files that are sized 96×96 pixels. The next step is to convert the images we wish into PBM format. We’ll use GIMP to accomplish that. Open GIMP and load the image you want. We’ll use the weather_icon-47.png file for this tutorial. Since the image is 96×96 pixels, and our display is at best 128×64, we’ll want to pick something slightly smaller. Let’s pick 50×50. Select Image | Scale Image from the menu bar.

Avant de commencer, je dois remercier Martin Fitzpatrick pour son excellent article sur l'utilisation des fichiers PBM et le code micropython qui les prend en charge. Son site web est https://www.mfitzp.com/tutorials/displaying-images-oled-displays/ .

La première chose dont nous avons besoin, ce sont des fichiers images. Je vais utiliser les icônes météo que j'ai trouvées sur https://iconstore.co/icons/rns-weather-icons/. Le fichier à télécharger contient des images monochromes dans de nombreux formats. Pour en faciliter l'utilisation, j'ai décidé d'utiliser les images du dossier PNG. Les 70 images sont des fichiers PNG monochromes d'une taille de 96×96 pixels.

L'étape suivante consiste à convertir les images choisies au format PBM. Pour ce faire, nous allons utiliser GIMP. Ouvrez GIMP et chargez l'image que vous voulez. Nous allons utiliser le fichier weather_icon-47.png pour ce tutoriel.

Comme l'image fait 96×96 pixels, et que notre écran fait au mieux 128×64, nous devrons choisir quelque chose de légèrement plus petit. Choisissons 50×50. Sélectionnez Image > Échelle et taille de l'image dans la barre de menu.

Highlight the Width value and change it to 50. Then simply press the {Tab} key to automatically set the Height value. Click on the Scale button to make the change. Now we want to invert the image so the black pixels become white. Select Colors | Invert from the menu bar. Now we need to convert the image to a 1-bit-per-pixel image. To do this, select Image | Mode | Indexed from the menu bar. You’ll see a dialog pop up that looks something like this. Make sure you have Use black and white (1-bit) palette selected and Remove unused and duplicate colors from colormap selected as well. Select Floyd-Steinberg (Reduced color bleeding) in the Color dithering dropdown, then click on the Convert button. Finally, we need to export it to our .pbm file format. Select File | Export As… from the menu bar, then, in the dialog, change the extension from .png to .pbm and then click the Export button. Another dialog pops up asking the Data formatting type. You want to make sure that Raw is selected then click the Export button.

Mettez en surbrillance la valeur de la Largeur et changez-la en 50. Ensuite, il suffit d'appuyer sur la touche {Tab} pour définir automatiquement la valeur Hauteur. Cliquez sur le bouton Mise à l'échelle pour effectuer la modification.

Nous voulons maintenant inverser l'image pour que les pixels noirs deviennent blancs. Sélectionnez Couleurs > Inverser dans la barre de menus. Nous devons maintenant convertir l'image en une image de 1 bit par pixel. Pour ce faire, sélectionnez Image > Mode > Couleurs indexées dans la barre de menus. Vous verrez apparaître une boîte de dialogue qui ressemble à celle-ci.

Assurez-vous que vous avez sélectionné « Utiliser la palette noir et blanc (1 bit) » et « Supprimer les couleurs inutilisées et en double de la carte des couleurs ». Sélectionnez Floyd-Steinberg (Couleurs qui déteignent le moins) dans la liste déroulante Tramage des couleurs, puis cliquez sur le bouton Convertir.

Enfin, nous devons exporter l'image vers notre format de fichier .pbm. Sélectionnez Fichier > Exporter sous… dans la barre de menu, puis, dans la boîte de dialogue, changez l'extension .png en .pbm et cliquez sur le bouton Exporter. Une autre boîte de dialogue apparaît pour demander le type de formatage des données. Assurez-vous que l'option Raw est sélectionnée, puis cliquez sur le bouton Exporter.

Your image should now look like this. That’s it for that part. It wasn’t too very painful – detailed, but not painful. Now we want to upload this image to our microcontroller. Again, I use mpfshell to do this (please see my note near the bottom of the article on using mpfshell). Next, we’ll look at our code to display it on the OLED display. We’ll name our file graphx32.py since we are using it on an ESP-32 generic microcontroller. As always, we need to import some libraries. We need the ssd1306 and framebuf libraries, as well as the SoftI2C and Pin libraries from the machine library. Next we need to define the display object for the display (top right). Now we will open the icon image file and do three readline calls. This gets the Magic Number, the Creator comment, and the dimension of the image from the image file header (we’ll talk about these in a moment), and finally the data of the image itself (middle right).

Votre image devrait maintenant ressembler à ceci :

C'est tout pour cette partie. Ce n'était pas trop pénible - détaillé, mais pas douloureux. Maintenant, nous voulons télécharger cette image sur notre microcontrôleur. Encore une fois, j'utilise mpfshell pour le faire (allez voir ma note vers le bas de l'article sur l'utilisation de mpfshell). Ensuite, nous allons regarder notre code pour l'afficher sur l'écran OLED. Nous nommerons notre fichier graphx32.py, car nous l'utilisons sur un microcontrôleur générique ESP-32.

Comme toujours, nous devons importer certaines bibliothèques. Nous avons besoin des bibliothèques ssd1306 et framebuf, ainsi que des bibliothèques SoftI2C et Pin de la bibliothèque machine. Ensuite, nous devons définir l'objet display pour l'affichage (en haut à droite).

Maintenant, nous allons ouvrir le fichier image de l'icône et faire trois appels readline. Cela permet d'obtenir le nombre magique, le commentaire du créateur et la dimension de l'image à partir de l'en-tête du fichier image (nous en parlerons dans un moment), et enfin les données de l'image elle-même (au milieu à droite).

The last things we need to do are load the image data (without the header information) into the framebuffer, fill the display with black, blit the data to our desired position, and call the display show method. The 50,50 in the first line of the next section refers to the size of the image. If it is not 50×50, set it to the correct size (bottom right). The P4 is the identifier that the file is actually a PBM file. (There is another PBM format that uses a P1, which denotes a “Plain PBM” file). The second line as you can see is a comment that states that the file was created by GIMP. Finally you can see that the image dimensions are, as we expected, 50 x 50 pixels. This information will be important if you don’t remember what the size of the image file will be. When you run the program, your display should look like this. Using this method is (in my mind) much better than converting images to a bytearray. It takes a few more lines of code to use the PBM file method, but I find it much easier to work with.

Les dernières choses que nous devons faire sont de charger les données de l'image (sans les informations d'en-tête) dans framebuffer, de remplir l'écran avec du noir, de « bliter » (par doublement du Framebuffer) les données à la position souhaitée et d'appeler la méthode show de l'écran. Le 50,50 de la première ligne de la section suivante fait référence à la taille de l'image. Si elle n'est pas 50×50, définissez-la à la taille correcte (en bas à droite).

P4 est l'identifiant qui assure que le fichier est bien un fichier PBM. (Il existe un autre format PBM qui utilise P1, qui indique un fichier « Plain PBM »). La deuxième ligne, comme vous pouvez le voir, est un commentaire qui indique que le fichier a été créé par GIMP. Enfin, vous pouvez voir que les dimensions de l'image sont, comme nous nous y attendions, de 50 x 50 pixels. Cette information sera importante si vous ne vous souvenez pas de la taille du fichier image.

Lorsque vous exécutez le programme, votre affichage devrait ressembler à ceci :

L'utilisation de cette méthode est (à mon avis) bien meilleure que la conversion des images en bytearray. L'utilisation de la méthode du fichier PBM nécessite quelques lignes de code supplémentaires, mais je la trouve beaucoup plus facile à utiliser.

You might not want to have to deal with GIMP everytime you want to convert a PNG file to PBM. Based on the steps we followed using GIMP to convert the file, I threw together a quick and VERY dirty Python program to do the conversion. We’ll use weather_icon-49.png for this part of the project. Name your file ConvertSingle.py . When you run the program, it should just take a moment to finish and you’ll have a nice 32 x 32 PBM format image. There is a small problem with the file we created using the PIL library. There doesn’t seem to be a way to set the Creator Comment in the header of the image file. Therefore, we need to make a small change to our micropython file to handle the lack of the comment. We need to change the with open code to the following (bottom left)…

Vous n'avez peut-être pas envie d'avoir affaire à GIMP chaque fois que vous voulez convertir un fichier PNG en PBM.

En me basant sur les étapes que nous avons suivies avec GIMP pour convertir le fichier, j'ai créé un programme Python rapide et TRÈS sale pour effectuer la conversion. Nous allons utiliser weather_icon-49.png pour cette partie du projet. Nommez votre fichier ConvertSingle.py .

Lorsque vous exécutez le programme, il ne devrait prendre qu'un instant pour se terminer et vous aurez une belle image de 32 x 32 au format PBM.

Il y a un petit problème avec le fichier que nous avons créé en utilisant la bibliothèque PIL. Il ne semble pas y avoir de moyen de définir le commentaire du créateur dans l'en-tête du fichier image. Par conséquent, nous devons apporter une petite modification à notre fichier micropython pour gérer l'absence de commentaire. Nous devons changer le code « with open » par le suivant (en bas à gauche).

Since the header comment (according to the specs that I can find) always starts with a #, we can simply check the value of the second line read to see if it starts with the pound symbol (or hash sign for all you social media users). If so, then we simply read the next line. If it doesn’t, we don’t want to try to read another line. There will only be two lines in the header, not three. If we try to read three and the comment doesn’t exist, the data portion of the file will be short and thereby corrupt. By using the scheme above, it will handle both cases properly. Since the new image is only 32×32, be sure to change the line that loads the data into the frame buffer to… fbuf = framebuf.FrameBuffer(data, 32, 32, framebuf.MONO_HLSB) You can see from the image below, that the image created by our Python program works just fine. I’ve placed all the code for this month’s article, along with a couple of sample images, on my github repository at https://github.com/gregwa1953/FCM176_MicroThisMicroThat. To run the above code on the RPi Pico, I had to make a very few changes – you can find the code file in the zipped repository as graphxPico.py. I hope that you and your family and friends have a happy and safe holiday season.

Puisque le commentaire d'en-tête (selon les spécifications que j'ai pu trouver) commence toujours par un #, nous pouvons simplement vérifier la valeur de la deuxième ligne lue pour voir si elle commence par le symbole dièse. Si c'est le cas, nous lisons simplement la ligne suivante. Si ce n'est pas le cas, il ne faut pas essayer de lire une autre ligne. Il n'y aura que deux lignes dans l'en-tête, pas trois. Si nous essayons d'en lire trois et que le commentaire n'existe pas, la partie données du fichier sera courte et donc corrompue. En utilisant le schéma ci-dessus, les deux cas seront traités correctement.

Puisque la nouvelle image ne fait que 32×32, assurez-vous de changer la ligne qui charge les données dans framebuffer en :

fbuf = framebuf.FrameBuffer(data, 32, 32, framebuf.MONO_HLSB)

Vous pouvez voir sur l'image ci-dessous, que l'image créée par notre programme Python fonctionne très bien.

J'ai placé tout le code de l'article de ce mois-ci, ainsi que quelques exemples d'images, sur mon dépôt github à https://github.com/gregwa1953/FCM176_MicroThisMicroThat.

Pour faire fonctionner le code ci-dessus sur le RPi Pico, j'ai dû faire très peu de changements, vous pouvez trouver le fichier de code dans le dépôt zippé sous le nom de graphxPico.py.

J'espère que vous, votre famille et vos amis passerez de bonnes fêtes de fin d'année.

Encart p. 35, texte en noir

I mentioned the Magic number, the Creator comment, and the Dimensions in the header. Here is what gets printed in the Thonny REPL when the program runs.

J'ai mentionné le nombre magique, le commentaire du créateur et les dimensions dans l'en-tête. Voici ce qui s'affiche dans le REPL de Thonny lorsque le programme s'exécute.

Encart p. 37

NOTE ON USING MPFSHELL When I was developing the project for this month, I was using mpfshell version 0.9.2 running under Python 3.7.4. This is also true for my environment when I wrote the article about using mpfshell in FCM #174. However, this month, I tried to use mpfshell under Python 3.8.11 and it wouldn’t connect to the ESP32 microcontroller. I was in a rush to get the article written so I just continued using Python 3.7.4 with no problems. When I passed an early version of the article and source code to my friend Halvard in Norway, he had issues with mpfshell using a more recent version of Python. I did some research on the mpfshell github repository and found that others were having problems on various versions of Linux using 0.9.2 under Python 3.8 and up, but mpfshell 0.9.1 seemed to work fine for them. I spent a couple of hours testing in virtual environments using mpfshell 0.9.1 under Python versions 3.7.4, 3.8.10, 3.9.5 and 3.10.0 (thanks to pyenv), and everything worked well and was able to connect to not only ESP8266 (the only officially supported microcontroller) but also ESP32 and RPi Pico. So, if you are having issues connecting to your microcontroller using mpfshell, you can use pip (or pip3) to uninstall mpfshell then install mpfshell version 0.9.1. It works just fine. The only thing that needs to change is the open command to connect via serial to the microcontroller. Instead of using “open /dev/ttyUSB0” (or whatever serial port you need to use), use “open ttyUSB0” (or your proper serial port) to connect. Hey, it saves a few keystrokes, right? Both ESP8266 and ESP32 all connect on my machine as /dev/ttyUSB0 and the RPi Pico connects as /dev/ttyACM0. Until next time, as always; stay safe, healthy, positive and creative!

NOTE SUR L'UTILISATION DE MPFSHELL

Lorsque j'ai développé le projet de ce mois-ci, j'ai utilisé la version 0.9.2 de mpfshell sous Python 3.7.4. Ceci est également vrai pour mon environnement lorsque j'ai écrit l'article sur l'utilisation de mpfshell dans le FCM n° 174. Cependant, ce mois-ci, j'ai essayé d'utiliser mpfshell sous Python 3.8.11 et il ne voulait pas se connecter au microcontrôleur ESP32. Comme j'étais pressé de rédiger l'article, j'ai continué à utiliser Python 3.7.4 sans problème. Lorsque j'ai transmis une première version de l'article et du code source à mon ami Halvard en Norvège, il a rencontré des problèmes avec mpfshell en utilisant une version plus récente de Python. J'ai fait quelques recherches sur le dépôt github de mpfshell et j'ai trouvé que d'autres personnes avaient des problèmes sur diverses versions de Linux en utilisant la version 0.9.2 sous Python 3.8 et plus, mais mpfshell 0.9.1 semblait bien fonctionner pour eux. J'ai passé quelques heures à faire des tests dans des environnements virtuels en utilisant mpfshell 0.9.1 sous les versions 3.7.4, 3.8.10, 3.9.5 et 3.10.0 de Python (grâce à pyenv), et tout a bien fonctionné. J'ai pu me connecter non seulement à l'ESP8266 (le seul microcontrôleur officiellement supporté) mais aussi à l'ESP32 et au RPi Pico. Donc, si vous avez des problèmes pour vous connecter à votre microcontrôleur en utilisant mpfshell, vous pouvez utiliser pip (ou pip3) pour désinstaller mpfshell puis installer mpfshell version 0.9.1. Cela fonctionne tout à fait bien. La seule chose à changer est la commande open pour se connecter au microcontrôleur via la liaison série.

Au lieu d'utiliser « open /dev/ttyUSB0 » (ou n'importe quel port série que vous utiliseriez), utilisez « open ttyUSB0 » (ou votre port série approprié) pour vous connecter. Cela permet d'économiser quelques frappes au clavier, non ? L'ESP8266 et l'ESP32 se connectent tous deux sur ma machine sous /dev/ttyUSB0 et la RPi Pico se connecte sous /dev/ttyACM0.

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

issue176/micro.txt · Dernière modification : 2022/01/07 16:25 de andre_domenech