So Easy MicroPython - Button Switch Vs. Debounce

by Yungger Chen in Circuits > Microcontrollers

3660 Views, 1 Favorites, 0 Comments

So Easy MicroPython - Button Switch Vs. Debounce

Header.png

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

Understanding Debounced Button

debounce.png

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.

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.

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

MyKitSwitch Pressed

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] ***

Wait for Button Switch Pressed Till Released

MyKitSwitch PressReleased

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] ***

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 😘 😘 !!