Outils pour utilisateurs

Outils du site


issue106:python

Welcome back to the crazy world of Python Programming in the real world. Before we get started, I need to make a confession. Last time I goofed. The images in part 63 are wrong. The LEDs are backwards from what they should be. Brian Kelly noted this and was brave enough to point out the old man’s errors. Thank you Brian. If you follow the text, you should be good to go. Secondly, I have to apologize for not making it last month (FCM#106). I’m having more medical issues that are keeping me from sitting for too long. Hopefully this will be taken care of soon. Enough of that. Now for this month’s offering. The Mystery LED In the last two articles, we learned how to turn on and off LEDs programmatically. That was simple enough. This is digital output as opposed to analog output. The RPi, unlike the Arduino, cannot do analog I/O. So we are limited to turning a GPIO pin (and in this case, a LED) either on or off. This time we will be using that knowledge to do something pretty interesting. So get your Pi and your breadboard and we’ll start working.

Bon retour dans le monde assez fou de Python Programming, dans la vraie vie. Avant de commencer, je dois vous avouer quelque chose. La dernière fois, j'ai fait une grosse faute : les images dans la partie 63 sont erronées. Les LED sont à l'inverse de ce qu'ils devraient être. Brian Kelly l'a remarqué et a été assez courageux pour signaler les erreurs du vieillard que je suis. Merci, Brian. Si vous suivez le texte, cela devrait aller.

Ensuite, je dois vous présenter des excuses, car je n'ai pas pu faire mon article le mois dernier (dans le FCM n° 106). J'ai encore des problèmes de santé qui m'empêchent de rester assis pendant longtemps. En principe, cela devrait être corrigé bientôt.

Bon, ça suffit. Maintenant voyons ce que je vous propose ce mois-ci.

Le LED mystère

Dans les deux derniers articles, vous avez appris à allumer et à éteindre des LED avec un programme. C'était assez simple. Il s'agit de sortie numérique et non pas analogique. Le Rpi, contrairement à l'Arduino, ne supporte pas d'entrée/sortie analogique, et nous sommes limités à n'utiliser une sortie du GPIO (et une LED dans ce cas) que dans l'état allumé ou éteint. Cette fois-ci, nous allons utiliser nos connaissances pour faire quelque chose de très intéressant.

Allez chercher votre Pi, votre carte d'expérimentation et au travail !

The Wiring You will need a Raspberry Pi, a breadboard, two LEDs - one Red and one White, two 220 Ohm resistors and 3 jumper wires. I’ve used the original Pi for this wiring image example. If you have a Pi B+ or 2B (or even the brand new 3), the pins at this point are exactly the same. Just to avoid confusion (on my side), the Cathodes (Negative side) of the LEDS are connected to the resistors going to ground, and the Anodes (Positive side) are connected through the jumper wires to the Pi pins. The positive side of the LED is usually marked by the longer lead and the negative side is the one that has the flat spot on the base of the LED.

Le câblage

Il vous faut un Raspberry Pi, une carte d'expérimentation, deux LED,une rouge et une blanche, deux résistances de 220 Ohms et 3 fils de raccordement.

Pour cet exemple de câblage, j'utilise le Pi original. Si vous avez un Pi B+ ou 2B (ou encore le tout nouveau 3), les broches concernées sont exactement les mêmes.

Pour éviter de s'emmêler les pinceaux (de mon côté), les Cathodes (côté Négatif) des LED sont connectées aux résistances, qui sont connectées, elles, à la terre, et les Anodes (côté Positif) sont connectées par les fils de raccordement aux broches du Pi. Le côté positif de la LED est habituellement indiqué par la broche la plus longue et le côté négatif est celui qui a un méplat sur la base du LED.

The Code I won’t explain the code just yet. Just put into the editor as it is. We will discuss it in a bit. Once you have the code entered correctly, then run it and see what happens. The Reveal If you have been paying attention over all these years, you probably have figured out what the code is doing. If you can’t figure it out, don’t feel bad. We’ll jump into the explanation. Instead of the LEDs being either on or off, they pulse on and off. Since I said earlier, we can only send out (or read) a On/Off voltage (or 1/0, or High/Low), so how can this be? We are using a trick called PWM or Pulse Width Modulation. We are still living with the rules, but we are bending them to our benefit. The pictures below, taken from my oscilloscope connected to the project, should help explain a bit clearer. We will be concerned with only one LED at this point.

Le code

Je n'expliquerai pas le code tout de suite. Il suffit de le copier tel quel dans l'éditeur. J'en parlerai après.

Une fois le code entré correctement, lancez-le et regardez ce qui se passe.

La révélation

Si vous avez prêté attention aux articles depuis le début, vous avez sans doute compris ce que fait le code. Sinon, ne vous tracassez pas : une explication suivra.

Les LED ne sont ni allumées ni éteintes, mais, à la place, elles basculent rapidement entre allumé et éteint. Puisque j'ai bien dit plus tôt que l'on ne peut émettre (ou lire) un voltage On/Off (ou 1/0 ou High/Low), comment est-ce possible ?

Nous utilisons un truc appelé PWM ou Pulse Width Modulation (modulation de largeur d'impulsions). Nous respectons toujours les règles, mais nous les contournons un peu dans notre intérêt. Les images ci-dessous, de mon oscilloscope connecté au projet, devront vous aider à comprendre un peu mieux. À ce stade, nous nous occuperons d'une seule LED.

If we send out a Low to the GPIO pin to the LED it's zero volts. The LED is getting nothing on the Anode, so it is off. In the last two articles, when we turned the LED on by sending the Anode of the LED a High So we have in the first instance a zero, and in the second a 1. Just like we have assumed… either Off or On. This time we vary the amount of time that the GPIO signal is high and low. If we do it slowly, the LED would simply flash on and off in response to the voltage. In the case of this version, we are switching it on and off very quickly and at the same time, changing the amount of time it is on compared to off, which is called the duty cycle. You can see that the signal is on for about 80% of the time and off for about 20%, which would be a 80% duty cycle. By doing this quickly, the LED reacts by dimming a bit from the 100% on all the time. As the program does its loop, it changes the duty cycle and makes the high longer or shorter depending on what part of the loop it is. In the picture above, we have a duty cycle of about 5%. In this case the LED is turned on for such a short time, that it is extremely dim and for all intents and purposes it is off.

Si nous envoyons un Low sur la sortie GPIO de la LED, cela fait zéro volt. La LED ne reçoit rien sur l'Anode et elle est donc éteinte. Dans les deux derniers articles, nous avons allumé la LED en envoyant un High à l'Anode de la LED. Ainsi, dans la première instance, nous avons un zéro et, dans la seconde, un 1. Comme prévu… soit Off soit On.

Cette fois-ci, nous varions le laps de temps où le signal GPIO est High et Low. Si nous le faisons lentement, les LED clignoteraient en réponse au voltage. Dans le cas de cette version, nous basculons entre les deux états très rapidement, tout en changeant le laps de temps pendant lequel il est On comparé à Off, ce qui s'appelle le rapport cyclique.

Comme vous pouvez le voir, le signal est On pendant environ 80 % du temps et Off pendant 20 %, ce qui ferait un rapport cyclique de 80 %. En faisant cela rapidement, la LED réagit en s'assombrissant un peu en dessous du 100 % de manière continue. Durant la boucle du programme, le rapport cyclique change et le High est rendu plus long ou plus court, selon telle ou telle partie de la boucle. Dans l'image ci-dessus, le rapport cyclique est d'environ 5 %. Dans ce cas, la LED est allumée pendant si peu de temps qu'elle est extrêmement sombre et, pour ainsi dire, elle est Off.

Now, let’s start taking apart the code. import RPi.GPIO as GPIO from time import sleep As always, we start with our imports. We import the GPIO library, and this time, we import the sleep function from the time library. You will understand the reason for that shortly. GPIO.setmode(GPIO.BCM) GPIO.setup(25,GPIO.OUT) GPIO.setup(24,GPIO.OUT) white = GPIO.PWM(25,100) red = GPIO.PWM(24,100) In these five lines, we set the GPIO mode to BCM, and set the GPIO pins 24 (physical pin 9) and 25 (physical pin 11) to be output pins. We have done this before. Now we set the values for the PWM to 100% duty cycle. white.start(0) # start white led on 0 percent duty cycle (off) red.start(100) # red fully on (100%) We next turn the Red LED on (100%) and the white LED to 0 volts. pause_time = 0.05 print(“Program Starting…Press CTRL+C to exit”)

Maintenant, examinons le code en détail.

import RPi.GPIO as GPIO from time import sleep

Comme toujours, nous commençons par les imports. Nous importons la bibliothèque GPIO et, cette fois-ci, nous importons la fonction sleep (sommeil) de la bibliothèque time (temps). Vous allez rapidement comprendre pourquoi.

GPIO.setmode(GPIO.BCM) GPIO.setup(25,GPIO.OUT) GPIO.setup(24,GPIO.OUT) white = GPIO.PWM(25,100) red = GPIO.PWM(24,100)

Dans ces cinq lignes, nous avons réglé le mode GPIO sur BCM et configuré le pins GPIO 24 (pin physique 9) et 25 (pin physique 11) comme pins de sortie. Nous avons déjà fait cela. Maintenant, nous réglons les valeurs du PWM à un rapport cyclique de 100 %.

white.start(0) # Démarrer la LED blanche avec un rapport cyclique de 0% (off)

red.start(100) # La rouge allumée en permanence (100%)

Ensuite, nous allumons la LED rouge (100%) et réglons la LED blanche à 0 volts.

pause_time = 0.05

print(“Program Starting…Press CTRL+C to exit”)

**We set the pause_time variable to 0.05 seconds. This makes it fast enough to (hopefully) not allow for a flicker.

In the next block of code, we do our loops. The first loop is to make the white LED get “brighter” and the red LED to get “dimmer”. The second is to reverse the process. Just using the first loop as an example, we use a FOR LOOP to set the value of i and then we set the duty cycle for the white LED to i and that of the red LED to 100-i.

Notice that we have wrapped this with a TRY…EXCEPT set. This allows us to continue to run until the user enters CTRL+C. When that happens, we fall out of the TRY side so we can do our clean up code.

So now you know that we can bend the rules to our use.

Next time, we will start to examine a different GPIO library. Until then, have fun.

Nous réglons la variable pause_time à 0,05 seconde. Cela la rend assez rapide pour (je l'espère) ne pas permettre un scintillement.

Dans le segment de code suivant, nous faisons les boucles. L'objectif de la première boucle est de rendre la LED blanche plus « brillante » et la LED rouge plus « sombre ». Celui de la deuxième est d'inverser le processus. Prenons la première boucle comme exemple : nous utilisons une boucle FOR pour régler la valeur de i, puis mettons le rapport cyclique de la LED blanche à i et celui de la LED rouge à 100-i.

Remarquez que nous l'avons entouré d'un ensemble TRY…EXCEPT, ce qui permet au programme de s'exécuter jusqu'à ce que l'utilisateur fasse CTRL+C. Quand cela arrive, nous quittons le côté TRY afin de pouvoir faire le code de nettoyage.

Ainsi, vous savez maintenant que nous avons la possibilité de contourner les règles dans notre intérêt.

La prochaine fois, nous commencerons notre examen d'une différente bibliothèque GPIO. En attendant, amusez-vous bien.

issue106/python.txt · Dernière modification : 2016/04/13 16:08 de andre_domenech