Advertisement
Guest User

Untitled

a guest
May 5th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import RPi.GPIO as GPIO
  3. import time
  4.  
  5. BuzzerPin = 11 # pin11
  6.  
  7. SPEED = 1
  8.  
  9. # List of tone-names with frequency
  10. TONES = {"c6":1047,
  11. "b5":988,
  12. "a5":880,
  13. "g5":784,
  14. "f5":698,
  15. "e5":659,
  16. "eb5":622,
  17. "d5":587,
  18. "c5":523,
  19. "b4":494,
  20. "a4":440,
  21. "ab4":415,
  22. "g4":392,
  23. "f4":349,
  24. "e4":330,
  25. "d4":294,
  26. "c4":262}
  27.  
  28. # Song is a list of tones with name and 1/duration. 16 means 1/16
  29. SONG = [
  30. ["e5",16],["eb5",16],
  31. ["e5",16],["eb5",16],["e5",16],["b4",16],["d5",16],["c5",16],
  32. ["a4",8],["p",16],["c4",16],["e4",16],["a4",16],
  33. ["b4",8],["p",16],["e4",16],["ab4",16],["b4",16],
  34. ["c5",8],["p",16],["e4",16],["e5",16],["eb5",16],
  35. ["e5",16],["eb5",16],["e5",16],["b4",16],["d5",16],["c5",16],
  36. ["a4",8],["p",16],["c4",16],["e4",16],["a4",16],
  37. ["b4",8],["p",16],["e4",16],["c5",16],["b4",16],["a4",4]
  38. ]
  39.  
  40. def setup():
  41. GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
  42. GPIO.setup(BuzzerPin, GPIO.OUT)
  43.  
  44. def playTone(p,tone):
  45. # calculate duration based on speed and tone-length
  46. duration = (1./(tone[1]*0.25*SPEED))
  47.  
  48. if tone[0] == "p": # p => pause
  49. time.sleep(duration)
  50. else: # let's rock
  51. frequency = TONES[tone[0]]
  52. p.ChangeFrequency(frequency)
  53. p.start(0.5)
  54. time.sleep(duration)
  55. p.stop()
  56.  
  57. def run():
  58. p = GPIO.PWM(BuzzerPin, 440)
  59. p.start(0.5)
  60. for t in SONG:
  61. playTone(p,t)
  62.  
  63. def destroy():
  64. GPIO.output(BuzzerPin, GPIO.HIGH)
  65. GPIO.cleanup() # Release resource
  66.  
  67. if __name__ == '__main__': # Program start from here
  68. setup()
  69. try:
  70. run()
  71. GPIO.cleanup()
  72. except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
  73. destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement