The Dirty Dozen - Part Two - RPi Clone
This week I pulled out of the Dirty Dozen box a very cool RPi PICO clone.
To set myself a bit of a task I decided to program in MicroPython using Thonny, not the usual C via the Arduino IDE.I had seen online some scuttlebutt about the ADC on these things being a little tricky, so I decided to test it out using an LDR which would then affect the integrated WS2812 LED to display light levels.
My Python skills were a little rusty, but after borrowing heavily from the internet, I was able to code the following.
import array, time from machine import Pin import rp2 # Configure the number of WS2812 LEDs, pins and brightness. NUM_LEDS = 1 PIN_NUM = 23 brightness = 0.1 ldr = machine.ADC(27) lightled = 0 BLACK = (0, 0, 0) RED = (255, 0, 0) YELLOW = (255, 150, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) WHITE = (255, 255, 255) COLORS = (WHITE, CYAN, YELLOW, GREEN, PURPLE, RED, BLUE, BLACK) @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(16). 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)]) 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] def pixels_fill(color): for i in range(len(ar)): pixels_set(i, color) for color in COLORS: pixels_fill(color) pixels_show() time.sleep(1.5) while True: lightled = ldr.read_u16() print(lightled) if lightled > 25000: pixels_fill(WHITE) elif lightled > 24000: pixels_fill(CYAN) elif lightled > 21000: pixels_fill(YELLOW) elif lightled > 18000: pixels_fill(GREEN) elif lightled > 15000: pixels_fill(PURPLE) elif lightled > 12000: pixels_fill(RED) elif lightled > 9000: pixels_fill(BLUE) elif lightled > 6000: pixels_fill(BLACK) pixels_show() time.sleep(0.2)
Loading up into the module was a breeze, and the second instalment of the Dirty Dozen was a success.
No comments:
Post a Comment