The WEMOS S3 MINI PRO includes three onboard push buttons that can be used as digital inputs.
They are useful for learning:
-
- Pull-up and pull-down logic
-
- Controlling other onboard devices
| Button |
GPIO |
| Button 1 |
GPIO0 |
| Button 2 |
GPIO47 |
| Button 3 |
GPIO48 |
A digital input normally has two states:
HIGH
LOW
or:
1
0
from machine import Pin
button = Pin(47, Pin.IN)
Read the state using:
button.value()
4. Pull-Up and Pull-Down Resistors
Example using a pull-up:
from machine import Pin
button = Pin(47, Pin.IN, Pin.PULL_UP)
With active-low logic:
Released -> 1
Pressed -> 0
from machine import Pin
import time
button = Pin(47, Pin.IN, Pin.PULL_UP)
while True:
print(button.value())
time.sleep_ms(100)
while True:
if button.value() == 0:
print("Button pressed")
7. Switch Bouncing
A mechanical button may temporarily behave like:
0 -> 1 -> 0 -> 1 -> 0 -> 1
before settling.
This is called
switch bouncing.
8. Software Debouncing
from machine import Pin
import time
button = Pin(47, Pin.IN, Pin.PULL_UP)
while True:
if button.value() == 0:
print("Button pressed")
time.sleep_ms(50)
while button.value() == 0:
pass
9. Detecting a Single Press
from machine import Pin
import time
button = Pin(47, Pin.IN, Pin.PULL_UP)
previous_state = 1
while True:
current_state = button.value()
if previous_state == 1 and current_state == 0:
print("Button pressed")
previous_state = current_state
time.sleep_ms(10)
Buttons can be used to:
-
- Increase or decrease a value
from machine import Pin
import time
import s3minipro
button = Pin(47, Pin.IN, Pin.PULL_UP)
while True:
if button.value() == 0:
s3minipro.rgb_led(255, 0, 0)
else:
s3minipro.rgb_led(0, 0, 0)
time.sleep_ms(20)
12. Interrupts
from machine import Pin
button = Pin(47, Pin.IN, Pin.PULL_UP)
def button_pressed(pin):
print("Button pressed")
button.irq(
trigger=Pin.IRQ_FALLING,
handler=button_pressed
)
13. Avoiding Unnecessary Global Variables
def read_button():
state = button.value()
return state
14. Exercises
Possible topics:
-
- Detecting press and release
-
- Controlling LEDs with buttons
-
- Using buttons with the display
15. Possible Modifications
-
- Use one button to cycle through RGB colours
-
- Use two buttons to increase/decrease a value
-
- Move objects on the display
-
- Use interrupts instead of polling
16. Key Lesson
Physical Button Press
|
v
GPIO Input
|
v
MicroPython Program
|
v
Program Decision
|
v
LED / Display / Other Device