Raspberry pi pico – Knight Rider LED effect

Someone recently told me about the Pi Pico – a microcontroller from the Raspberry pi foundation that can implement Micropython. Being a big fan of raspberry pi’s, microntrollers, and Python I had to try one out!

Only ~$5 USD from Digikey!

Set up:

First, I soldered header pins on the pi so I could interface it to the breadboard.

Then, I followed the on-line guide for deploying Micropython:

https://www.raspberrypi.org/documentation/rp2040/getting-started/#getting-started-with-micropython

Basically download the “UF2” file containing micropython. Then connect the pi to the PC with a microUSB cable (make sure data cable, not charging only cable!) while holding down the bootsel button.

This mounts the pi as a mass storage device; drop the UF2 file into the pi folder; once the pi reboots its running Micropython!

Thonny is recommended to work with micropython and I found it easy to use:

https://thonny.org/

To connect, click the python environment selector in the lower right corner, and select ‘MicroPython (Raspberry pi pico)

The Knight Rider led effect code is as follows:

from machine import Pin
import time
leds = []
for i in range(15,7,-1):
leds.append(Pin(i, Pin.OUT))
sleep_time = 0.035 #50 ms
#THESE list comprehensions make a list corresponding to LEDs to light
#Corresponds to number of the LED in the leds list.
LED_sequence = [x for x in range(0,8,1)] + [x for x in range(6,0,-1)]
print(LED_sequence)
#LED_sequence = [0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1]
#This is a list of "values" to apply to the LED. Turn it on, turn it off.
LED_values = [1,0]
while 1:
for i in LED_sequence: # Loop through the sequence
print(i)
for value in LED_values: #Loop through the values
leds[i].value(value) # For each LED, turn it on, then turn it off!
time.sleep(sleep_time) # Then sleep for sleep_time

As short as this program is, it shows why I love Python! For example, you can make ‘list’ objects that contain other objects (in this case, ‘leds’)! You can then access an led, and even turn it on and off, by referencing the led’s index in the list! This flexibility makes python very powerful.

Once you enter the code, you can run it. If you want it to have it run as soon as you start up the Raspberry Pi, rename it as main.py and save with Thonny to the raspberry pi itself:

A couple wiring tips:

To light the LEDs, I am bringing the pico pins high; the other ends are connected to the ground “bus”; the ground bus is connected to the pico through its pin 3.

A good pinout diagram of the pi:

From: https://www.waveshare.com/wiki/Raspberry_Pi_Pico

Another tip, I’m using these LEDs that have built in resistors to simplify wiring:

Have fun!