Advertisement
Guest User

Untitled

a guest
Nov 28th, 2023
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import os
  2. import sys
  3. import RPi.GPIO as GPIO
  4. import time
  5. from pygame import mixer
  6.  
  7. # init and PIN setup
  8. button_en = 5
  9. button_fr = 6
  10. sensor1 = 23
  11. sensor2 = 24
  12.  
  13. GPIO.setmode(GPIO.BCM)
  14. GPIO.setup([button_en, button_fr], GPIO.IN, pull_up_down=GPIO.PUD_UP)
  15. GPIO.setup([sensor1, sensor2], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
  16. GPIO.add_event_detect(button_en, GPIO.FALLING)
  17. GPIO.add_event_detect(button_fr, GPIO.FALLING)
  18. GPIO.add_event_detect(sensor1, GPIO.RISING)
  19. GPIO.add_event_detect(sensor2, GPIO.RISING)
  20.  
  21. mixer.init()
  22. fr_track = '/path/to/musicfile.wav'
  23. en_track = '/path/to/musicfile2.wav'
  24. maxIdle = 4 * 3600 # delay in hours before script restart
  25. sensor_delay = 25 # delay (in seconds) between play() and reactivating sensors
  26. lang = "en"
  27. lastmove = time.time()
  28. motion = 0
  29.  
  30. # script self restart function
  31. def self_restart():
  32. os.execv(sys.executable, [sys.executable] + sys.argv)
  33.  
  34. # switch langage function
  35. def fr_en(lg):
  36. if lg == "fr":
  37. mixer.music.load(fr_track)
  38. return "en"
  39. elif lg == "en":
  40. mixer.music.load(en_track)
  41. return "fr"
  42.  
  43. # main loop
  44. try:
  45. while 1:
  46. # button interrupts
  47. if GPIO.event_detected(button_fr) or GPIO.event_detected(button_en):
  48. time.sleep(.100)
  49. if GPIO.input(button_fr) == GPIO.LOW:
  50. mixer.music.load(fr_track)
  51. mixer.music.play()
  52. lastmove = time.time()
  53. elif GPIO.input(button_en) == GPIO.LOW:
  54. mixer.music.load(en_track)
  55. mixer.music.play()
  56. lastmove = time.time()
  57.  
  58. # motion sensors, keeps one movement in memory during track
  59. if (time.time() - lastmove) >= sensor_delay:
  60. if GPIO.event_detected(sensor1) or GPIO.event_detected(sensor2):
  61. time.sleep(1)
  62. if GPIO.input(sensor1) == GPIO.HIGH:
  63. motion = 1
  64. elif GPIO.input(sensor2) == GPIO.HIGH:
  65. motion = 1
  66.  
  67. if motion:
  68. if not mixer.music.get_busy():
  69. lang = fr_en(lang)
  70. mixer.music.play()
  71. motion = 0
  72. lastmove = time.time()
  73.  
  74. if (time.time() - lastmove) >= maxIdle:
  75. print("idle restart")
  76. self_restart()
  77.  
  78. time.sleep(.200)
  79.  
  80.  
  81. # end of script
  82. finally:
  83. print("restarting ...")
  84. GPIO.cleanup()
  85. self_restart()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement