Différences entre versions de « RASP-SENSE-HAT-ASTRO-PI-Joystick »

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 4 : Ligne 4 :
  
 
== Le joystick ==
 
== Le joystick ==
{{bloc-etroit|text=The Sense HAT joystick is mapped to the four keyboard cursor keys, with the joystick middle-click being mapped to the Return key. This means that moving the joystick has exactly the same effect as pressing those keys on the keyboard. Remember that the down direction is with the HDMI port facing downwards.}}
+
{{bloc-etroit|text=Le joystick du Sense Hat est mis en correspondance (ont dit "''map''" en anglais) avec les 4 touches de déplacement du curseur, le click du joystick presse la touche "retour clavier" (dite "''Return''" ou "''Enter''" en anglais). Le joystick du Hat Sense se ''comporte'' donc comme ''un clavier''. Rappelez vous que la direction 'vers le bas' se trouve face au port HDMI.}}
  
 
[[fichier:RASP-SENSE-HAT-ASTRO-PI-Joystick-01.jpg]]
 
[[fichier:RASP-SENSE-HAT-ASTRO-PI-Joystick-01.jpg]]
Ligne 10 : Ligne 10 :
 
== Keyboard Mapping ==
 
== Keyboard Mapping ==
 
{{bloc-etroit|text=
 
{{bloc-etroit|text=
"Keyboard Mapping" que nous traduirons par "mappage clavier" qui est pris en charge par un pilote et transforme l'utilisation du joystick en simulation d'activation sur le clavier du PC.
+
"Keyboard Mapping" que nous traduirons par "mappage clavier" (''correspondance clavier'') est pris en charge par un pilote et transforme l'utilisation du joystick en simulation d'activation sur le clavier du PC.
  
 
L'utilisation d'un pilote et du "Keyboard Mapping" est plus que pratique, votre programme n'a pas besoin de savoir comment lire l'état du joystick... il a juste besoin de détecter les touches pressées sur le clavier (et cela, tous les programmes savent le faire).   
 
L'utilisation d'un pilote et du "Keyboard Mapping" est plus que pratique, votre programme n'a pas besoin de savoir comment lire l'état du joystick... il a juste besoin de détecter les touches pressées sur le clavier (et cela, tous les programmes savent le faire).   
 
}}
 
}}
  
'''1.''' Open '''Python 3''' from a terminal window as {{fname|sudo}} by typing:
+
'''1.''' Ouvrez '''Python 3''' depuis une fenêtre terminal et utilisez la commande suivante avec {{fname|sudo}}:
  
 
  <nowiki>sudo idle3 &</nowiki>
 
  <nowiki>sudo idle3 &</nowiki>
  
'''2.''' A Python Shell window will now appear.
+
'''2.''' Une fenêtre de commande Python va apparaître.
  
'''3.''' Select {{fname|File > New Window}}.
+
'''3.''' Sélectionnez l'option {{fname|File > New Window}} (Fichier > Nouvelle fenêtre).
  
 
'''4.''' Et tapez le code suivant:
 
'''4.''' Et tapez le code suivant:
Ligne 44 : Ligne 44 :
 
             print("AU REVOIR")</nowiki>
 
             print("AU REVOIR")</nowiki>
  
'''5.''' Select {{fname|File > Save}} and choose a file name for your program.
+
'''5.''' Sélectionnez {{fname|File > Save}} (pour "Fichier > Sauver") et choissisez un nom pour votre programme.
  
'''6.''' Then select {{fname|Run > Run module}}.<br /><br />Note that we are using the {{underline|pygame}} Python module to detect the key presses.
+
'''6.''' Sélectionnez ensuite {{fname|Run > Run module}} (pour "Executer > Exécutez module").<br /><br />Notez que nous utilisons le module Python {{underline|pygame}} pour détecter les touches pressées.
  
'''7.''' A blank window will appear. Use the mouse to move it to one side of your screen so that the Python Shell window is also visible.
+
'''7.''' Une fenêtre va apparaître. Utilisez la souris pour bouger cette fenêtre sur le côté de votre bureau de façon à pouvoir voir la fenêtre du Shell Python.
  
