LED Control Using Push Button with Raspberry Pi Pico: Pressed and Released, Long Pressed
Introduction
LED Control Using Push Button with Raspberry Pi Pico: Pressed and Released, Long Pressed- The Raspberry Pi Pico stands out in the realm of DIY electronics as a robust microcontroller board, offering vast potential for a range of projects. A key element often incorporated into these projects is the push button, renowned for its simplicity and effectiveness in user interaction. In this article, we will guide you through the steps of creating a basic circuit and programming for LED control using Push Button with the Raspberry Pi Pico.
We will delve into essential concepts including button debouncing, which ensures accurate input recognition by eliminating false triggers caused by electrical noise. Additionally, we’ll discuss the implementation of long and short-press functionalities, enabling more nuanced control and interaction within projects.
By the end of this guide, readers will gain a solid understanding of how to effectively utilize a push button with the Raspberry Pi Pico, enhancing their projects with reliable and responsive user inputs.
Raspberry Pi Pico Pinout:
What is a Push Button?
A push button, frequently referred to as a momentary switch, stands as a cornerstone in the realm of electronic components due to its simplicity and versatility. This type of switch is mechanically designed to facilitate user interaction with electronic devices. Its most defining characteristic is its temporary engagement feature: the push button remains in the ‘ON’ state exclusively while being actively pressed. As soon as the pressure is removed, it automatically reverts to its default ‘OFF’ state.
The mechanics of a push button are straightforward yet ingeniously effective. Internally, the button comprises a set of contacts that, when pressed, complete an electrical circuit. This action allows current to flow through the circuit, thereby enabling control or activation of a connected device or system. Upon release, these contacts separate, interrupting the current flow and effectively ceasing the action or command previously initiated.
Push Button with Raspberry Pi Pico Circuit Diagram:
LED Connection: The anode of the LED is connected to GPIO pin 28 (labeled “GP28”) on the Raspberry Pi Pico. A current-limiting resistor is in series with the LED to prevent it from drawing too much current when it’s turned on. The cathode of the LED is connected to the ground (GND).
Connect one terminal of the button to a 10k ohm resistor.
From the junction between the button and the resistor, connect a wire to GPIO 19 (GP19) on the Raspberry Pi Pico. This will be the signal wire.
Connect the other terminal of the resistor to the 3.3V (3V3) pin on the Raspberry Pi Pico.
Connect the second terminal of the button directly to the ground (GND) pin on the Raspberry Pi Pico.
When the button is not pressed, the GPIO pin 19 maintains a HIGH state due to the pull-up resistor linked to 3.3V. Pressing the button causes GPIO pin 19 to switch to a LOW state as it creates a direct path to GND, circumventing the resistor. The Raspberry Pi Pico can detect this shift in voltage to manage the LED’s behavior. This arrangement, which incorporates the resistor alongside the push button, effectively establishes a pull-up resistor setup. It guarantees a consistent HIGH signal when the button is not pressed and a distinct LOW signal upon pressing it.
Example #1: LED Control with Button Pressed and released:
Now that we have the push button and LED connected, let’s write some code to interact with them. We will be using MicroPython, a lightweight version of Python specifically designed for microcontrollers.
First, we need to import the necessary libraries:
1 2 |
import machine import time |
Next, we will define the GPIO pins to which the push button and LED are connected:
1 2 |
button_pin = machine.Pin(19, machine.Pin.IN) led_pin = machine.Pin(28, machine.Pin.OUT) |
In this example, we have connected the button to GPIO pin 19 and the LED to GPIO pin 28.
However, if you don’t use a pull-up or pull-down resistor, you will need to use the machine.Pin.PULL_UP or machine.Pin.PULL_DOWN parameter like this:
1 |
button_pin = machine.Pin(19, machine.Pin.IN, machine.Pin.PULL_UP) |
Now, let’s write a simple program. When the button is pressed, the LED will turn on, and when the button is released, the LED will turn off:
1 2 3 4 5 6 |
while True: if button_pin.value() == 0: led_pin.value(1) else: led_pin.value(0) time.sleep(0.1) |
This code continuously checks the value of button_pin. If the value is 0, it means the button is pressed. If the value is 1, it means the button is released. We also add a small delay of 0.1 seconds using the time.sleep() function to avoid rapid state changes due to button bounce.
Output:
after releasing the button
Example #2: Raspberry Pi Pico Toggle LED Using Push Button:
In this example, we demonstrate a simple yet effective way to control an LED using a push button with the Raspberry Pi Pico microcontroller. This basic project is an excellent starting point for beginners in electronics and programming, as it combines hardware interaction with software control in a straightforward manner.
We utilize MicroPython, a lean and efficient implementation of Python 3 that’s optimized for microcontrollers like the Raspberry Pi Pico. This makes it possible to execute high-level Python scripts in a hardware-oriented environment.
Our setup involves connecting an LED and a push button to the GPIO pins of the Raspberry Pi Pico. The code continuously monitors the state of the push button. When the button is pressed, the state of the LED is toggled – if the LED is off, it turns on, and vice versa. We also implement a debouncing technique to ensure stable operation by introducing brief delays, which helps in filtering out the noise or false triggers due to the mechanical nature of the push button.
This example is a practical demonstration of handling input (push button) and output (LED) with the Raspberry Pi Pico, showcasing the fundamental concepts of digital signals and control logic in microcontroller programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from machine import Pin import time button = Pin(19, Pin.IN) led = Pin(28, Pin.OUT) state = False # False means that the LED is currently off while True: if button.value() == 0: # Button press detected time.sleep(0.1) # Debounce delay if state: led.value(0) state = False else: led.value(1) state = True while button.value() == 0: # Wait here until the button is released pass time.sleep(0.1) # Short delay to prevent high CPU usage |
output:
What is Button Debouncing?
Button debouncing is a crucial concept in digital electronics, particularly when dealing with mechanical buttons or switches. When a button is pressed, it doesn’t simply change from an ‘off’ to an ‘on’ state instantaneously. Instead, it may momentarily ‘bounce’ between states. This bouncing can lead to multiple signals being detected for what is actually a single press. To address this, we implement button debouncing.
Button debouncing ensures that only a single signal is registered for each button press, regardless of any minor fluctuations in the button’s state during actuation. This is typically achieved by introducing a small delay after the initial detection of a button press. During this delay, any further changes in the button’s state are ignored, allowing time for the bouncing to subside and ensuring that only one signal is registered.
Below is a simple Python code snippet demonstrating the button debouncing. This example is designed for a Raspberry Pi Pico or similar microcontroller running MicroPython. When the button is pressed, the code prints a message to the console indicating a ‘Button Pressed’ event, while implementing a debouncing mechanism.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from machine import Pin import time button = Pin(19, Pin.IN) debounce_delay = 0.1 while True: if button.value() == 0: # Button press detected time.sleep(debounce_delay) # Debounce delay if button.value() == 0: # Confirm button is still pressed print("Button Pressed") while button.value() == 0: pass # Wait for the button to be released print("Button Released") # Add this line to indicate button release |
Code explanation:
from machine import Pin
import time
These lines import necessary modules. machine is used for accessing the hardware features of the microcontroller, specifically the GPIO (General Purpose Input/Output) pins. time is used for handling delays.
button = Pin(19, Pin.IN)
This line sets up a GPIO pin (pin 19 in this case) as an input pin, which is used to read the state of the button.
debounce_delay = 0.1
Debouncing is essential for handling mechanical buttons. When a button is pressed or released, it doesn’t instantly change states but rather “bounces” between states for a brief period. This variable sets a delay of 0.1 seconds to mitigate the bouncing effect.
while True:
This is an infinite loop that continuously checks the state of the button.
if button.value() == 0:
The button’s state is checked here. If the button is pressed, the GPIO pin reads 0 (assuming the button is configured to pull the pin to ground when pressed).
time.sleep(debounce_delay)
After detecting a button press, the program waits for the specified debounce delay to filter out any false positives due to the bouncing.
if button.value() == 0:
After the debounce delay, the button’s state is checked again to confirm that it is indeed still pressed.
print(“Button Pressed”)
If the button press is confirmed, the program prints “Button Pressed” to the console.
while button.value() == 0:
   pass
