button.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import RPi.GPIO as GPIO
  2. import time
  3. import subprocess
  4. import logging
  5. import os
  6. import io
  7. import soundfile as sf
  8. import sounddevice as sd
  9. import pygame
  10. pygame.mixer.init()
  11. # Setup logging
  12. logging.basicConfig(filename='/home/pi/script_log.txt', level=logging.INFO, format='%(asctime)s - %(message)s')
  13. # Setup GPIO pins
  14. GPIO.setmode(GPIO.BCM)
  15. button1_pin = 17 # GPIO pin for Button 1
  16. button2_pin = 27 # GPIO pin for Button 2
  17. led_pin = 22 # GPIO pin for LED
  18. GPIO.setup(button1_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  19. GPIO.setup(button2_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  20. GPIO.setup(led_pin, GPIO.OUT)
  21. GPIO.output(led_pin, GPIO.LOW) # Turn off LED initially
  22. # Global process variable
  23. current_process = None
  24. pygame.mixer.music.load('Welcome.mp3')
  25. pygame.mixer.music.play()
  26. def run_script(script_path):
  27. global current_process
  28. if current_process is not None:
  29. logging.info("Terminating existing process...")
  30. current_process.terminate()
  31. time.sleep(2) # Give it some time to terminate
  32. if current_process.poll() is None: # If it's still running
  33. logging.info("Force killing process...")
  34. current_process.kill()
  35. current_process.wait()
  36. current_process = None
  37. GPIO.output(led_pin, GPIO.LOW) # Turn off LED
  38. logging.info(f"Starting {script_path}")
  39. current_process = subprocess.Popen(['python3', script_path])
  40. GPIO.output(led_pin, GPIO.HIGH) # Turn on LED
  41. try:
  42. while True:
  43. button1_state = GPIO.input(button1_pin)
  44. button2_state = GPIO.input(button2_pin)
  45. if button1_state == GPIO.LOW: # Button 1 pressed
  46. run_script('/home/pi/Desktop/MasterFiles/Theproject/Labtourmode.py')
  47. pygame.mixer.music.load('mode1.mp3')
  48. pygame.mixer.music.play()
  49. time.sleep(0.5) # Debounce delay
  50. if button2_state == GPIO.LOW: # Button 2 pressed
  51. run_script('/home/pi/Desktop/MasterFiles/Theproject/generalnew.py')
  52. pygame.mixer.music.load('mode2.mp3')
  53. pygame.mixer.music.play()
  54. time.sleep(0.5) # Debounce delay
  55. time.sleep(0.1) # Small delay to debounce the buttons
  56. finally:
  57. # Cleanup GPIO pins on exit
  58. if current_process is not None:
  59. current_process.terminate()
  60. GPIO.cleanup()
  61. logging.info("Button manager script terminated.")