'''8.''' Keep the blank window selected but move the mouse over it, press and release some keys on the keyboard and waggle the Sense HAT joystick. Try pressing and holding a key for a moment and then releasing it a few seconds later. You should notice that two events occur when you do this: one for the key going down, and another for the key being released. For this program you will only use the '''KEY DOWN''' event.<small><br />KEY DOWN signifie FLECHE BAS</small>
+
'''8.''' Gardez le nouvelle fenêtre sélectionnée et bougez la souris au dessus de celle-ci, pressez et relachez des touches sur le clavier et jouez avec le joystick du Sense Hat. Essayez de presser et maintenir une touche enfoncé pendant un moment puis la relâcher quelques secondes. Vous pouvez noter que deux événements ("''EVENT'' en anglais) se passent durant ce temps: un événement lorsque la touche est enfoncée, et un autre événement lorsque la touche est relâchée. Dans ce programme vous allez uniquement utiliser l'événement '''KEY DOWN'''.<small><br />KEY DOWN signifie FLECHE BAS</small>
  
'''9.''' Click the {{fname|x}} in the corner of the blank pygame window. You should see the {{fname|AU REVOIR}} message appear in the Python Shell window but the blank window does not close.
+
'''9.''' Cliquez sur le {{fname|x}} dans coin supérieur droit de la fenêtre Pygame (dans laquelle nous n'affichons rien). Vous devriez voir le message {{fname|AU REVOIR}} apparâitre dans la fenêtre Shell Python Shell (mais la fenêtre vide ne se ferme pas).
  
 
We're consuming the pygame event queue using the {{fname|for event in pygame.event.get():}} syntax. This will loop through all keyboard and mouse events that occur. Inside the loop, we display what the event was by using {{fname|print(event)}} and then test to see if the event type is {{fname|QUIT}}. If it is, we set {{fname|running}} to {{fname|False}} which causes the {{fname|while}} loop to end and the program to finish. The program should print a line of text in the Python Shell window whenever we move the mouse, click the mouse, and press or release a keyboard key.
 
We're consuming the pygame event queue using the {{fname|for event in pygame.event.get():}} syntax. This will loop through all keyboard and mouse events that occur. Inside the loop, we display what the event was by using {{fname|print(event)}} and then test to see if the event type is {{fname|QUIT}}. If it is, we set {{fname|running}} to {{fname|False}} which causes the {{fname|while}} loop to end and the program to finish. The program should print a line of text in the Python Shell window whenever we move the mouse, click the mouse, and press or release a keyboard key.

Version du 17 octobre 2015 à 12:17


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.

Le joystick

Le joystick du Sense Hat est mis en correspondance (ont dit "map" en anglais) avec les 4 touches de déplacement du curseur, le click du joystick presse la touche "retour clavier" (dite "Return" ou "Enter" en anglais). Le joystick du Hat Sense se comporte donc comme un clavier. Rappelez vous que la direction 'vers le bas' se trouve face au port HDMI.

RASP-SENSE-HAT-ASTRO-PI-Joystick-01.jpg

Keyboard Mapping

"Keyboard Mapping" que nous traduirons par "mappage clavier" (correspondance clavier) est pris en charge par un pilote et transforme l'utilisation du joystick en simulation d'activation sur le clavier du PC.

L'utilisation d'un pilote et du "Keyboard Mapping" est plus que pratique, votre programme n'a pas besoin de savoir comment lire l'état du joystick... il a juste besoin de détecter les touches pressées sur le clavier (et cela, tous les programmes savent le faire).

1. Ouvrez Python 3 depuis une fenêtre terminal et utilisez la commande suivante avec sudo:

sudo idle3 &

2. Une fenêtre de commande Python va apparaître.

3. Sélectionnez l'option File > New Window (Fichier > Nouvelle fenêtre).

4. Et tapez le code suivant:

import pygame

from pygame.locals import *
from sense_hat import SenseHat

pygame.init()
pygame.display.set_mode((640, 480))
sense = SenseHat()
sense.clear()

running = True

while running:
    for event in pygame.event.get():
        print(event)
        if event.type == QUIT:
            running = False
            print("AU REVOIR")

5. Sélectionnez File > Save (pour "Fichier > Sauver") et choissisez un nom pour votre programme.

6. Sélectionnez ensuite Run > Run module (pour "Executer > Exécutez module").

Notez que nous utilisons le module Python pygame pour détecter les touches pressées.

7. Une fenêtre va apparaître. Utilisez la souris pour bouger cette fenêtre sur le côté de votre bureau de façon à pouvoir voir la fenêtre du Shell Python.

8. Gardez le nouvelle fenêtre sélectionnée et bougez la souris au dessus de celle-ci, pressez et relachez des touches sur le clavier et jouez avec le joystick du Sense Hat. Essayez de presser et maintenir une touche enfoncé pendant un moment puis la relâcher quelques secondes. Vous pouvez noter que deux événements ("EVENT en anglais) se passent durant ce temps: un événement lorsque la touche est enfoncée, et un autre événement lorsque la touche est relâchée. Dans ce programme vous allez uniquement utiliser l'événement KEY DOWN.
KEY DOWN signifie FLECHE BAS

9. Cliquez sur le x dans coin supérieur droit de la fenêtre Pygame (dans laquelle nous n'affichons rien). Vous devriez voir le message AU REVOIR apparâitre dans la fenêtre Shell Python Shell (mais la fenêtre vide ne se ferme pas).

We're consuming the pygame event queue using the for event in pygame.event.get(): syntax. This will loop through all keyboard and mouse events that occur. Inside the loop, we display what the event was by using print(event) and then test to see if the event type is QUIT. If it is, we set running to False which causes the while loop to end and the program to finish. The program should print a line of text in the Python Shell window whenever we move the mouse, click the mouse, and press or release a keyboard key.

Détecter les mouvements du joystick

Consider how a joystick might work. You can use the LED matrix to help you think about it. Let's make a pixel white and use the joystick to move the pixel around the 8x8 matrix. To do this you can use an event to detect a key press. For example, if a key is pressed DOWN what steps need to happen to move the pixel?

- Turn OFF the LED using current `x` and `y`
- If DOWN then add 1 to `y`
- If UP then subtract 1 from `y`
- If RIGHT then add 1 to `x`
- If LEFT then subtract 1 from `x`
- Turn ON the LED using updated `x` and `y`


1. Start by just adding the code for the DOWN key. Delete the print(event) command that you used in the previous section and insert the code below at the same indentation level:

if event.type == KEYDOWN:
    sense.set_pixel(x, y, 0, 0, 0)  # Black 0,0,0 means OFF

    if event.key == K_DOWN:
        y = y + 1

        sense.set_pixel(x, y, 255, 255, 255)

2. Save and run the code. You should be able to move the pixel point down using the DOWN key or the joystick. If you keep going, you'll eventually see this error:

ValueError: Y position must be between 0 and 7

3. Our y value can only be between 0-7, otherwise it's off the edge of the matrix and into empty space! So that's why the error happens; the Sense HAT doesn't understand values outside this range. Our code just keeps adding 1 to y every time the DOWN key is pressed, so we need to stop y going above 7.

We can achieve this by adding the syntax and y < 7 (and y is less than 7) to the key direction test:

if event.key == K_DOWN and y < 7:
    y = y + 1

4. Save and run the code again; this time, the code should not allow the point to go beyond the edge of the screen.

5. Now that this works, you will need to add the other directions for the joystick. Where you have if event.key == K_DOWN: in your code, you can also use:

  • K_UP - Touche vers le haut
  • K_DOWN - Touche vers le bas
  • K_LEFT - Touche vers la gauche
  • K_RIGHT - Touche vers la droite
  • K_RETURN - Touche "retour clavier" ou "entrée".

6. We can add a section for each direction to complete your code:

import pygame

from pygame.locals import *
from sense_hat import SenseHat

pygame.init()
pygame.display.set_mode((640, 480))

sense = SenseHat()
sense.clear()

running = True

x = 0
y = 0
sense.set_pixel(x, y, 255, 255, 255)

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            sense.set_pixel(x, y, 0, 0, 0)  # Black 0,0,0 means OFF

            if event.key == K_DOWN and y < 7:
                y = y + 1
            elif event.key == K_UP and y > 0:
                y = y - 1
            elif event.key == K_RIGHT and x < 7:
                x = x + 1
            elif event.key == K_LEFT and x > 0:
                x = x - 1

        sense.set_pixel(x, y, 255, 255, 255)
        if event.type == QUIT:
            running = False
            print("BYE")

7. When you run your code, you should now be able to move the pixel point anywhere on the matrix.


Source: Getting Started with Astro PI et Astro-Pi Guide proposé par Raspberry Pi Learning Resource (www.raspberrypi.org)

Licence Creative Commons - CC-BY-SA
The learning resource is provided for free by the Raspberry Pi Foundation under a Creative Commons licence.
Find more at raspberrypi.org/resources and github.com/raspberrypilearning.

Traduction réalisée par Meurisse. D pour shop.MCHobby.be - Licence CC-BY-SA.
Crédit de traduction: Toute référence, mention ou extrait de cette traduction doit également être explicitement accompagné du crédit de traduction suivant : «  Traduction par MCHobby (shop.MCHobby.be) » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.