RASP-PYGAME-GUI-ECRAN

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.

De l'écran vers le GPIO

Voyons maintenant comment obtenir une entrée depuis l'écran tactile. Nous allons utiliser cette information pour allumer quelques LEDs sur le breadboard.

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Avec les 4 boutons ttactiles du PiTFT, il ne reste pas beaucoup de GPIO disponible sur un Raspberry-Pi. Raccordons donc #17 et #4. Le logiciel fait le rendu de 4 libellés (des labels en anglais) sur l'écran puis surveille les événements souris (mouse events) dans les 4 quartiers de l'écran.

Code d'initialisation

Dans cette partie du programme, nous allons configurer le 2 GPIOs en sortie de manière à pouvoir controler les LEDs. Nous devons également définir des varaibles d'environnement supplémentaires pour que la SDL prenne l'écran tactile en charge. La fonction os.putenv sera utilisée pour définir les variables d'environnement.

import pygame
from pygame.locals import *
import os
from time import sleep
import RPi.GPIO as GPIO
 
#Définir les GPIO comme sortie - Seul 4 et 17 restent disponibles
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
 
# Définir la couleur blanche
WHITE = (255,255,255)
 
os.putenv('SDL_FBDEV', '/dev/fb1')
os.putenv('SDL_MOUSEDRV', 'TSLIB')
os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')
 
pygame.init()
pygame.mouse.set_visible(False)
lcd = pygame.display.set_mode((320, 240))
# remplir l'écran en noir
lcd.fill((0,0,0))
pygame.display.update()
 
font_big = pygame.font.Font(None, 50)

Définition de l'interface

The touch_buttons map simply holds the button text and center position (x,y with top left as 0,0) for this text on the display. We then loop through this map and draw each "button".

touch_buttons = {'17 on':(80,60), '4 on':(240,60), '17 off':(80,180), '4 off':(240,180)}
 
for k,v in touch_buttons.items():
    text_surface = font_big.render('%s'%k, True, WHITE)
    rect = text_surface.get_rect(center=v)
    lcd.blit(text_surface, rect)
 
pygame.display.update()

La boucle principale

Here we introduce pygame events. Whenever there's some user interaction an event is generated on a queue for our program to read. It's the responsibility of our program to read this queue quickly enough to avoid events getting thrown away. Of course, we want to do this anyway to have a reasonably responsive program.

We're only really interested in the MOUSEBUTTONUP event, this will be added to the queue when you lift your finger off the display. We then simply get the current mouse position (this is also availble in the event itself) and determine which quadrant of the screen was selected.

while True:
    # Scan touchscreen events
    for event in pygame.event.get():
        if(event.type is MOUSEBUTTONDOWN):
            pos = pygame.mouse.get_pos()
            print pos
        elif(event.type is MOUSEBUTTONUP):
            pos = pygame.mouse.get_pos()
            print pos
            #Find which quarter of the screen we're in
            x,y = pos
            if y < 120:
                if x < 160:
                    GPIO.output(17, False)
                else:
                    GPIO.output(4, False)
            else:
                if x < 160:
                    GPIO.output(17, True)
                else:
                    GPIO.output(4, True)
    sleep(0.1)

This is certainly not a perfect UI experience: you could touch the screen on one button, drag to another and then lift off - which button did you hit? The complexities of event handling for simple things like clicking on buttons is one of the reasons why UI frameworks exist. We'll start using one in the next section.

Exécuter le programme

Again, you can run this from the pygamelcd project:

sudo python test3.py

Source: Raspberry Pi Pygame UI basics créé par by Jeremy Blythe pour www.adafruit.com

Traduit par Meurisse D. pour MCHobby SPRL 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.

Traduit avec l'autorisation d'AdaFruit Industries - Translated with the permission from Adafruit Industries - www.adafruit.com