I am making a pumpkin pi for Halloween and am having trouble with the integration of the button; specifically, the is_held bit. It consists of 3 led lights that make up the candle (1 yellow flicker, 1 yellow "breathing", and 1 orange steady) and a red led light that fades in as the candle fades out, then pulses with creepy laugh. I have integrated the button to start everything, but when I hold the button down to stop it, nothing happens. I am pretty new to coding, so any help regarding my main issue or feedback in general is appreciated!
from gpiozero import PWMLED, Button
from gpiozero.tools import random_values
from signal import pause
from time import sleep
import subprocess
import random
led_flicker_yellow = PWMLED(17, frequency = 1500)
led_breath_yellow = PWMLED(18, frequency = 1500)
led_steady_orange = PWMLED(27, frequency = 1500)
led_red = PWMLED(24, frequency = 1500)
button = Button(2, hold_time = 2)
def candle_lights():
led_flicker_yellow.source = random_values()
led_flicker_yellow.souce_delay = random.uniform(0.05,0.1)
led_breath_yellow.pulse(15,10)
led_steady_orange.value = 0.20
def candle_out():
led_flicker_yellow.source = led_pulse_yellow
led_breath_yellow.pulse(0,3, n=1)
led_steady_orange.off()
def pumpkin_pi():
subprocess.Popen (["omxplayer", "-o", "alsa", "--loop", "/home/pi/Desktop/LED_PROJECTS/SoundEffects/candle.mp3"])
while True:
candle_lights()
sleep(300)
candle_out()
subprocess.Popen(["omxplayer", "-o", "alsa", "/home/pi/Desktop/LED_PROJECTS/SoundEffects/laugh.mp3"])
led_red.pulse(3,0,n=1)
sleep(3)
led_red.blink(0.03,0.03,n=35)
sleep(2)
candle_lights()
if button.is_held:
subprocess.call(["pkill", "omx"])
break
button.when_pressed = pumpkin_pi
Ok - so credit to thagrol on RPi forums, but here is the answer. Here I am controlling an LED light sequence that utilizes a while True loop with a button via python and gpiozero.
from gpiozero import PWMLED, Button
from time import sleep
from signal import pause
import threading
led = PWMLED(24)
button = Button(2, hold_time=2)
running = False
def pumpkin_pi_loop():
while running:
led.value = 0
sleep(1)
led.value = 0.5
sleep(1)
led.value = 1
sleep(1)
def button_press():
global running
if not running:
led.value = 1
sleep(3)
running = True
loop_thread = threading.Thread(target=pumpkin_pi_loop, daemon=True)
loop_thread.start()
else:
running = False
def button_hold():
global running
running = False
button.when_pressed = button_press
button.when_held = button_hold
pause()