Menu Close

Button Controlled Relay using Raspberry Pi Pico

The objective of this project is to control a relay connected to the Raspberry Pi Pico using a push-button. The relay toggles ON and OFF each time the button is pressed. This demonstrates how digital input (button press) can be used to change the state of a digital output (relay) in a microcontroller environment using MicroPython. It also introduces the concept of edge detection and debouncing in button handling.

Connection:

Code:

from machine import Pin
import time
button = Pin(4, Pin.IN, Pin.PULL_UP)
relay = Pin(16, Pin.OUT)
relay_state = False
last_button_state = 1
print("Toggle relay with button...")
while True:
current_state = button.value()
if last_button_state == 1 and current_state == 0:  
    relay_state = not relay_state  
    relay.value(relay_state)  
    print("Relay ON" if relay_state else "Relay OFF")  
    time.sleep(0.2)  

last_button_state = current_state  
time.sleep(0.01)

Download Code:

Results:
When the code is uploaded and running, pressing the push-button once will toggle the relay ON, and pressing it again will turn the relay OFF. The relay switches each time a button press is detected. The serial monitor prints the current relay state (Relay ON or Relay OFF) for feedback. This experiment confirms the successful use of GPIO input with debouncing to toggle digital output in embedded systems.

Leave a Reply