This loop waits until the button is released. It ensures that the program doesn’t register a new press until after the current press is released.
Long Press and Short Press
In this example, we explore a slightly more advanced application using the Raspberry Pi Pico, demonstrating how to toggle an LED on and off based on the duration of a button press. Specifically, the code is designed to differentiate between a short press and a long press of the button, toggling the LED only on a long press.
The code is written in MicroPython, a variant of Python tailored for microcontrollers like the Raspberry Pi Pico, making it ideal for interacting with hardware components in a simple yet powerful way.
Example: Controlling LED using Long Press with Raspberry Pi Pico:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
from machine import Pin import time button = Pin(19, Pin.IN) # Assuming internal pull-up led = Pin(28, Pin.OUT) button_pressed_time = None led_state = False # Main loop while True: if button.value() == 0: # Button is pressed if button_pressed_time is None: button_pressed_time = time.ticks_ms() # Record the time when button is first pressed else: if button_pressed_time is not None: button_released_time = time.ticks_ms() # Record the time when button is released button_press_duration = button_released_time - button_pressed_time if button_press_duration > 1000: # Check if it's a long press (e.g., longer than 1000 ms) led_state = not led_state # Toggle LED state led.value(led_state) # Update LED state # Reset the button press time button_pressed_time = None time.sleep(0.1) # Short delay to prevent high CPU usage |
Code explanation:
from machine import Pin
import time
button = Pin(19, Pin.IN)Â # Button connected to GPIO pin 19
led = Pin(28, Pin.OUT)Â Â Â # LED connected to GPIO pin 28
This part initializes the GPIO pins. Pin 19 is set as an input to read the button’s state, and pin 28 is configured as an output to control the LED. It’s assumed that the button uses the Pi Pico’s internal pull-up resistor.
button_pressed_time = None
led_state = False
Here, button_pressed_time will store the time at which the button was pressed, and led_state is a boolean indicating the current state of the LED (on or off).
while True:
The while True loop allows the program to continuously check the button’s state.
if button.value() == 0:Â # Button is pressed
   if button_pressed_time is None:
       button_pressed_time = time.ticks_ms()
