0

I currently have this MicroPython code running on a Pyboard v1.1:

import pyb

def toggle_led():
    pyb.LED(3).toggle()

sw = pyb.Switch()
sw.callback(toggle_led)

However, this setup is susceptible to contact bounce.

I tried adding up to pyb.delay(500) to no avail.

Is there an elegant way to remedy USR switch bounce on the Pyboard?

dda
  • 6,030
  • 2
  • 25
  • 34
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102

1 Answers1

1

Here is what worked for me. I got my inspiration from a procedure described in a post on the MicroPython forum.

import pyb

def toggle_led():
    pyb.disable_irq()
    pyb.delay(100)
    if sw.value(): pyb.LED(3).toggle()
    pyb.enable_irq()

sw = pyb.Switch()
sw.callback(toggle_led)

Better: uasyncio

There is a much better way without a need for interrupts. Here is a link to the buttons example in Peter Hinch's excellent uasyncio tutorial.

Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
  • 1
    You should probably use [micropython.schedule](http://docs.micropython.org/en/latest/pyboard/library/micropython.html#micropython.schedule) to have the `LED.toggle` method called outside of the IRQ handler. Because you can't use bound methods directly with `schedule` and schedule always passes its second arg to the scheduled function, you have to make a little wrapper outside of your interrupt function (e.g. `led_toggle = lambda led: led.toggle()` and then schedule that: `micropython.schedule(led_toggle, led)`. – Chris Arndt Nov 26 '17 at 19:17
  • @ChrisArndt I read the [micropython.schedule](http://docs.micropython.org/en/latest/pyboard/library/micropython.html#micropython.schedule) documentation, but it still remains pretty etheric to me; more so because above code does what it needs to do. Perhaps you should write a full answer with a working code example. Cheers. – Serge Stroobandt Nov 26 '17 at 20:47
  • @ChrisArndt Someone posted a solution involving `micropython.schedule` [over here](https://forum.micropython.org/viewtopic.php?f=11&t=1938&p=23453#p23472). – Serge Stroobandt Nov 26 '17 at 22:28
  • That was me! ;) – Chris Arndt Nov 27 '17 at 21:40