0

so i have written this code in my nano editor. the first button which is gpio(21) is functioning properly. the first button (21) is turning the LED's on and off. as for the second button i would like it to change the speed of the LED's flashing once you hold it down. here is the code i have written so far. please help as i have been stuck on this for 2 days now. thank you!!


from gpiozero import LED, Button
from signal import signal, SIGTERM, SIGHUP, pause
from time import sleep


blink_on = False
interval = 0.5


def safe_exit(signum, frame):
    exit(1)


def go_blink():
    global blink_on

    if blink_on:
        led1.off()
        led2.off()
        led3.off()
    else:
        led1.blink(0.5, 0.5)
        sleep(0.5)
        led2.blink(0.5, 0.5)
        sleep(0.5)
        led3.blink(0.5, 0.5)

    blink_on = not blink_on


led1 = LED(13)
led2 = LED(19)
led3 = LED(26)
button = Button(20)
button = Button(21)
time_on = 1
time_off = 2


try:
    button.when_pressed = go_blink
    signal(SIGTERM, safe_exit)
    signal(SIGHUP, safe_exit)
    led1.blink(time_on, time_off)
    sleep(time_on)
    led2.blink(time_on, time_off)
    sleep(time_on)
    led3.blink(time_on, time_off)

    pause()


except KeyboardInterrupt:
    pass


finally:
    led1.close()
    led2.close()
    led3.close()

i have tried this code but i can not seem to think how to add the second function to the second button gpio (20). here is my code.


from gpiozero import LED, Button
from signal import signal, SIGTERM, SIGHUP, pause
from time import sleep


blink_on = False
interval = 0.5


def safe_exit(signum, frame):
    exit(1)


def go_blink():
    global blink_on

    if blink_on:
        led1.off()
        led2.off()
        led3.off()
    else:
        led1.blink(0.5, 0.5)
        sleep(0.5)
        led2.blink(0.5, 0.5)
        sleep(0.5)
        led3.blink(0.5, 0.5)

    blink_on = not blink_on


led1 = LED(13)
led2 = LED(19)
led3 = LED(26)
button = Button(20)
button = Button(21)
time_on = 1
time_off = 2


try:
    button.when_pressed = go_blink
    signal(SIGTERM, safe_exit)
    signal(SIGHUP, safe_exit)
    led1.blink(time_on, time_off)
    sleep(time_on)
    led2.blink(time_on, time_off)
    sleep(time_on)
    led3.blink(time_on, time_off)

    pause()


except KeyboardInterrupt:
    pass


finally:
    led1.close()
    led2.close()
    led3.close()

i have also been provided a pseudo code to use for inspiration. maybe i am missing something but here it is.

control_speed_function (for Part 4, activated by button hold): use global designation for blink_interval(s) variable(s)

if blink_interval is long: set blink_interval variable(s) short

otherwise: set blink_interval variable(s) long

if LEDs are blinking: call turn_LEDs_off function call turn_LEDs_on function

0 Answers0