This block checks if the button is pressed (read as 0). If it’s the first detection of the press, it records the current time in milliseconds.
else:
   if button_pressed_time is not None:
       button_released_time = time.ticks_ms()
       button_press_duration = button_released_time – button_pressed_time
When the button is released, it captures the release time and calculates the duration of the press.
if button_press_duration > 1000:Â # Long press detected
   led_state = not led_state
   led.value(led_state)
If the duration is longer than a specified threshold (1000 ms in this case), it’s considered a long press. The LED’s state is then toggled.
button_pressed_time = None
After handling the button press, the button_pressed_time is reset, preparing for the next press detection.
time.sleep(0.1)
This small delay is added to reduce CPU usage, preventing the loop from running too quickly.
Output:
Conclusion
Using a push button with Raspberry Pi Pico opens up a world of possibilities for creating interactive projects. By implementing button debouncing, long press, and short press detection, we can enhance the functionality and user experience of our projects. Whether you’re building a home automation system or a gaming console, understanding how to work with buttons is a valuable skill.
Remember to always test your code and experiment with different debounce delays and press durations to fine-tune the behavior of your buttons. With Raspberry Pi Pico and a push button, you have the power to create innovative and engaging projects.
Related Articles:
How to use external LED with Raspberry Pi Pico
Creating LED Animations with Raspberry Pi Pico: A Step-by-Step Guide
Raspberry Pi Pico Install UF2 MicroPython Firmware and LED Blink Example