MicroPython-Hack-LED

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche


MCHobby investit du temps et de l'argent dans la réalisation de traduction et/ou documentation. C'est un travail long et fastidieux réalisé dans l'esprit Open-Source... donc gratuit et librement accessible.
SI vous aimez nos traductions et documentations ALORS aidez nous à en produire plus en achetant vos produits chez MCHobby.

Activer les LEDs et concepts de base

L'une des choses les plus faciles à faire sur une carte PyBoard est est d'allumer les LEDs qui sont montés sur la carte. Connectez la carte, et connectez vous sur la carte en REPL comme décrit dans le tutoriel précédent. Nous allons commencer par allumer une LED dans l’interpréteur en tapant la commande suivante:

>>> myled = pyb.LED(1)
>>> myled.on()
>>> myled.off()

Ces commandes allume (on) et éteint (off) la LED.

Tout cela est très bien mais nous aimerions que ce processus soit automatisé. Ouvrez le fichier main.py sur la carte PyBoard avec votre éditeur de texte favorit. Ecrivez (ou copiez/collez) les lignes suivantes dans le fichier. Si vous débutez en Python, assurez-vous de bien préserver l'indentation dans les différentes lignes, cela est vraiment très important!

led = pyb.LED(2)
while True:
    led.toggle()
    pyb.delay(1000)

Lorsque vous sauvez le fichier, la LED rouge sur la carte doit s'allumer pendant environ une seconde. Pour exécuter le script, faite une réinitialisation logicielle (soft reset) en pressant (CTRL-D). La carte PyBoard va redémarrer et vous devriez voir la LED rouge clignoter continuellement. Ca marche? génial, vous venez de réaliser la première étape vous permettant de réaliser votre futur armée de petits robots! Lorsque vous serez lassé de voir la LED clignoter alors pressez la combinaison CTRL-C dans votre terminal pour interrompre l'exécution.

So what does this code do? First we need some terminology. Python is an object-oriented language, almost everything in python is a class and when you create an instance of a class you get an object. Classes have methods associated to them. A method (also called a member function) is used to interact with or control the object.

The first line of code creates an LED object which we have then called led. When we create the object, it takes a single parameter which must be between 1 and 4, corresponding to the 4 LEDs on the board. The pyb.LED class has three important member functions that we will use: on(), off() and toggle(). The other function that we use is pyb.delay() this simply waits for a given time in miliseconds. Once we have created the LED object, the statement while True: creates an infinite loop which toggles the led between on and off and waits for 1 second.

Exercice 1

Try changing the time between toggling the led and turning on a different LED.

Exercice 2

Connect to the pyboard directly, create a pyb.LED object and turn it on using the on() method.

C'est Disco sur votre PyBoard

So far we have only used a single LED but the pyboard has 4 available. Let’s start by creating an object for each LED so we can control each of them. We do that by creating a list of LEDS with a list comprehension.

leds = [pyb.LED(i) for i in range(1,5)]

If you call pyb.LED() with a number that isn’t 1,2,3,4 you will get an error message. Next we will set up an infinite loop that cycles through each of the LEDs turning them on and off.

n = 0
while True:
  n = (n + 1) % 4
  leds[n].toggle()
  pyb.delay(50)

Here, n keeps track of the current LED and every time the loop is executed we cycle to the next n (the % sign is a modulus operator that keeps n between 0 and 3.) Then we access the nth LED and toggle it. If you run this you should see each of the LEDs turning on then all turning off again in sequence.

One problem you might find is that if you stop the script and then start it again that the LEDs are stuck on from the previous run, ruining our carefully choreographed disco. We can fix this by turning all the LEDs off when we initialise the script and then using a try/finally block. When you press CTRL-C, Micro Python generates a VCPInterrupt exception. Exceptions normally mean something has gone wrong and you can use a try: command to “catch” an exception. In this case it is just the user interrupting the script, so we don’t need to catch the error but just tell Micro Python what to do when we exit. The finally block does this, and we use it to make sure all the LEDs are off. The full code is:

leds = [pyb.LED(i) for i in range(1,5)]
for l in leds:
    l.off()

n = 0
try:
   while True:
      n = (n + 1) % 4
      leds[n].toggle()
      pyb.delay(50)
finally:
    for l in leds:
        l.off()

Les 4 LEDs spéciales

The blue LED is special. As well as turning it on and off, you can control the intensity using the intensity() method. This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED gradually brighter then turns it off again.

led = pyb.LED(4)
intensity = 0
while True:
    intensity = (intensity + 1) % 255
    led.intensity(intensity)
    pyb.delay(20)

You can call intensity() on the other LEDs but they can only be off or on. 0 sets them off and any other number up to 255 turns them on.



Source: Turning on LEDs and basic Python concepts écrit par/written by Damien P.George

Traduit par Meurisse D. pour MCHobby.be - Translated by Meurisse D. for MCHobby.be

Traduit avec l'autorisation de micropython.org - Translated with the authorisation of micropython.org

Toute référence, mention ou extrait de cette traduction doit être explicitement accompagné du texte suivant : «  Traduction par MCHobby (www.MCHobby.be) - Vente de kit et composants » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.

L'utilisation commercial de la traduction (texte) et/ou réalisation, même partielle, pourrait être soumis à redevance. Dans tous les cas de figures, vous devez également obtenir l'accord du(des) détenteur initial des droits. Celui de MC Hobby s'arrêtant au travail de traduction proprement dit.