Introduction: So Easy MicroPython - Button Switch Vs. Debounce

*** Just add 2~3 lines, then you will be no problem to correctly handle the button switch to control your devices ***

Step 1: Understanding Debounced Button

It is sometimes so annoyed to avoid incorrect signal handle when you push a button. Two metal parts of a switch come together, you may think the contact is made instantly but not quite correct actually. That because when you physically press a normal pushbutton, two pieces of metal come into contact with each other. If these two tiny sheets of metal aren’t perfectly flat or perfectly aligned (and they’re not) then the contacts torturously hitting and rebounding, bouncing for milliseconds before finally settling into a stable state.

To avoid the switch bouncing trouble, somebody fix from the hardware thinking, but the easier way is to let program to handle them, BUT how to do it, that is this MyKitSwitch library designed for.

Step 2: Upload Libraries to Your MCU

First, You need to upload the MyKitSwitch library to your MCU board.

*** If you have no idea how to upload File to your MCU, read my another article "So Easy MicroPython - ESP8266/ESP32 MCU File Management" first.

Step 3: Example 1:Detect the Status of a Switch, Pressed ? Released ?

from machine import Pin

from MyKitSwitch import mySwitch

led = Pin(2, Pin.OUT)

my_sw = mySwitch(12)

while True:

if sw.pressed() and sw.getStatus() == 1:

led.value(0)

print("Button pressed and LED value is ", led.value())


if sw.released() and sw.getStatus() == 0:

led.value(1)

print("Button released and LED value is ", led.value())


time.sleep_ms(100)


*** You can download the source code [HERE] ***

Step 4: Wait for Button Switch Pressed Till Released

from machine import Pin

from MyKitSwitch import mySwitch

led = Pin(2, Pin.OUT)

sw = mySwitch(12)

while True:

if sw.pressReleased():

led.value(not led.value())

print("Pressed period in ms is ", sw.getPressed())

*** You can download the source code [HERE] ***

Step 5: That's So Easy, Hope to Help a Little Bit !

Posted by Yungger

If it help you, and want to give some encouragement, just go HERE 😘 😘 !!