Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from gpiozero import TonalBuzzer
- from gpiozero.tones import Tone
- import time
- def get_integer(prompt, min = 0, max = 65536): # min and max can be over-ridden by calling code
- '''gets an integer from the user '''
- valid_input = False
- while not valid_input:
- user_input = input(prompt + '_')
- user_input = user_input.strip()
- if user_input == '':
- print("\nPressing Enter only, or spaces does not work...")
- else:
- try:
- user_input = int(user_input)
- if user_input >= min and user_input <= max:
- valid_input = True
- else:
- print("\nTry a number from " + str(min) + " to " + str(max) + "...")
- except:
- print("\nTry entering a number - " + user_input + " does not cut it...")
- return user_input
- def menu(title, menu_list):
- ''' displays a menu using the text in 'title', and a list of menu items (string) '''
- print(title)
- for i in range(1, len(menu_list) + 1):
- print(f"\t{i}) {menu_list[i-1]}")
- return get_integer(f"Type the number of your choice (1 to {len(menu_list)})", 1, len(menu_list)) - 1
- def play_tune(buzzer, tune):
- '''Auto detect whether string eg 'C4' or integer supplied'''
- is_tone = False
- if type(tune[0][0]) is int:
- is_tone = True
- for i in range(len(tune[0])):
- if is_tone:
- buzzer.play(Tone(midi=tune[0][i]))
- else:
- buzzer.play(tune[0][i])
- time.sleep(tune[1][i])
- buzzer.stop()
- def main():
- star_wars = [['C4','G4','F4','E4','D4','C5','G4','F4','E4','D4','C5','G4','F4','E4','F4','D4'],
- [1.2, 0.8, 0.4, 0.4, 0.4, 0.8, 0.8, 0.4, 0.4, 0.4, 0.8, 0.8, 0.4, 0.4, 0.4, 1.6]]
- harry_buzzer = [[59,64,67,65,64,71,69,65,64,67,65,63,66,59,64,67,65,64,71,74,74,72,69,72,71,70,58,67,64,64,
- 67,71,67,71,67,72,71,70,65,67,71,70,58,59,71,71,67,71,67,71,67,74,73,72,68,72,71,70,58,67,64,58],
- [.25,.375,.125,.25,.5,.25,.75,.75,.375,.125,.25,.5,.25,.75,.375,.125,.25,.5,.25,.75,.25,.75,.25,.375,.125,.25,.5,.25,.75,.5,
- .25,.5,.25,.5,.25,.5,.25,.5,.25,.375,.125,.25,.5,.25,.75,.5,.25,.5,.25,.5,.25,.5,.25,.5,.25,.375,.125,.25,.5,.25,.75,.1]]
- tunes = [star_wars, harry_buzzer]
- choice = menu("Choose your tune:",["Star Wars", "Harry Buzzer"])
- buzzer = TonalBuzzer(17)
- play_tune(buzzer, tunes[choice])
- main()
Add Comment
Please, Sign In to add comment