LEGO Set Lighting
2024-12-17 | By Adafruit Industries
License: See Original Project Batteries LEDs / Discrete / Modules STEMMA
Courtesy of Adafruit
Guide by John Park
Overview
Light up your LEGO buildings, spacecraft, vehicles, and more with super-tiny LEDs. Sets such as the Winter Village and Star Wars lines are just begging to have lights added. You can add lights exactly where you want using pre-wired SMD LEDs. Then, you can animate them to blink, dim, and flicker exactly as you like using CircuitPython.
Or you can keep it very simple using an on/off coin cell battery holder breakout.
Other Resources
If you want to mount your QT Py to LEGO bricks, check out this great Ruiz Brothers guide.
And for other STEMMA QT board mounting, this guide has you covered.
While working on this guide, I found an excellent and very similar tutorial on BrickNerd! Check it out, especially for some more ideas on doing an amazing cyberpunk-style lighting setup.
Parts
Simple Setup / Testing
A coin cell breakout it great for quickly testing LEDs or for doing a simple on/off lighting setup.
20mm Coin Cell Breakout w/On-Off Switch (CR2032)
LEGO Set
Any LEGO creation you build that includes translucent plates and bricks can be lit up with these techniques.
If you want to start with an official model, the models in Winter Village line is are excellent candidates for cozy lighting, as are any of the modular buildings.
The Razor Crest is one of the many, many, many Star Wars ships that light up nicely.
Text editor powered by tinymce.
Test Lighting with a Coin Cell
The wired SMD LEDs are designed to run off of 3VDC, so you can easily power them from a 3V coin cell battery.
The holder with switch makes it simple to get started (and to test LEDs for color).
The blue wires connect to either GND pad, and the red wires connect to the Sw pad if you want to use the on/off switch. The On pad is always on regardless of switch position.
Semi-Permanent Solderless Wiring
While soldering would be ideal, you can get by pretty well by twisting together all of the blue wires to each other and all of the red wires to each other of multiple LEDs and then twisting these bundles in the coin cell breakout pads as shown here.
This is a parallel circuit, in which each LED draws the full power, so there's no need to worry about dimming as in a series circuit.
Text editor powered by tinymce.
Mounting LEDs in Bricks and Plates
Wire Insertion
The great thing about these wired LEDs is that the wires are so thin you can put the lights where you need and still stack plates and bricks right over the wires.
Here, the LEDs are fed through the open stud round plate though the bottom.
Once the LED is where you want it, press the round plate back onto the stud below.
Then, the red translucent round plate is placed over top.
Battery Pack
Find a central location to hide the battery pack and switch -- I chose this spot under the removable escape pod.
Is he hiding the battery in there?
Wiring Plan
I then roughly placed the lights in their desired location before feeding them through the model. This build has two red headlights (pink LEDs under translucent red round plates), two blue engine lights, and one green cockpit light.
Part Fitting
Add LEDs to both of the front lights on the ship as shown here, then fit the assembly back onto the ship.
Engine Lighting
With the battery in a central location, I lifted strategic plates to sneak the wiring through to the engines, then placed the plates back, being careful to route the wire between studs.
Then, I covered the blue LEDs with a clear translucent square plate and affixed to a stud.
That wire could be hidden more effectively...
Cockpit Light
The cockpit light is angled up to illuminate Baby Yoda.
Next, let's look at creating an animated lighting display using CircuitPython and a constant current driver to control the LEDs.
Text editor powered by tinymce.
Build the Lighting Circuit
You can gain lots of control over your LEGO lighting by using a microcontroller and constant current driver board. This will allow you to create individualized brightness levels and animated effects for 16 LEDs (more if you use additional driver boards, for a total of 64 LEDs per I2C port).
Wiring Cables
You'll use the AW9523 driver breakout to control the LEDs. The board is conveniently designed with 16 pairs of pads for the connections to your LEDs. You can wire the LEDs directly (red to Vin, blue to numbered GPIO current-source pin), or do some extra wiring prep to make detachable wiring cable assemblies.
Cable Assembly
Twist the wire pairs to make them more manageable. You can do this by hand or chuck them into a drill for speed.
Then, add a short length of heat shrink tubing to each LED wire.
Solder the red LED wire to the red wire of the smaller female JST cable, and the blue LED wire to the black wire of the JST cable.
Board Cable
Next, solder the larger male JST cable to the driver board. The black wire will go to pin 0, the red to the associated Vin pad.
Plug the cable ends together to connect.
You can now create cable assemblies for all of the LEDs you want to use. It can be helpful to add color-coded heat shrink tubing to help differentiate the lights.
Lamp Lighting
To light up a typical Winter Village lamp, simply run the LED up through the base as shown.
The translucent yellow brick will look amazing when illuminated from within!
Here's what the lamp will look like when we plug the board into the QT Py and code it with CircuitPython in the next pages.
Now you will connect the driver board to your QT Py via the STEMMA QT cable and code it.
Text editor powered by tinymce.
Easy Codeless Installation
If you want to get set up quickly with the same lighting patterns I used in my model, all you have to do is copy a single file onto the QT Py RP2040. You won't be able to customize this file, but it is as easy as drag-and-drop to get started.
To customize, check out the CircuitPython and Code the Lighting Controller pages.
To enter the bootloader, hold down the BOOT/BOOTSEL button (highlighted in red above), and while continuing to hold it (don't let go!), press and release the reset button (highlighted in blue above). Continue to hold the BOOT/BOOTSEL button until the RPI-RP2 drive appears!
If the drive does not appear, release all the buttons, and then repeat the process above.
You can also start with your board unplugged from USB, press, and hold the BOOTSEL button (highlighted in red above), continue to hold it while plugging it into USB, and wait for the drive to appear before releasing the button.
A lot of people end up using charge-only USB cables and it is very frustrating! Make sure you have a USB cable you know is good for data sync.
The UF2 file is large, so it may take a couple of minutes to copy onto your RPI-PR2 drive. Since the QT Py RP2040 has 8MB of flash, the UF2 file is 16MB, due to the way UF2 files work.
You will see a new disk drive appear called RPI-RP2.
Drag the lego_lighting_01.uf2 file to RPI-RP2.
The RPI-RP2 drive will disappear, and a new disk drive called CIRCUITPY will appear.
That's it, you're done, the lights will automatically start running.
If you ever want to create your own drag-and-drop UF2 file for an RP2040 board running CircuitPython, check out this Playground page by Dan Halbert. It shows you how to use picotool to build your own to share.
Create All-in-One UF2's with CIRCUITPY Files on RP2040
Text editor powered by tinymce.
CircuitPython
CircuitPython is a derivative of MicroPython designed to simplify experimentation and education on low-cost microcontrollers. It makes it easier than ever to get prototyping by requiring no upfront desktop software downloads. Simply copy and edit files on the CIRCUITPY drive to iterate.
CircuitPython QuickStart
Follow this step-by-step to quickly get CircuitPython running on your board.
Download the latest version of CircuitPython for this board via circuitpython.org
Click the link above to download the latest CircuitPython UF2 file.
Save it wherever is convenient for you.
To enter the bootloader, hold down the BOOT/BOOTSEL button (highlighted in red above), and while continuing to hold it (don't let go!), press and release the reset button (highlighted in red or blue above). Continue to hold the BOOT/BOOTSEL button until the RPI-RP2 drive appears!
If the drive does not appear, release all the buttons, and then repeat the process above.
You can also start with your board unplugged from USB, press, and hold the BOOTSEL button (highlighted in red above), continue to hold it while plugging it into USB, and wait for the drive to appear before releasing the button.
A lot of people end up using charge-only USB cables and it is very frustrating! Make sure you have a USB cable you know is good for data sync.
You will see a new disk drive appear called RPI-RP2.
Drag the adafruit_circuitpython_etc.uf2 file to RPI-RP2.
The RPI-RP2 drive will disappear, and a new disk drive called CIRCUITPY will appear.
That's it, you're done! :)
Safe Mode
You want to edit your code.py or modify the files on your CIRCUITPY drive but find that you can't. Perhaps your board has gotten into a state where CIRCUITPY is read-only. You may have turned off the CIRCUITPY drive altogether. Whatever the reason, safe mode can help.
Safe mode in CircuitPython does not run any user code on startup and disables auto-reload. This means a few things. First, safe mode bypasses any code in boot.py (where you can set CIRCUITPY read-only or turn it off completely). Second, it does not run the code in code.py. And finally, it does not automatically soft-reload when data is written to the CIRCUITPY drive.
Therefore, whatever you may have done to put your board in a non-interactive state, safe mode gives you the opportunity to correct it without losing all of the data on the CIRCUITPY drive.
Entering Safe Mode
To enter safe mode when using CircuitPython, plug in your board or hit reset (highlighted in red above). Immediately after the board starts up or resets, it waits 1000ms. On some boards, the onboard status LED (highlighted in green above) will blink yellow during that time. If you press reset during that 1000ms, the board will start up in safe mode. It can be difficult to react to the yellow LED, so you may want to think of it simply as a slow double click of the reset button. (Remember, a fast double click of reset enters the bootloader.)
In Safe Mode
If you successfully enter safe mode on CircuitPython, the LED will intermittently blink yellow three times.
If you connect to the serial console, you'll find the following message.
Auto-reload is off. Running in safe mode! Not running saved code. CircuitPython is in safe mode because you pressed the reset button during boot. Press again to exit safe mode. Press any key to enter the REPL. Use CTRL-D to reload.
You can now edit the contents of the CIRCUITPY drive. Remember, your code will not run until you press the reset button, or unplug and plug in your board, to get out of safe mode.
Flash Resetting UF2
If your board ever gets into a really weird state and CIRCUITPY doesn't show up as a disk drive after installing CircuitPython, try loading this 'nuke' UF2 to RPI-RP2. which will do a 'deep clean' on your Flash Memory. You will lose all the files on the board, but at least you'll be able to revive it! After loading this UF2, follow the steps above to re-install CircuitPython.
Download flash erasing "nuke" UF2
Text editor powered by tinymce.
Code the Lighting Controller
Text Editor
Adafruit recommends using the Mu editor for editing your CircuitPython code. You can get more info in this guide.
Alternatively, you can use any text editor that saves simple text files.
Download the Project Bundle
Your project will use a specific set of CircuitPython libraries, and the code.py file. To get everything you need, click on the Download Project Bundle link below, and uncompress the .zip file.
Connect your computer to the board via a known good USB power+data cable. A new flash drive should show up as CIRCUITPY.
Drag the contents of the uncompressed bundle directory onto your board CIRCUITPY drive, replacing any existing files or directories with the same names, and adding any new ones that are necessary.
# SPDX-FileCopyrightText: Copyright (c) 2023 john park for Adafruit Industries # # SPDX-License-Identifier: MIT import asyncio from random import randint, uniform import busio import board import adafruit_aw9523 # pin descriptions are based on physical LED placement # 0 bakery window, 1 lamp1 A, 2 lamp1 B, 3 bakery sconce, 4 lamp 2, 5 music sconce a, # 6 music sconce b, 7 music candle, 8 bakery red a, 9 bakery red b, 10 bakery green a, # 11 bakery green b i2c = busio.I2C(board.SCL1, board.SDA1) leddriver = adafruit_aw9523.AW9523(i2c) # Set all pins to outputs and LED (const current) mode leddriver.LED_modes = 0xFFFF leddriver.directions = 0xFFFF window_set = [8, 10, 9, 11] # red/green string always_on_set = [0, 1, 2, 4] # window and lanterns always_on_set_maxes = [100, 30, 30, 40] # maximum brightness per light # lights that are always on for n in range(len(always_on_set)): leddriver.set_constant_current(always_on_set[n], always_on_set_maxes[n]) async def flicker(pin, min_curr, max_curr, interval): while True: rand_max_curr = randint(min_curr, max_curr) for i in range(min_curr, rand_max_curr): leddriver.set_constant_current(pin, i) # aw9523 pin, current out of 255 await asyncio.sleep(0.07) await asyncio.sleep(uniform(0.0, interval)) async def string_lights(interval, max_curr): while True: for i in range(len(window_set)): # fade up for j in range(max_curr): leddriver.set_constant_current(window_set[i], j) print(j) await asyncio.sleep(interval) for i in range(len(window_set)): # fade down for j in range(max_curr): leddriver.set_constant_current(window_set[i], max_curr-j) print(j) await asyncio.sleep(interval) async def main(): led0_task = asyncio.create_task(flicker(3, 3, 10, 0.7)) # music candle led1_task = asyncio.create_task(flicker(5, 6, 12, 0.7)) # music sconce a led2_task = asyncio.create_task(flicker(6, 6, 12, 0.7)) # music sconce b led3_task = asyncio.create_task(flicker(7, 3, 10, 0.7)) # music candle led4_task = asyncio.create_task(string_lights(0.03, 30)) await asyncio.gather(led0_task, led1_task, led2_task, led3_task, led4_task) asyncio.run(main())
How it Works
Imports
First the code imports the necessary library modules:
asyncio: This module provides infrastructure for writing single-threaded concurrent code using coroutines
randint, uniform: Functions for generating random numbers
busio, board: for setting up the I2C communication bus
adafruit_aw9523: library for the AW9523 LED driver board
import asyncio from random import randint, uniform import busio import board import adafruit_aw9523
I2C and Driver Setup
busio.I2C initializes one I2C bus on the STEMMA QT port pins
adafruit_aw9523.AW9523(i2c) initializes the AW9523 driver using the I2C bus with the name leddriver
Configure all of the leddriver pins as LED constant current mode with their direction set to output
i2c = busio.I2C(board.SCL1, board.SDA1) leddriver = adafruit_aw9523.AW9523(i2c) leddriver.LED_modes = 0xFFFF leddriver.directions = 0xFFFF
Light Sets
Four of the lights are part of the red/green string over the upper floor bakery window. These pins are added to a list named window_set[] with the proper order for running a left-right chase pattern.
Four other lights (lanterns, bakery shop display window) will always be on, so they are handled very simply just once. The always_on_set[] is a list of these four pins.
The always_on_set_maxes[] define the brightness level for the "always on" set of lights.
window_set = [8, 10, 9, 11] # red/green string always_on_set = [0, 1, 2, 4] # window and lanterns always_on_set_maxes = [100, 30, 30, 40] # maximum brightness per light
Always-On Set Activation
Next, we'll turn on the LEDs that are always on at a constant current value.
for n in range(len(always_on_set)): leddriver.set_constant_current(always_on_set[n], always_on_set_maxes[n])
async flicker() Function
We define a function that flickers lights with inputs for pin, minimum current, maximum current, and the timing interval.
Similar to a regular CircuitPython function, but these are asyncio functions, which means they can operate in a non-blocking way, so their timing is independent of other async functions.
This is really helpful for creating multiple different lighting effects that happen simultaneously! In fact, this function will run concurrently on four different LEDs, lending them an organic look, since they operate independently of each other with their own randomized brightness levels.
async def flicker(pin, min_curr, max_curr, interval): while True: rand_max_curr = randint(min_curr, max_curr) for i in range(min_curr, rand_max_curr): leddriver.set_constant_current(pin, i) # aw9523 pin, current out of 255 await asyncio.sleep(0.07) await asyncio.sleep(uniform(0.0, interval))
async string_lights() Function
This function is a typical holiday string light effect where each light fades up in turn and then loops around to fade down in order.
async def string_lights(interval, max_curr): while True: for i in range(len(window_set)): # fade up for j in range(max_curr): leddriver.set_constant_current(window_set[i], j) print(j) await asyncio.sleep(interval) for i in range(len(window_set)): # fade down for j in range(max_curr): leddriver.set_constant_current(window_set[i], max_curr-j) print(j) await asyncio.sleep(interval)
async main() Function
In the main() async function, create each task that is to be executed concurrently. These tasks call the previously defined async functions flicker() and string_lights(). In the case of flicker(), different pins, minimum and maximum current values and timing intervals per task can be specified.
The asyncio.gather() function runs the multiple co-routines concurrently, and awaits their completion before starting them again, respectively.
async def main(): led0_task = asyncio.create_task(flicker(3, 3, 10, 0.7)) # music candle led1_task = asyncio.create_task(flicker(5, 6, 12, 0.7)) # music sconce a led2_task = asyncio.create_task(flicker(6, 6, 12, 0.7)) # music sconce b led3_task = asyncio.create_task(flicker(7, 3, 10, 0.7)) # music candle led4_task = asyncio.create_task(string_lights(0.03, 30)) await asyncio.gather(led0_task, led1_task, led2_task, led3_task, led4_task)
Run main() co-routine
Finally, to call the main() function using asyncio.run().
asyncio.run(main())
Text editor powered by tinymce.
Light the Winter Village
Rig the Lights
There are many different ways to run your lighting. I found convenient gaps in bricks and windows, and ran a light down into the wall sconce, behind the display window overhang, into the four string lights, inside a candle, and in the three lantern lights.
With some extra care you can hide the wiring even better than the examples here :)
No peeking backstage
Text editor powered by tinymce.
Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.
Visit TechForum