I have a button, that is connected between GPIO14 (D5 pin on Wemos D1 mini) and ground. I need to count number of button presses.
First I tried to trigger pin change interrupt only on falling edge, but this code often was triggered on button release. With the code below I an handling both rising and falling edge, and applying 50ms filter to debounce button pins.
Code: Select all
import machine
import utime
pin = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
value = 0
last_value_change_ms = 0
def callback(p):
global value
global last_value_change_ms
pin_state = p.value()
cur_time = utime.ticks_ms()
diff = cur_time - last_value_change_ms
if diff > 500:
print("")
#print("CurTime={}, LastChange={}, Diff={}, State={}".format(cur_time, last_value_change_ms, diff, p.value()))
if diff > 50:
if pin_state == 0:
value += 1
print('pin change', value)
else:
print("Button up")
else:
print("Debouncing...", diff)
last_value_change_ms = cur_time
pin.irq(trigger=machine.Pin.IRQ_FALLING | machine.Pin.IRQ_RISING, handler=callback)
prev_value = value
while True:
new_value = value
if new_value != prev_value:
print("Value Changed:", value)
prev_value = value
Code: Select all
pin change 8
Value Changed: 8
pin change 9
Debouncing... 1
Debouncing... 0
Debouncing... 1
Debouncing... 0
Value Changed: 9
Does micropython firmware provide an information about why pin change interrupt has been triggered? How can I make it more reliable?