0

How to have micropython using an IRQ, count to a certain value then when equaling that certain value light a led

I am using micropython with Thonny and a Raspberry Pi Pico and not that it matters but my OS is Ubuntu 22.04 now for my question.

I have pin14 setup to react to a rising IRQ upon which time it prints "button pushed". Now how would I have those rising IRQ's caused by a button push increment to a given count and when that count is reached have pin13 go high to light an LED? I have pin14 setup and its working I have pin13 setup with a led and its working. But i am new and trying to tie together an IRQ and a Count up to (4) to make pin13 go high but it is eluding me. Coffee isnt helping....

Following is what I currently have...

import machine
import utime

button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
led = machine.Pin(13, machine.Pin.OUT)

count = 0

def button_handler(pin):
    utime.sleep_ms(100)
    if pin.value():
        print("button pushed")
        print(count)
        led.toggle()
        
button.irq(trigger=machine.Pin.IRQ_RISING, handler=button_handler)

-Brian-

Brian
  • 17
  • 1
  • 1
  • 2

1 Answers1

1

First, you need to tell your handler that you want to use the global variable "count". Then, you have to modify it when the interrupt occurs.

An interrupt service routine (ISR) should be as fast as possible, so don't put a delay in there.

You can also omit the check wether the button is pressed. The ISR is triggered because of the button press, so no need to verify that again.

def button_handler(pin):
    global count                # declare the count variable as global
    print("button pushed")
    count += 1              # modify the global counter
    print(count)
    if count > 3 :
        led.toggle()
        count = 0    # dont't forget to reset the counter!
Peter I.
  • 101
  • 6