SHARE
TWEET

gpio_controls

a guest May 2nd, 2019 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import os
  2. import sys
  3. import time
  4. import signal
  5. from datetime import datetime
  6. import RPi.GPIO as GPIO
  7. from evdev import uinput, UInput, ecodes as e
  8.  
  9. # Settings
  10. BOUNCE_TIME = 0.01 # seconds
  11.  
  12. # GPIO defintions for buttons
  13. UP_BTN    = 30
  14. DOWN_BTN  = 31
  15. LEFT_BTN  = 32
  16. RIGHT_BTN = 33
  17. A_BTN     = 34
  18. B_BTN     = 35
  19. X_BTN     = 36
  20. Y_BTN     = 37
  21. START     = 38
  22. SELECT    = 39
  23. RTRIG     = 42
  24. LTRIG     = 43
  25.  
  26. BUTTONS = [A_BTN, B_BTN, X_BTN, Y_BTN, SELECT, START, RTRIG, LTRIG, UP_BTN, DOWN_BTN, LEFT_BTN, RIGHT_BTN]
  27.  
  28. KEYS = {# EDIT KEYCODES IN THE TABLE TO YOUR PREFERENCES:
  29.         # See /usr/include/linux/input.h for keycode names
  30.         #Button     # Keyboard          EmulationStation
  31.         RTRIG:      e.KEY_RIGHTALT,     #'RT' button
  32.         LTRIG:      e.KEY_LEFTALT,      #'LT' button
  33.         A_BTN:      e.KEY_A,            # 'A' button
  34.         B_BTN:      e.KEY_B,            # 'B' button
  35.         X_BTN:      e.KEY_X,            # 'X' button
  36.         Y_BTN:      e.KEY_Y,            # 'Y' button
  37.         UP_BTN:     e.KEY_UP,           # Dpad Up
  38.         DOWN_BTN:   e.KEY_DOWN,         # Dpad Down
  39.         RIGHT_BTN:  e.KEY_RIGHT,        # Dpad Right
  40.         LEFT_BTN:   e.KEY_LEFT,         # Dpad Left
  41.         SELECT:     e.KEY_SPACE,        # Select button
  42.         START:      e.KEY_ENTER         # Start button
  43. }
  44.  
  45.  
  46. # GPIO Init
  47. GPIO.setwarnings(False)
  48. GPIO.setmode(GPIO.BCM)
  49. GPIO.setup(BUTTONS, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  50.  
  51. try:
  52.     ui = UInput({e.EV_KEY: KEYS.values()}, name="game-io controls", bustype=e.BUS_USB)
  53. except uinput.UInputError as e:
  54.     sys.stdout.write(e.message)
  55.     sys.stdout.write("are you root?")
  56.     sys.exit(0)
  57.  
  58. def handle_button(channel):
  59.     key = KEYS[channel]
  60.     time.sleep(BOUNCE_TIME)
  61.     state = 0 if GPIO.input(channel) else 1
  62.     ui.write(e.EV_KEY, key, state)
  63.     ui.syn()
  64.  
  65. for button in BUTTONS:
  66.     GPIO.add_event_detect(button, GPIO.BOTH, callback=handle_button, bouncetime=1)
  67.  
  68.  
  69. while True:
  70.     time.sleep(3)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top