-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpio-hardware-keys.py
62 lines (52 loc) · 2.08 KB
/
gpio-hardware-keys.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import RPi.GPIO as GPIO
import time
import keyboard
class ButtonToKeyMapper:
def __init__(self, button_key_mappings):
self.button_key_mappings = button_key_mappings
self.button_states = {pin: False for pin in button_key_mappings.keys()}
# Initialize GPIO and setup pins
GPIO.setmode(GPIO.BCM)
for button_pin in self.button_key_mappings:
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def monitor_buttons(self):
try:
while True:
for button_pin, key in self.button_key_mappings.items():
button_state = not GPIO.input(button_pin) # Invert the logic because PUD_UP is used
if button_state:
if not self.button_states[button_pin]:
# Button is pressed for the first time
keyboard.press(key)
self.button_states[button_pin] = True
# print("Button pressed: " + key)
else:
if self.button_states[button_pin]:
# Button is released
keyboard.release(key)
self.button_states[button_pin] = False
# You can add additional keypresses or logic here as needed.
# Add a slight delay to debounce the buttons (adjust as needed)
time.sleep(0.05)
except KeyboardInterrupt:
pass
finally:
# Release any keys that may still be held down
for key in self.button_key_mappings.values():
keyboard.release(key)
GPIO.cleanup()
# Define GPIO pin to key mappings (adjust as needed)
button_key_mappings = {
26: "up",
19: "right",
13: "down",
6: "left",
21: "a", #option
20: "s", #edit
16: "z", #shift
12: "x", #play
}
# Create an instance of the ButtonToKeyMapper class
button_mapper = ButtonToKeyMapper(button_key_mappings)
# Start monitoring the buttons
button_mapper.monitor_buttons()