-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyboardplay.py
executable file
·94 lines (82 loc) · 3.14 KB
/
keyboardplay.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
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 仅为了测试与检查所用。
#
# 在键盘上按动字符1-8,使得实体的八个舵机分别敲击。
import sys, os
import select
import tty
import termios
import time
import multiprocessing
# 键值数值标记
keyboard_data = {\
"=": {"low":0.23, "high":0.21, "gpio":21, "time":0.14},\
"-": {"low":0.23, "high":0.21, "gpio":18, "time":0.14},\
'0': {"low":0.22, "high":0.20, "gpio":17, "time":0.14},\
'9': {"low":0.23, 'high':0.20, 'gpio':4, 'time':0.12},\
'8': {'low':0.165, 'high':0.21, 'gpio':25, 'time':0.14},\
'7': {'low':0.18, 'high':0.21, 'gpio':24, 'time':0.14},\
'6': {'low':0.23, 'high':0.26, 'gpio':23, 'time':0.14},\
'5': {'low':0.18, 'high':0.20, 'gpio':22, 'time':0.14},\
'4': {'low':0.19, 'high':0.21, 'gpio':21, 'time':0.14},\
'3': {'low':0.19, 'high':0.21, 'gpio':18, 'time':0.14},\
'2': {'low':0.18, 'high':0.20, 'gpio':17, 'time':0.14},\
'1': {'low':0.18, 'high':0.20, 'gpio':4, 'time':0.12}}
# 确认是树莓派平台
#is_under_pi = False
is_under_pi = True
def kp_play_note_once(inputnote):
"""
Play a note once a time.
"""
#if inputnote == 0:
# Do nothing
# return
#if inputnote > 9:
# Return to upright position
# pass
# count = 0
# while count < 8:
# count += 1
# os.system('echo {0}={1} >> /dev/pi-blaster'.format(keyboard_data[count]['gpio'], keyboard_data[count]['high']))
# time.sleep(keyboard_data[count]['time'])
# print('All released.')
# return
print('{0} pressed; Will play: {1}.'.format(inputnote, keyboard_data[inputnote]))
if not is_under_pi:
return
os.system('echo {0}={1} >> /dev/pi-blaster'.format(keyboard_data[inputnote]['gpio'], keyboard_data[inputnote]['low']))
time.sleep(keyboard_data[inputnote]['time'])
os.system('echo {0}={1} >> /dev/pi-blaster'.format(keyboard_data[inputnote]['gpio'], keyboard_data[inputnote]['high']))
# May be improved later? Don't use os.system (TODO)
return
def kp_start_playing():
"""
Non-stop play the note using keyboard.
Use ESC to stop.
"""
def isData():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
while True:
if not isData():
c = sys.stdin.read(1)
if True:#c >= '0' and c <= '9':
# Valid input, use multiprocessing to prevent problem?
# 0 means release
p = multiprocessing.Process(target=kp_play_note_once, args=(c,))
p.start()
# Never join!
continue
elif c == '\x1b': # ESC
break
print('Not valid input.') # Invalid input
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
if __name__ == "__main__":
# 读取键盘输入的1-8,转换成音乐播放
kp_start_playing()
# vim: set ts=8 sw=4 tw=0 et :