ESP32 MicroPython Button

This tutorial instructs you how to use button with ESP32, using MicroPython.

Buttons can be a bit tricky when used with ESP32, especially for those new to electronics. Let's break down the basics and avoid some common pitfalls.

Two Key Issues to Address:

By understanding these two issues and implementing the appropriate solutions, you'll be well-equipped to use buttons effectively with your ESP32 projects.

ESP32 MicroPython button

Hardware Preparation

1×ESP-WROOM-32 Dev Module
1×USB Cable Type-C
1×Breadboard-mount Button with Cap
1×Breadboard-mount Button Kit
1×Panel-mount Button
1×Breadboard
1×Jumper Wires
1×(Recommended) Screw Terminal Expansion Board for ESP32

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Button

Push buttons are switches that close when pressed and open when released. They're also known as tactile buttons or momentary switches. There are two main types of push buttons:

  • PCB-mount push buttons: Designed for mounting on breadboards or printed circuit boards.
  • Panel-mount push buttons: Intended for mounting on panels or enclosures.
ESP32 MicroPython Push button

Pinout

The PCB-mount buttons usually have four pins.

Button Pinout

Although a button has four pins, only two are used. This is because the pins are connected internally in pairs. There are four possible ways to connect a button to a PCB, but two of these configurations are symmetrical.

How To Use Button

Why are only two pins used on a button that has four?

⇒ To ensure secure mounting on the PCB (printed circuit board) and to withstand pressing force.

The panel-mount buttons usually have two pins.

two-pin push button Pinout
image source: diyables.io

How It Works

  • When the button is not pressed, pin A and pin B are not connected.
  • When the button is pressed, pin A and pin B are connected.
How Button Works

ESP32 - Button

One button pin attaches to VCC or GND, while the other pin connects to a pin on the ESP32. We can determine if the button is pressed by checking the input pin status on the ESP32.

Button State and Pressing State

The behavior of an ESP32 pin when a button is pressed or released depends on how the button is connected and how the pin is configured.

Two Common Connection Methods:

  • Pull-Down Resistor:
    • Connect one side of the button to VCC (power) and the other to an ESP32 pin.
    • Use either an internal pull-down resistor or an external pull-down resistor to the ESP32 pin.
    • When the button is pressed, the ESP32 pin reads HIGH. When the button is not pressed, it reads LOW.
  • Pull-Up Resistor:
    • Connect one side of the button to GND (ground) and the other to an ESP32 pin.
    • Use either a built-in pull-up resistor or an external resistor to the ESP32 pin.
    • When the button is pressed, the ESP32 pin reads LOW. When the button is not pressed, it reads HIGH.

    Why Use a Pull-Up or Pull-Down Resistor?

    Without a resistor, the ESP32 pin can have an unstable state when the button is not pressed. This can lead to incorrect readings. Using a pull-up or pull-down resistor ensures a stable state.

    Recommended Configuration:

    For beginners, we recommend using a built-in pull-up resistor on the ESP32 pin. This simplifies the wiring and eliminates the need for an external resistor. You can configure this in your MicroPython code using button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP).

    Remember: Using a pull-up or pull-down resistor is essential for reliable button readings on an ESP32.

    ※ NOTE THAT:

    The ESP32 pins GPIO34, GPIO35, GPIO36 (VP), and GPIO39 (VN) do not support internal pull-up or pull-down resistors. For these pins, you must use an external pull-up or pull-down resistor.

Wiring Diagram

  • How to connect ESP32 and button using breadboard
The wiring diagram between ESP32 MicroPython Button

This image is created using Fritzing. Click to enlarge image

The wiring diagram between ESP32 MicroPython two-pin push button

This image is created using Fritzing. Click to enlarge image

How To Program For Button

  • Sets up an ESP32 pin to work as an input with a built-in pull-up resistor, using the pinMode() function.
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
  • Read the ESP32 pin state.
button_state = button.value()

※ NOTE THAT:

There are two usual cases:

  • The first: If the input is HIGH, act. If the input is LOW, do the opposite.
  • The second: If the input shifts from LOW to HIGH (or from HIGH to LOW), act.

Based on what we want, we choose one of these methods. For instance, when using a button to control the LED:

  • If we desire the light to turn ON when the button is pressed and turn OFF when released, we should pick the first case.
  • If our aim is for the light to switch ON and OFF each time the button is tapped, select the second case.

ESP32 MicroPython Code - Reading the state of button

from machine import Pin import time BUTTON_PIN = 21 # The ESP32 pin GPIO21 connected to the button # Set up the button pin. The Pin.PULL_UP enables the internal pull-up resistor. button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP) while True: # Read the state of the button button_state = button.value() # Print the button's state print(button_state) # Wait for half a second before reading the button again time.sleep(0.5)

Detailed Instructions

Here’s instructions on how to set up and run your MicroPython code on the ESP32 using Thonny IDE:

  • Make sure Thonny IDE is installed on your computer.
  • Confirm that MicroPython firmware is loaded on your ESP32 board.
  • If this is your first time using an ESP32 with MicroPython, check out the ESP32 MicroPython Getting Started guide for step-by-step instructions.
  • Follow the provided diagram to connect the button to the ESP32.
  • Use a USB cable to connect the ESP32 board to your computer.
  • Open Thonny IDE on your computer.
  • In Thonny IDE, go to Tools Options.
  • Under the Interpreter tab, choose MicroPython (ESP32) from the dropdown menu.
  • Make sure the correct port is selected. Thonny IDE usually detects it automatically, but you might need to select it manually (like COM12 on Windows or /dev/ttyACM0 on Linux).
  • Copy the provided MicroPython code and paste it into Thonny's editor.
  • Save the code to your ESP32 by:
    • Clicking the Save button or pressing Ctrl+S.
    • In the save dialog, choose MicroPython device.
    • Name the file main.py.
  • Click the green Run button (or press F5) to execute the script.
  • Press the green Run button or F5 to execute your script.
  • Check out the message in the Shell at the bottom of Thonny IDE.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot 1 1 1 0 0 0 0 0 0 1 1 1
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

1 indicates unpressed, 0 indicates pressed.

Code Explanation

You can see the explanation in the comments part of the ESP32 MicroPython code that was given before.

ESP32 MicroPython Code - Detecting the button's press and release event

Let's change the code so it can recognize when buttons are pressed and released

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-button """ from machine import Pin import time BUTTON_PIN = 21 # The ESP32 pin GPIO21 connected to the button # Setup the button pin. The Pin.PULL_UP enables the internal pull-up resistor. button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP) # Initialize the previous state of the button prev_button_state = 1 # Assuming the button is unpressed initially while True: # Read the current state of the button button_state = button.value() # Check if button was released if prev_button_state == 0 and button_state == 1: print("The button is released") # Check if button was pressed if prev_button_state == 1 and button_state == 0: print("The button is pressed") # Save the current state as the previous state for the next loop iteration prev_button_state = button_state

Detailed Instructions

  • Copy the code above and insert it into Thonny IDE.
  • Click the green Run button or press F5 to start the script.
  • Click the button and then release it.
  • Look at the message in the Shell at the bottom of Thonny.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot The button is pressed The button is released
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

※ NOTE THAT:

Occasionally, if you press a button once, it might display multiple presses in Thonny's Shell. This frequent problem is known as chattering phenomenon, or bouncing. You can learn more and find a solution in the ESP32 MicroPython Button Debounce tutorial.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!