Différences entre versions de « MicroPython-Hack-souris »

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 65 : Ligne 65 :
  
 
== Transformer l'accéléromètre en souris ==
 
== Transformer l'accéléromètre en souris ==
 +
{{traduction}}
 +
 
Now lets make the mouse move based on the angle of the pyboard, using the accelerometer. The following code can be typed directly at the REPL prompt, or put in the {{fname|main.py}} file. Here, we’ll put in in {{fname|main.py}} because to do that we will learn how to go into safe mode.
 
Now lets make the mouse move based on the angle of the pyboard, using the accelerometer. The following code can be typed directly at the REPL prompt, or put in the {{fname|main.py}} file. Here, we’ll put in in {{fname|main.py}} because to do that we will learn how to go into safe mode.
  

Version du 10 avril 2015 à 11:09


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.

Transformer votre PyBoard en souris

La carte pyboard est un périphérique USB et peut être configurée pour agir comme une souris à la place du lecteur Flash USB que vous connaissez déjà.

Pour transformer votre PyBoard en périphérique souris, vous devez d'abord editer le fichier boot.py et y changer la configuration USB. Si vous n'avez pas encore modifié votre fichier boot.py il devrait ressembler à quelque-chose comme ceci:

# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
#pyb.main('main.py') # main script to run after this one
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

Vous trouverez ci-dessous une version du même fichier avec une traduction des commentaire pour vous aider à en comprendre le contenu.

# boot.py -- executé au démarrage
# Peut exécuter un script Python arbitraire, mais le mieux est de le garder aussi minimaliste que possible

import pyb
#pyb.main('main.py') # Le script principal à exécuter après celui-ci.
#pyb.usb_mode('CDC+MSC') # agit comme périphérique série et de stockage
#pyb.usb_mode('CDC+HID') # agit comme périphérique série et souris

Pour activer le mode souris, il faut décommenter la dernière ligne du fichier.

Cette ligne du fichier doit alors ressembler à ceci:

pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

Si vous avez déjà modifié votre fichier boot.py alors le code minimum pour fonctionner est celui-ci:

import pyb
pyb.usb_mode('CDC+HID')

Cela informe le pyboard de se configurer son USB comme un CDC (port série) et HID (interface Homme-Machine dite "human interface device", dans notre cas, c'est une souris) au moment du boot.

Ejectez/démonter le lecteur USB/Flash de votre carte Pyboard et réinitialisez votre carte en pressant le bouton RST. Votre PC détectera maintenant puboard comme une souris!

Envoyer des événements souris

Pour que notre souris-python fasse des choses, il faut que le programme envoie des événements souris à notre PC. Pour commencer, nous allons faire cela manuellement avec une invite de commande REPL (voyez les précédents tutoriels). Connectez-vous sur votre PyBoard à l'aide de votre logiciel terminal favoris et tapez la commande suivante:

>>> pyb.hid((0, 10, 0, 0))

Votre souris devrait se déplacer de 10 pixels sur la droite!

La commande ci-dessus envoi 4 informations: l'état du bouton, x, y et défilement (scroll en anglais). Le numéro 10 indique à notre ordinateur qu'il y a un déplacement de 10 pixels (10 points) dans la direction x.

Faisons osciller notre souris de gauche à droit:

>>> import math
>>> def osc(n, d):
...   for i in range(n):
...     pyb.hid((0, int(20 * math.sin(i / 10)), 0, 0))
...     pyb.delay(d)
...
>>> osc(100, 50)

Le premier argument de la fonction osc est le nombre d'événement souris à envoyer. Le second argument est le délais (en millisecondse) entre les événements. Testez la fonction avec différentes valeurs numériques.

Exercice

Une petit exercice amusant est de faire dessiner un cercle à la souris.

Transformer l'accéléromètre en souris

Now lets make the mouse move based on the angle of the pyboard, using the accelerometer. The following code can be typed directly at the REPL prompt, or put in the main.py file. Here, we’ll put in in main.py because to do that we will learn how to go into safe mode.

At the moment the pyboard is acting as a serial USB device and an HID (a mouse). So you cannot access the filesystem to edit your main.py file.

You also can’t edit your boot.py to get out of HID-mode and back to normal mode with a USB drive...

To get around this we need to go into safe mode. This was described in the [safe mode tutorial](tut-reset), but we repeat the instructions here:

  1. Hold down the USR switch.
  2. While still holding down USR, press and release the RST switch.
  3. The LEDs will then cycle green to orange to green+orange and back again.
  4. Keep holding down USR until only the orange LED is lit, and then let go of the USR switch.
  5. The orange LED should flash quickly 4 times, and then turn off.
  6. You are now in safe mode.

In safe mode, the boot.py and main.py files are not executed, and so the pyboard boots up with default settings. This means you now have access to the filesystem (the USB drive should appear), and you can edit main.py. (Leave boot.py as-is, because we still want to go back to HID-mode after we finish editting main.py.)

In main.py put the following code:

import pyb

switch = pyb.Switch()
accel = pyb.Accel()

while not switch():
    pyb.hid((0, accel.x(), accel.y(), 0))
    pyb.delay(20)

Save your file, eject/unmount your pyboard drive, and reset it using the RST switch. It should now act as a mouse, and the angle of the board will move the mouse around. Try it out, and see if you can make the mouse stand still!

Press the USR switch to stop the mouse motion.

You’ll note that the y-axis is inverted. That’s easy to fix: just put a minus sign in front of the y-coordinate in the pyb.hid() line above.

Restaurer l'état normal de la PyBoard

If you leave your pyboard as-is, it’ll behave as a mouse everytime you plug it in. You probably want to change it back to normal. To do this you need to first enter safe mode (see above), and then edit the boot.py file. In the boot.py file, comment out (put a # in front of) the line with the CDC+HID setting, so it looks like:

#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

Save your file, eject/unmount the drive, and reset the pyboard. It is now back to normal operating mode.



Source: Making the pyboard act as a USB mouse é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.