0
0
Iot-protocolsHow-ToBeginner · 3 min read

How to Blink LED on Raspberry Pi Pico: Simple Python Guide

To blink an LED on Raspberry Pi Pico, use the machine.Pin class to control the LED pin and toggle it on and off with delays using time.sleep. Write a loop that switches the LED state every half second to create the blinking effect.
📐

Syntax

The basic syntax to blink an LED on Raspberry Pi Pico involves these parts:

  • machine.Pin(pin_number, machine.Pin.OUT): sets the pin as output to control the LED.
  • pin.value(1) or pin.value(0): turns the LED on or off.
  • time.sleep(seconds): pauses the program to keep the LED on or off for a set time.
python
import machine
import time

led = machine.Pin(25, machine.Pin.OUT)  # Pin 25 controls the onboard LED

while True:
    led.value(1)  # Turn LED on
    time.sleep(0.5)  # Wait for 0.5 seconds
    led.value(0)  # Turn LED off
    time.sleep(0.5)  # Wait for 0.5 seconds
💻

Example

This example blinks the onboard LED on Raspberry Pi Pico every half second. It shows how to set up the pin and use a loop to toggle the LED state with delays.

python
import machine
import time

led = machine.Pin(25, machine.Pin.OUT)  # Onboard LED pin

for _ in range(10):  # Blink 10 times
    led.value(1)  # LED on
    time.sleep(0.5)  # Wait 0.5 seconds
    led.value(0)  # LED off
    time.sleep(0.5)  # Wait 0.5 seconds

print('Blinking complete')
Output
Blinking complete
⚠️

Common Pitfalls

Common mistakes when blinking an LED on Raspberry Pi Pico include:

  • Using the wrong pin number. The onboard LED is on pin 25.
  • Not setting the pin as output with machine.Pin.OUT.
  • Forgetting to import the time module for delays.
  • Using too short delays, making the blink too fast to see.
python
import machine
import time

# Wrong: Not setting pin as output
led = machine.Pin(25)  # Missing machine.Pin.OUT

# Correct way:
led = machine.Pin(25, machine.Pin.OUT)

# Wrong: No delay, LED will not blink visibly
led.value(1)
led.value(0)

# Correct way:
led.value(1)
time.sleep(0.5)
led.value(0)
time.sleep(0.5)
📊

Quick Reference

Remember these key points for blinking an LED on Raspberry Pi Pico:

  • Use machine.Pin(25, machine.Pin.OUT) for the onboard LED.
  • Toggle LED with pin.value(1) (on) and pin.value(0) (off).
  • Use time.sleep(seconds) to control blink speed.
  • Run the toggle inside a loop for continuous blinking.

Key Takeaways

Use pin 25 with machine.Pin.OUT to control the onboard LED on Raspberry Pi Pico.
Toggle the LED state with pin.value(1) to turn on and pin.value(0) to turn off.
Add delays with time.sleep() to make the blinking visible.
Run the LED toggle inside a loop for repeated blinking.
Check imports and pin setup carefully to avoid common errors.