Loop flashing LED with button stop

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
soggycashew
Posts: 55
Joined: Sat Sep 18, 2021 10:21 pm

Loop flashing LED with button stop

Post by soggycashew » Sat Oct 23, 2021 7:52 pm

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,

soggycashew
Posts: 55
Joined: Sat Sep 18, 2021 10:21 pm

Re: Loop flashing LED with button stop

Post by soggycashew » Sun Oct 24, 2021 7:56 pm

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)

Post Reply