Here's a really reduced example:
Code: Select all
from debounce import DebouncedSwitch
from machine import Pin
def mycallback(arg):
print("Switch toggled", arg)
sw = DebouncedSwitch(Pin(23, Pin.IN), mycallback, "dummy")
Code: Select all
from debounce import DebouncedSwitch
from machine import Pin
def mycallback(arg):
print("Switch toggled", arg)
sw = DebouncedSwitch(Pin(23, Pin.IN), mycallback, "dummy")
Yes, for this you'll have to pass a machine.Pin object to DebouncedSwitch as the first argument and change line 37 and 43 to pass a value for the trigger parameter (note that self._set_cb is an alias name for the irq method of your Pin instance here):
Code: Select all
self._set_cb(self._sw_cb if cb else None, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING)
Code: Select all
#
# inspired by: https://forum.micropython.org/viewtopic.php?t=1938#p10931
#
import micropython
try:
from machine import Timer
timer_init = lambda t, p, cb: t.init(period=p, callback=cb)
except ImportError:
from pyb import Timer
timer_init = lambda t, p, cb: t.init(freq=1000 // p, callback=cb)
# uncomment when debugging callback problems
#micropython.alloc_emergency_exception_buf(100)
class DebouncedSwitch:
def __init__(self, sw, cb, arg=None, delay=50, tid=4):
self.sw = sw
# Create references to bound methods beforehand
# http://docs.micropython.org/en/latest/pyboard/library/micropython.html#micropython.schedule
self._sw_cb = self.sw_cb
self._tim_cb = self.tim_cb
self._set_cb = getattr(sw, 'callback', None) or sw.irq
self.delay = delay
self._last = -1
self.tim = Timer(tid)
self.callback(cb, arg)
def sw_cb(self, pin=None):
self._set_cb(None)
self._last = self.sw()
timer_init(self.tim, self.delay, self._tim_cb)
def tim_cb(self, tim):
tim.deinit()
if self.sw() == self._last:
self._last = -1
micropython.schedule(self.cb, self.arg)
self._set_cb(self._sw_cb if self.cb else None)
def callback(self, cb, arg=None):
self.tim.deinit()
self.cb = cb
self.arg = arg
self._set_cb(self._sw_cb if cb else None)
def test_pyb(ledno=1):
import pyb
sw = pyb.Switch()
led = pyb.LED(ledno)
return DebouncedSwitch(sw, lambda l: l.toggle(), led)
def test_machine(swpin=2, ledpin=16):
from machine import Pin
sw = Pin(swpin, Pin.IN)
led = Pin(ledpin, Pin.OUT)
return DebouncedSwitch(sw, lambda l: l.value(not l.value()), led)
Thank you anyway, this code is working but as expected there is a huge delay sometimes.SpotlightKid wrote: ↑Sun Feb 25, 2018 1:46 pmSorry, I overlooked the "if self.sw():" statement in line 35. The code will not work for handling callbacks on the rising and falling edge as is. I'll put a version below that does but it doesn't work very well, due to timing issues. The callback for the rising edge is fired with a very noticable delay. I guess this is due to the use of micropython.schedule.
So I recommend using another debouncing approach in your case. Unfortunately I don't have the time at the moment to offer a solution.