*** Just add 2~3 lines, then you will have no trouble to correctly handle the annoyed switch debouncing and control your devices ***
Step 1: Understanding the switch debouncing
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 library to your MCU
First, download the library by its link and upload it to your MCU !
- MyKitSwitch : A basic library for a switch button to handle the event
*** If no idea how to upload files to your MCU board, you can read my other article “So Easy — ESP8266/ESP32 File Management” first. ***
Step 3: Lets’ learn some examples
The following examples, basically need to include the following statements onto the top of your script:
import utime as time
from machine import Pin
from MyKitSwitch import mySwitch
led = Pin(2, Pin.OUT) # ESP8266 built-in LED
led.value(1) # for ESP8266, 0/low is on, 1/high is off
sw = mySwitch(12) # D6: ESP8266
Example 1:Detect if the button pressed ?
while True:
if sw.pressed():
led.value(not led.value()) # LED ON/OFF
time.sleep_ms(100)
Example 2:Detect if the button released ?
while True:
if sw.released():
led.value(1)
else:
led.value(0)
time.sleep_ms(100)
Example 3:Detect if the button pressed and then released ?
while True:
if sw.pressReleased():
led.value(not led.value()) # LED ON/OFF
time.sleep_ms(100)
Example 4:Detect the moment as the button pressed
while sw.counter < 5: # only test 5 times
if sw.atPressed():
led.value(not led.value()) # LED ON/OFF
time.sleep_ms(100)
Example 5:Detect the moment as the button released
while sw.counter < 5: # only test 5 times
if sw.atReleased():
led.value(not led.value()) # LED ON/OFF
time.sleep_ms(100)
That’s all, so easy right ? Hope this helps !
Posted by Yungger
If it really help you, you are welcome to clap your hands clicking on top-left icon, or want to buy me a coffee to encourage me to write more, I thank you too 😘 😘 !!