I have completed an alarm for my eBike using a Pico and PiicoDev Motion Sensor which powers a piezo screamer on activation. I also wanted visual warning to anyone trying to steal my eBike so I added a Glowbit Rainbow. This is the code I used, modified from the Core Electronics code. The While True loop could be improved but I have kept it simple to make changes you want to make, easy.
Certainly a fun device for displaying.
Cheers,
Brian
# Example using PIO to drive a set of WS2812 LEDs.
# Adapted from code courtesy of CoreElectronics
# Display of Glowbit Rainbow an alarm display -
# fast colour chase a bit frantic -
# green - forwards
# blue - backwards
# red - forwards
# blue - backwards
import array, time
from machine import Pin
import rp2
# Configure the number of WS2812 LEDs.
NUM_LEDS = 13
PIN_NUM = 0 # changed from 22 for physical convenience
brightness = 0.2
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()
# Create the StateMachine with the ws2812 program, outputting on pin
sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
# Display a pattern on the LEDs via an array of LED RGB values.
ar = array.array("I", [0 for _ in range(NUM_LEDS)])
# if you want to understand above code ask CoreElectronics
# as I have no idea.
##########################################
def pixels_show():
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
dimmer_ar[i] = (g<<16) + (r<<8) + b
sm.put(dimmer_ar, 8)
time.sleep_ms(10)
def pixels_set(i, color):
ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
# do while added funcion to enable simple reverse direction -
def color_chase_reverse(color): # sleep time not passed
i = (NUM_LEDS) - 1 # loop from 12 to 0
while i > -1:
pixels_set(i, color)
time.sleep(0.005)
pixels_show()
i = i - 1
def color_chase(color): # sleep time not passed
for i in range(NUM_LEDS):
pixels_set(i, color)
time.sleep(0.005)
pixels_show()
# Other colours removed as not required.
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
while True:
color_chase(GREEN)
color_chase(BLACK)
color_chase_reverse(BLUE)
color_chase_reverse(BLACK)
color_chase(RED)
color_chase(BLACK)
color_chase_reverse(BLUE)
color_chase_reverse(BLACK)
#time.sleep(2) # remove rem to give time to stop on black