RASP-SENSE-HAT-ASTRO-PI-Bouton

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.

Boutons de vols

Le boîtier de vol de l'Astro Pi utilise le sense Hat ainsi que 6 boutons d'usage général, boutons que vous pourriez brancher sur le GPIO du Raspberry Pi. Cela demande quelques opérations de bricolages mais au final, vous auriez 6 boutons de plus branché sur votre Pi, des boutons que vous pourriez exploiter dans vos propres programmes.

Il s'agit de simple bouton poussoir que l'on branche directement sur les broches du GPIO (dans un circuit pull-up): vous pouvez facilement recréer cette configuration en utilisant un breadboard, quelques boutons et du fils.

 

Les éléments nécessaires

Pour réaliser ce montage, vous aurez besoin des éléments suivants:

Utilisez ce stacking header allongé pour monter le votre Hat Sense sur le Rasberry Pi (à la place de celui déjà monté sur le hat sense).

De sorte, les broches du GPIO dépassent de l'autre côté du sense hat... il sera alors possible de brancher les cables sur le haut du pinHeader.

Le connecteur GPIO

Les boutons sont raccordés sur les 6 dernières broches en bas du GPIO du Pi.

Voici comment les raccorder sur le connecteur GPIO.

 

Note: l'orientation du diagramme des broches correspond aux broches de votre Pi avec le port USB et Ethernet placé vers le bas, et les rangées de broche du GPIO à main droite sur le Raspberry-Pi.

Cela signifie que cette configuration ne peut pas être utilisée si vous utilisez un ancien Raspberry A et/ou B. Si vous utilisez un ancien modèle, vous devrez choisir d'autres broches, mais aussi modifier les numéros de broches dans votre code.

Voici l'assignation des broches:

  • Les quatres boutons supérieurs:
    • Haut = UP: GPIO 26, broche 37
    • Bas = DOWN: GPIO 13, broche 33
    • Gauche = LEFT: GPIO 20, broche 38
    • Droite = RIGHT: GPIO 19, broche 35
  • La paire de bouton du bas
    • A (sur la gauche): GPIO 16, broche 36
    • B (sur la droite): GPIO: 21, broche 40

Si vous utilisez ces boutons pour réaliser votre projet alors vous aurez besoin de vous conformer a cet assignation de broche.

Détecter un bouton

Voici comment détecter la pression sur un bouton.

Les broches du GPIO peuvent être configurées comme entrée (input) ou sortie (output en anglais). Le mode sortie (output) est utilisé si vous avez besoin de fournir de l'électricité à un périphérique tel qu'une LED ou un buzzer. Avec le mode en entrée (input), une broche du GPIO dispose d'une valeur que vous pouvez lire dans vos programmes. Si une tension est appliqué sur la broche, la lecture renvéra la valeur 1 (HIGH, le niveau haut); Si la broche est connectée directement sur la masse (dit ground en anglais, donc sans tension), la lecture retournera la valeur 0 (LOW, le niveau bas).

The goal is to use a push button to switch voltage on and off for a GPIO pin, thus making the pin's reading change in our code when we press the button.

When a GPIO pin is in input mode the pin is said to be floating, meaning that it has no fixed voltage level. That's no good for what we want, as the pin will randomly float between HIGH and LOW. For this job, we need to know categorically whether the button is up or down, so we need to fix the voltage level to HIGH or LOW, and then make it change only when the button is pressed.

The flight hardware buttons are all wired in a pull up configuration, which means we pull the GPIO to HIGH and only short it to LOW when we press the button.o

 

In the diagram above we wire the GPIO pin to 3.3 volts through a large 10k ohm resistor so that it always reads HIGH. Then we can short the pin to ground via the button, so that the pin will go LOW when you press it.

So HIGH means button up and LOW means button down.

Fortunately, the Raspberry Pi has all the above circuitry built in; we can select a pull up circuit in our code for each GPIO pin, which sets up some internal circuitry that is too small for us to see. So you can get away with just using two jumper wires here, although you're welcome to wire it up the way shown above if you wish.

All we now need to do is create the above circuit six times for each of the GPIO pins.

Branchement sur breadboard

The diagram below shows how to wire up the six buttons on a breadboard so that they match the flight hardware. As always, wire colour does not matter. The numbers next to each button indicate the GPIO number that they are connected to. Every button requires one side to be connected to ground so that the HIGH GPIO pin can be shorted to LOW when the button is pressed.

 

 

Détecter un bouton (dans le code)

1. Open Python 3 from a terminal window en tant que super utilisateur avec sudo by typing:

sudo idle3 &

2. A Python Shell window will now appear.

3. Select File > New Window.

Type in or copy/paste the following code:

import RPi.GPIO as GPIO
import time
from sense_hat import SenseHat

sense = SenseHat()

UP = 26
DOWN = 13
LEFT = 20
RIGHT = 19
A = 16
B = 21  

running = True

def button_pressed(button):
    global running
    global sense
    print(button)
    sense.show_message(str(button))
    if button == B:
        running = False

GPIO.setmode(GPIO.BCM)

for pin in [UP, DOWN, LEFT, RIGHT, A, B]:
    GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
    GPIO.add_event_detect(pin, GPIO.FALLING, callback=button_pressed, bouncetime=100)

while running:
    time.sleep(1)

sense.show_message("Bye")

5. Select File > Save and choose a file name for your program.

6. Then select Run > Run module.

7. This program will just display the corresponding GPIO number every time a button is pressed. If you press the B button (bottom pair, right) then the program ends. This should allow you to test that your wiring is correct before proceeding.

8. The code above makes the button_pressed function run whenever any button is pressed. However, there are many different ways you can program the button detection. For instance, you might want to make your code wait until a button is pressed before doing something. Here is an example of how to do that using the UP button:

import RPi.GPIO as GPIO
from sense_hat import SenseHat

sense = SenseHat()

UP = 26
DOWN = 13
LEFT = 20
RIGHT = 19
A = 16
B = 21  

GPIO.setmode(GPIO.BCM)

for pin in [UP, DOWN, LEFT, RIGHT, A, B]:
    GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)

sense.show_message("Press UP to Start")
GPIO.wait_for_edge(UP, GPIO.FALLING)
sense.show_message("Nous y voici!")

9. You might also want to test if a button is being held down and perhaps do something if it was held down for over 3 seconds. Here is another example:

import RPi.GPIO as GPIO
import time
from sense_hat import SenseHat

sense = SenseHat()

UP = 26
DOWN = 13
LEFT = 20
RIGHT = 19
A = 16
B = 21  

GPIO.setmode(GPIO.BCM)

for pin in [UP, DOWN, LEFT, RIGHT, A, B]:
    GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)

while GPIO.input(A) == GPIO.HIGH:  # wait while HIGH / not pressed
    time.sleep(0.01)

button_down_time = time.time()  # record the time when the button went down

held_down = False

while GPIO.input(A) == GPIO.LOW:  # wait while LOW / pressed
    time.sleep(0.01)
    if time.time() - button_down_time > 3:  # has 3 seconds gone by?
        held_down = True
        break

if held_down:
    print("Held down")
    sense.show_message("Here we go!")
else:
    print("Not held down")

Lorsque vous maintenez le bouton A enfoncé pendant 3 secondes, vous devriez voir le message "Nous y voici".


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é.