Page 1 of 1

Loop flashing LED with button stop

Posted: Sat Oct 23, 2021 7:52 pm
by soggycashew
Hello, I needed to def instance that when triggered an LED would flash on/off repeatedly until a button would be pressed to stop it. Can someone give me an example please?

Thanks,

Re: Loop flashing LED with button stop

Posted: Sun Oct 24, 2021 7:56 pm
by soggycashew
I got it.....Shew!

Code: Select all

from machine import Pin, Timer
import utime

micro_switch = machine.Pin(22, machine.Pin.IN, machine.Pin.PULL_DOWN)
btn_reset = machine.Pin(17, machine.Pin.IN, machine.Pin.PULL_DOWN)
led_red = machine.Pin(21, machine.Pin.OUT)

tim = Timer()
top_count = 0 
bottom_count = 0

def blink(timer):
    global led_red
    led_red.toggle()

while True:
    if micro_switch.value():
        top_count += 1
        bottom_count = 0
        if top_count == 1:
            tim.init(freq=2, mode=Timer.PERIODIC, callback=blink)
        
    if btn_reset.value():
        bottom_count += 1
        top_count = 0
        if bottom_count == 1:
            tim.deinit()
            led_red.value(0)