Outils pour utilisateurs

Outils du site


issue179:micro-ci_micro-la

This month, we will look at interfacing the LSM303DLHC Triple Axis Accelerometer and Magnetometer (Compass) breakout board to the Raspberry Pi Pico Microcontroller. There are many websites that talk about interfacing the board with an Arduino and a few that discuss how to interface it with the PyBoard, but very few discuss how to deal with the ESP32, ESP8622 or the Raspberry Pi Pico using Micropython. I found three different driver libraries that were supposed to be for Micropython and supposedly supported the three Microcontrollers that we focus on. After testing the three drivers, only one actually worked properly on any of the three boards and that one only worked on the RPi Pico. First, let’s talk about the wiring. Thankfully, this sensor breakout board supports I2C, so the hookup is pretty standard, as you can see from the breadboard drawing. I used the standard I2C bus 0, which uses GPIO pin 8 for SDA and GPIO pin 9 for SCL.

Ce mois-ci, nous allons nous intéresser à l'interfaçage de la carte LSM303DLHC Accéléromètre et Magnétomètre trois axes (Compas) à picots avec le microcontrôleur Raspberry Pi Pico. Il existe de nombreux sites Web qui traitent de l'interfaçage de la carte avec un Arduino et quelques-uns qui traitent de l'interfaçage avec la PyBoard, mais très peu parlent de la façon de traiter l'ESP32, l'ESP8622 ou le Raspberry Pi Pico à l'aide de Micropython.

J'ai trouvé trois différentes bibliothèques de pilotes qui étaient censées être pour Micropython et qui étaient censées supporter les trois microcontrôleurs sur lesquels nous nous concentrons. Après avoir testé les trois pilotes, seul un d'entre eux a fonctionné correctement sur l'une des trois cartes et ce dernier n'a fonctionné que sur le RPi Pico.

Tout d'abord, parlons du câblage. Heureusement, cette carte de capteur supporte I2C, car, ainsi, le branchement est assez standard, comme vous pouvez le voir sur le dessin de la plaque d'essai.

J'ai utilisé le bus I2C standard 0, qui utilise la broche GPIO 8 pour SDA et la broche GPIO 9 pour SCL.

Running the i2cscan program for the Pico, I verified that the addresses were 0x19 (for the accelerometer) and 0x1e (for the magnetometer), which matches the driver information. That driver library can be found at https://gitlab.iue.fh-kiel.de/hassan.karo/robotling-m3-labor/-/blob/feature/config_2020/robotling_lib/driver/lsm303.py but still requires a couple of changes to work correctly on the Pico. I will also provide the modified driver on my repository. You can find the address of the repository near the end of this article. We can’t move forward without the driver modifications, so let’s look at the changes. I won’t try to provide the full source code here. Copy the source file onto your Pico and use Thonny to modify it. The first thing that needs to be changed is one line in the import section (top right). I verified that nothing in the driver code calls the timed_function routine, so we can safely comment it out. Now we need to create a new blank file for our test program. Since we are going to concentrate on the compass feature of the LSM303, the program is pretty simple.

En exécutant le programme i2cscan pour le Pico, j'ai vérifié que les adresses étaient 0x19 (pour l'accéléromètre) et 0x1e (pour le magnétomètre), ce qui correspond aux informations du pilote.

Cette bibliothèque de pilotes peut être trouvée sur https://gitlab.iue.fh-kiel.de/hassan.karo/robotling-m3-labor/-/blob/feature/config_2020/robotling_lib/driver/lsm303.py mais nécessite néanmoins quelques modifications pour fonctionner correctement sur le Pico. Je vais également fournir le pilote modifié sur mon dépôt. Vous trouverez l'adresse du dépôt à la fin de cet article.

Nous ne pouvons pas avancer sans les modifications du pilote, alors regardons les changements. Je ne vais pas essayer de fournir le code source complet ici. Copiez le fichier source sur votre Pico et utilisez Thonny pour le modifier.

La première chose à modifier est une ligne dans la section d'importation (en haut à droite). J'ai vérifié que rien dans le code du pilote n'appelle la routine timed_function, nous pouvons donc la commenter en toute sécurité.

Nous devons maintenant créer un nouveau fichier vierge pour notre programme de test. Comme nous allons nous concentrer sur la fonction boussole du LSM303, le programme est assez simple.

The first thing, as you already know, is to set up the imports. We need to have access to the I2C functions. Since we are using the i2c bus 0, we don’t have to import the Pin functions, but I’m going to pull it in as well. We also need to import the LSM303 class from the library we just fixed up, as well as sleep from time, and the atan2 and pi functions from the math library. from machine import I2C,Pin from lsm303a import LSM303 from time import sleep from math import atan2,pi Next, we need to define the i2c object, instantiate the LSM303 class to the compass object, and define a variable for the “forever” loop that we will use to continuously poll the magnetometer. i2c=I2C(0) compass = LSM303(i2c) loop=True In our driver library is the function that returns a tuple providing the x, y and z axis.

La première chose, comme vous le savez déjà, est de mettre en place les importations. Nous devons avoir accès aux fonctions I2C. Puisque nous utilisons le bus i2c 0, nous n'avons pas besoin d'importer les fonctions Pin, mais je vais également les intégrer. Nous devons aussi importer la classe LSM303 de la bibliothèque que nous venons de créer, ainsi que sleep depuis time, et les fonctions atan2 et pi depuis la bibliothèque mathématique.

