forked from mlesniew/amiga-joystick-rpi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amiga-joystick.py
executable file
·86 lines (67 loc) · 2.37 KB
/
amiga-joystick.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python2
import time
import threading
try:
import uinput
except ImportError:
raise SystemExit('uinput module missing -- to install run "sudo apt-get install python-uinput"')
import RPi.GPIO as GPIO
# this is the mapping of GPIO numbers (in BCM mode) to key codes
CHANNELS = {
6: uinput.KEY_UP,
13: uinput.KEY_DOWN,
19: uinput.KEY_LEFT,
26: uinput.KEY_RIGHT,
20: uinput.KEY_LEFTCTRL, # button A
21: uinput.KEY_LEFTALT, # button B
}
KEYS = CHANNELS.values()
# Debounce time in seconds
BOUNCETIME = 1.0 / 100
def capture_keys():
GPIO.setmode(GPIO.BCM)
with uinput.Device(KEYS, name='amiga-joystick') as device:
# current state of all buttons
state = { ch: False for ch in CHANNELS }
condition = threading.Condition()
inputs_changed = set()
# this will get called when the Raspberry detects a change on the
# inputs
def callback(channel):
with condition:
inputs_changed.add(channel)
condition.notify()
# setup GPIOs and callbacks
for channel in CHANNELS:
GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(channel, GPIO.BOTH, callback=callback)
# all set, start looping
while True:
with condition:
# wait for at least one input to change
while not inputs_changed:
condition.wait()
# process the changes
while inputs_changed:
channel = inputs_changed.pop()
ch_state = not GPIO.input(channel)
if state[channel] != ch_state:
# a button got pressed or released
state[channel] = ch_state
device.emit(CHANNELS[channel], ch_state)
# take a short break to do a kind of debouncing
time.sleep(BOUNCETIME)
def main():
# run the function in a separate background thread -- otherwise it's not
# possible to interrupt it using CTRL-C
thread = threading.Thread(target=capture_keys)
thread.daemon = True
thread.start()
# wait forever
while True:
raw_input()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
raise SystemExit