Aus PISACORE
Wechseln zu: Navigation, Suche

Python2 Scripts zum reagieren auf Tastatur Tasten

pygame

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
import os
import sys
import pygame
from pygame.locals import *
from RPi import GPIO

#------------------------------------------------------------------------

red = 17
green = 22

# to use RaspberryPi gpio# (BCM) or pin# (BOARD)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)

#------------------------------------------------------------------------

GPIO.setwarnings(False)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)

os.environ["SDL_FBDEV"] = "/dev/fb1"
width  = 320
height = 240
size = (width, height)
pygame.display.init()
screen = pygame.display.set_mode(size)

def schalten(pin):
    current_state = GPIO.input(pin)
    GPIO.output(pin, not current_state)
    print('switched GPIOpin {} from {} to {}' . format(pin, current_state, (not current_state)))


try:
    running=True
    clock = pygame.time.Clock()
    # run the game loop
    while running:
        clock.tick(10)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                #https://www.pygame.org/docs/ref/key.html
                if event.key == K_a:
                    print('Key "a" is pressed')
                    schalten(red)
                elif event.key == K_1:
                    print('Key "1" is pressed')
                    schalten(green)
                else:
                    print('Unknown Key: "{}"'.format(str(pygame.key.name(event.key))))

except pygame.error, perr:
    print('pygame Error: ' + str(perr))
except (KeyboardInterrupt, SystemExit):
    running = False
    GPIO.cleanup()
    print('\nQuit\n')


Tkinter

from Tkinter import Tk, Frame

def keyup(event):
    key = event.keysym
    print "Key Released: %s" % key

def keydown(event):
    key = event.keysym
    print "Key Pressed: %s" % key

root = Tk()
frame = Frame(master=root, width=100, height=100)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
root.mainloop()


curses

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
import sys
import curses
from RPi import GPIO

#------------------------------------------------------------------------

red = 17
green = 22

# to use RaspberryPi gpio# (BCM) or pin# (BOARD)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)

#------------------------------------------------------------------------

GPIO.setwarnings(False)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)

def schalten(pin):
    current_state = GPIO.input(pin)
    GPIO.output(pin, not current_state)
    stdscr.addstr(3, 5, 'switched GPIOpin {} from {} to {}' . format(pin, current_state, (not current_state)))

try:
    running=True
    #for KeyPress Events
    stdscr = curses.initscr() #init curses
    curses.cbreak() #react on keys instantly without Enter
    curses.noecho() #turn off echoing of keys to the screen
    stdscr.keypad(1) #returning a special value such as curses.KEY_LEFT
    stdscr.addstr(0, 0, "Hit 'q' to quit") #display text on pos y, x
    # run the loop
    while running:
        stdscr.move(1,0) #move cursor to (new_y, new_x)
        key = stdscr.getch() #waits until a key is pressed
        stdscr.clrtobot() #erase all lines below the cursor
        stdscr.refresh()
        if key == ord('q'): raise KeyboardInterrupt
        elif key == ord('a'):
            stdscr.addstr(2, 5, 'Key "a" is pressed')
            schalten(red)
        elif key == ord('1'):
            stdscr.addstr(2, 5, 'Key "1" is pressed')
            schalten(green)
        else:
            stdscr.addstr(2, 5, 'Unknown Key: "{}"'.format(curses.keyname(key)))
        stdscr.refresh()

except KeyboardInterrupt:
    stdscr.addstr(1, 0, "..Quitting..")
    stdscr.refresh()
    running=False
except Exception, e:
    print("\nError: " + str(e))
    running=False

stdscr.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
GPIO.cleanup()


termios

#!/usr/bin/python
import sys
import termios
import tty

inkey_buffer = 1

def inkey():
    fd=sys.stdin.fileno()
    remember_attributes=termios.tcgetattr(fd)
    tty.setraw(sys.stdin.fileno())
    character=sys.stdin.read(inkey_buffer)
    termios.tcsetattr(fd,termios.TCSADRAIN, remember_attributes)
    return character

while 1:
    key = (inkey())
    if key == 'w':
        print key
    if key == 'q':
        exit()


stdin

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()


evdev

from evdev import InputDevice, list_devices, categorize, ecodes, KeyEvent

dev = InputDevice("dev/input/event2") # in meinem Falle eine extra Numerische USB-Tastatur

for event in dev.read_loop():
     if event.type == ecodes.EV_KEY:
          key = categorize(event)
          if key.keystate = KeyEvent.key_hold: 
                 #Taste wird festgehalten