from machine import I2C,Pin from lsm303a import LSM303 from time import sleep from math import atan2,pi

Ensuite, nous devons définir l'objet i2c, instancier la classe LSM303 à l'objet compass et définir une variable pour la boucle « éternelle » que nous utiliserons pour interroger continuellement le magnétomètre.

i2c=I2C(0) compass = LSM303(i2c) loop=True

Dans la bibliothèque de notre pilote se trouve la fonction qui renvoie un tuple fournissant les axes x, y et z.

Here is what the function looks like (next page, top right). Thankfully, we don’t have to type this into our code. Anyway, back to the code of our test program. Now, we create our “forever” loop (bottom left) that polls the compass object to get our heading in relation to magnetic north. I’m going to borrow some of the text from the Adafruit website to explain what is going on in the code: In the absence of any strong local magnetic fields, the sensor readings should reflect the magnetic field of the earth (between 20 and 60 micro-Teslas). When the sensor is held level, by calculating the angle of the magnetic field with respect to the X and Y axis, the device can be used as a compass. To convert the microTesla readings into a 0-360 degree compass heading, we can use the atan2() function to compute the angle of the vector defined by the Y and X axis readings. The result will be in radians, so we multiply by 180 degrees and divide by Pi to convert that to degrees. After we have the value of where the sensor is pointing, the data coming back will be from -180 to +180. We need to normalize the value to be from 0 to 359. So we simply check to see if the value is less than 0 and if so we add 360 to the value and return that.

Voici à quoi ressemble la fonction (en haut à droite de la page suivante).

Heureusement, nous n'avons pas à taper cela dans notre code. Quoi qu'il en soit, revenons au code de notre programme de test.

Maintenant, nous créons notre boucle « éternelle » (en bas à gauche) qui interroge l'objet compass pour obtenir notre cap par rapport au nord magnétique.

Je vais emprunter une partie du texte du site Web d'Adafruit pour expliquer ce qui se passe dans le code : en l'absence de champs magnétiques locaux puissants, les relevés du capteur devraient refléter le champ magnétique de la terre (entre 20 et 60 micro-Teslas). Lorsque le capteur est maintenu à niveau, en calculant l'angle du champ magnétique par rapport aux axes X et Y, le dispositif peut être utilisé comme une boussole. Pour convertir les relevés microTesla en un cap de boussole de 0 à 360 degrés, nous pouvons utiliser la fonction atan2() pour calculer l'angle du vecteur défini par les relevés des axes Y et X. Le résultat sera exprimé en radians, nous le multiplions donc par 180 degrés et le divisons par Pi pour le convertir en degrés.

Une fois que nous avons la valeur de l'orientation du capteur, les données qui reviennent sont comprises entre -180 et +180. Nous devons normaliser la valeur pour qu'elle soit comprise entre 0 et 359. Nous vérifions donc simplement si la valeur est inférieure à 0 et si c'est le cas, nous ajoutons 360 à la valeur et nous la retournons.

Now when we run our program, we’ll get a value that shows our heading. My board has a small indicator silk-screened on it that shows the x, y and z axis. When the x axis aligns to north, the device returns 0. Save your file as lsm303aTest.py and run it. Move your breadboard around so that the x axis is pointing close to north and watch the values change and try to get the heading value to 0. I’ve put the code for our project on my repository at https://github.com/gregwa1953/FCM-179_MicroThisMicroThat . In a future article (hopefully next month), we’ll add a NeoPixel style RGB LED ring to our project to provide a visual indication that points to north – no matter what direction we are facing, emulating a real compass. Until next time, as always; stay safe, healthy, positive and creative!

Maintenant, lorsque nous lançons notre programme, nous obtenons une valeur qui indique notre cap. Ma carte a un petit indicateur sérigraphié sur elle qui montre les axes x, y et z. Lorsque l'axe x est aligné sur le nord, le dispositif renvoie 0.

Enregistrez votre fichier sous le nom de lsm303aTest.py et exécutez-le. Déplacez votre plaque d'essai de façon à ce que l'axe x pointe vers le nord et regardez les valeurs changer et essayez d'obtenir la valeur du cap à 0.

J'ai mis le code de notre projet sur mon dépôt à https://github.com/gregwa1953/FCM-179_MicroThisMicroThat .

Dans un prochain article (le mois prochain, j'espère), nous ajouterons un anneau de LED RVB de style NeoPixel à notre projet pour fournir une indication visuelle qui pointe vers le nord, quelle que soit la direction à laquelle nous sommes confrontés, émulant ainsi une vraie boussole.

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

Encadré de la p 35 en haut à droite, lignes noires :

Next, the RPi Pico Micropython port doesn’t include a method called deviceAddrList, so we need to replace that. However, the i2c.scan function already returns a list, so we can simply replace the line.

Ensuite, le portage du Micropython vers le RPi Pico n'inclut pas de méthode appelée deviceAddrList et nous devons donc la remplacer. Cependant, la fonction i2c.scan retourne déjà une liste ; aussi, nous pouvons simplement remplacer la ligne.

issue179/micro-ci_micro-la.txt · Dernière modification : 2022/04/01 16:53 de andre_domenech