HOW to Control Button with ESP32
Overview
In this kit, there is a Keyestudio single-channel button module, which mainly uses a tact switch and comes with a yellow button cap.
In previous lessons, we learned how to make the pins of our single-chip microcomputer output a high level or low level. In this experiment, we will read the high level (3.3V) and low level (0V).
We can determine whether the button on the sensor is pressed by reading the high and low level of the S terminal on the sensor.
Working Principle
The button module has four pins. The pin 1 is connected to the pin 3 and the pin 2 is linked with the pin 4. When the button is not pressed, they are disconnected. Yet, when the button is pressed, they are connected. If the button is released, the signal end is high level.
Components
|
|
|
|
|
---|---|---|---|---|
ESP32 Board*1 |
ESP32 Expansion Board*1 |
Keyestudio DIY Button Module*1 |
3P Dupont Wire*1 |
Micro USB Cable*1 |
Connection Diagram
Test Code
from machine import Pin
import time
button = Pin(15, Pin.IN, Pin.PULL_UP)
while True:
if button.value() == 0:
print("You pressed the button!") #Press to print the corresponding information.
else:
print("You loosen the button!")
time.sleep(0.1) #delay 0.1s
Code Explanation
button = Pin(15, Pin.IN, Pin.PULL_UP), we define the pin of the button as GP15 and set to PULL-UP mode
We can use button = Pin(15, Pin.IN) to set INPUT mode, at this time, the pins are in high resistance state.
1). button.value(), read levels of buttons. Function returns High or Low
2). if…else… sentence, when the logic judge is TRUE, the code under the if will be activated; otherwise, the code udder the else will be activated.
3). When ESP32 detects the button pressed, the signal end is low level (GP 15 is low level). button.value() is 0. If the ESP32 detects the button unpressed, button.value() is 1 and else sentence will be activated.
Test Result
Connect the wires according to the experimental wiring diagram and power on. Click “Run current script”, the code starts executing, the string will be displayed on the ”Shell“ window.
When the button is pressed, the ”Shell“ window will show“You pressed the button!”;when the button is released,the ”Shell“ window will show “Loosen the button”; as shown below. Press “Ctrl+C”or click“Stop/Restart backend”to exit the program.