einfacher Keyboard Event?

  • Hallo,
    ich versuche eine LED über die Tastatur An und Auszuschalten. Habe es schon mit pygame versucht doch ohne Erfolg bzw. ohne Fehlermeldung.

    Ich möchte einfach nur wenn ich das Script Ausführe das wenn ich zb. A oder 1 drücke die LED an geht und wenn ich A oder 1 noch einmal drücke die LED wieder ausgeht.

    :helpnew:

    So sieht mein Script rein für die LED aus:

    Einmal editiert, zuletzt von StolleJay (9. Mai 2015 um 21:51)

  • Mit pygame könnte das wie folgt aussehen:

    [code=php]#!/usr/bin/python
    # -*- coding: utf-8 -*-

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

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

    red = 17
    yellow = 27
    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(yellow, 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:
    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')
    [/php]..bei erneutem drücken der Taste wird der GPIO wieder ausgeschaltet..

    Welche Taste wie erkannt wird steht hier: https://www.pygame.org/docs/ref/key.html

    Nachteil hierbei ist eben dass das Display initialisiert werden und du das pygame Fenster aktiv haben musst.

    //EDIT: Siehe dazu auch
    => http://wiki.roxxs.org/index.php/Python/keyboard_event
    => http://wiki.roxxs.org/index.php/Bash/keyboard_event

  • Ein Kollege hat mich gefragt ob so etwas Möglich ist da er sein Pi als Steuermodul für seine selbst gebaute Modellbahnanlage nutzen Möchte worüber er auch Manuell (Automatisch hab ich das alles schon hinbekommen) via Tastatur Signale, Ampeln etc. Steuern kann. Da er jedoch vom Programmieren überhaupt keine Ahnung hat bzw. noch viel weniger als ich mache ich das für ihn bzw. Versuche es.

  • Alternativ die Sache von oben nur in bash:

    [code=php]#!/bin/bash

    declare -A GPIO
    GPIO['a']=17 ;#red
    GPIO['1']=22 ;#green
    GPIO['y']=27 ;#yellow


    ## init GPIOpin
    for key in ${!GPIO[@]}; do
    if [ ! -f /sys/class/gpio/gpio${GPIO[$key]}/value ]; then
    echo ${GPIO[$key]} > /sys/class/gpio/export
    echo out > /sys/class/gpio/gpio${GPIO[$key]}/direction
    fi
    done


    function schalten() {
    ## get current state
    GPIOstate=$(cat /sys/class/gpio/gpio${1}/value)

    ## switch state
    NEWstate=$(( ! $GPIOstate ))
    echo $NEWstate > /sys/class/gpio/gpio${1}/value
    echo "switched GPIOpin $1 from $GPIOstate to $NEWstate"
    }

    function _exit() {
    stty sane
    #echo -e '\nQuit\n'
    exit 0
    }
    trap _exit SIGHUP SIGINT SIGTERM EXIT

    stty -echo

    while :; do
    read -n 1 keypress
    if [ "$keypress" == "a" ]; then
    echo "Key 'a' is pressed"
    schalten ${GPIO[$keypress]}
    elif [ "$keypress" == "1" ]; then
    echo "Key '1' is pressed"
    schalten ${GPIO[$keypress]}
    elif [ "$keypress" == "y" ]; then
    echo "Key 'y' is pressed"
    schalten ${GPIO[$keypress]}
    else
    echo "Unknown key: $keypress"
    fi
    done

    [/php]

  • Noch eine Alternative mithilfe des Python Modules curses

    [code=php]
    #!/usr/bin/python
    # by meigrafd

    from __future__ import print_function
    import curses
    import RPi.GPIO as GPIO

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

    red = 17
    yellow = 27
    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(yellow, 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()
    [/php]

Jetzt mitmachen!

Du hast noch kein Benutzerkonto auf unserer Seite? Registriere dich kostenlos und nimm an unserer Community teil!