Easy
Create Animated Snowflakes on Art Matrix
Write a MicroPython plugin that fills Art Matrix with randomly generated, spinning snowflakes.
Each snowflake is the result of a unique geometric process that produces stunning shapes, but their fine detail is hard to see without magnification. What if we could generate big, unique and beautiful snowflakes in the comfort of our home?
We can with Art Matrix.
In this guide, we will learn how to make randomly generated snowflakes appear across all 16,384 pixels of Art Matrix. Best of all, you don't have to step out into the cold!
What You'll Need
- Art Matrix
- USB-C to USB-A or USB-C to USB-C cable
- A computer running Thonny
Connecting to Art Matrix
We're going to assume that you have already used Art Matrix and its default plugins before starting this guide. But, just in case, we will run through the basics of getting your Art Matrix powered up and ready for coding.
Art Matrix requires two connections. The first is for power, and the second is a data connection between Art Matrix and our computer.
- Connect a USB data cable to the
PROGRAMport on Art Matrix, and your computer. A good quality USB data cable is essential. We have USB-C to USB-A and USB-C to USB-C cables in our store. - Connect the included 45W power supply to the
POWERUSB-C port. Art Matrix always requires a power connection, but thePROGRAMconnection can be removed when Art Matrix is in general use. - On your computer, open Thonny and connect to Art Matrix. Click on
Tools >> Optionsand in the dialog select theInterpretertab. Then set the interpreter toMicroPython (Raspberry Pi Pico)and leave the port set to auto-detect. Click onOKand then click onStopto force reset the connection.
- Click on
View >> Filesand, in theRaspberry Pi Picopane, navigate tolib >> plugins. This will show all of the folders for the pre-installed plugins.
- Right-click in
pluginsand create a new directory calledsnowflake.
Coding the Project
The project code will programmatically generate pseudo-random snowflakes in varying sizes, positions and configurations. The goal is to create a subtle winter or festive decoration that fits in with your home.
In Thonny, create a new blank document by clicking
File >> New.Import a series of modules:
- Math: Used to create and transform the snowflakes using maths.
- Random: To add pseudo-random snowflake generation.
- Time: To control the pace of the project code.
import math import random import timeTurn on anti-aliasing to smooth screen images. Then use a constant to store the number of snowflakes. In our tests, three snowflakes at once was ideal. Any more and the screen is a little too busy, which won't show the beauty of our snowflakes.
screen.antialias = image.X4 NUM_FLAKES = 3Create two more constants for the minimum and maximum time that a snowflake will appear on screen. This is measured in milliseconds. You can increase or decrease these values to suit your mood.
MIN_LIFE = 500 MAX_LIFE = 2000To create our snowflakes, we use a function. Inside the function, we randomly select a hue and then set the angle for each arm of the snowflake. Snowflakes are based on hexagons, so we divide 360 degrees by 6 to get the angle.
def make_flake(): hue = random.randint(190, 300) arm_angle = 360 / 6Create two variables for the arm length and width. These values are randomly generated float values each time the function is called.
arm_length = random.uniform(0.8, 1.0) arm_width = random.uniform(0.04, 0.09)Create an empty list,
parts, which is used to store the parts of one snowflake arm.parts = []Generate the main part of an arm and append it to the
partslist. Then create a variable,branches, and pick a random number between 2 and 4.parts.append(shape.line(0, 0, arm_length, 0, arm_width)) branches = random.randint(2, 4)Create variables,
angleandlength, to store randomly generated values for the angle and length of the side branches. The angle is selected between 20 and 75 degrees.angle = math.radians(random.randint(20, 75)) length = random.uniform(0.2, 0.8)Create variables,
dxanddy, to work out how far along and how far sideways the tip of each branch is from its starting point.dx = math.cos(angle) * length dy = math.sin(angle) * lengthUsing a
forloop, build the branches. At each point along the arm we add a mirrored pair of branches, one angled up and one down.for b in range(branches): pos = arm_length * (b + 1) / (branches + 1) parts.append(shape.line(pos, 0, pos + dx, dy, arm_width)) parts.append(shape.line(pos, 0, pos + dx, -dy, arm_width))Create a small hexagon for the middle of the snowflake and then set
spinto represent the number of degrees the snowflake turns per millisecond.centre = shape.regular_polygon(0, 0, random.uniform(0.1, 0.2), 6) spin = 0.02Set a random position,
xandyusing a fraction of the screen. This is later turned into a pixel position. Then set thesizeof the snowflake. Finally, set thestarttime and randomly select a lifespan betweenMIN_LIFEandMAX_LIFE.x = random.uniform(0.1, 0.9) y = random.uniform(0.1, 0.9) size = random.uniform(0.08, 0.35) start = time.ticks_ms() life = random.randint(MIN_LIFE, MAX_LIFE)For the final part of the
make_flake()function, we return the snowflake configuration as a dictionary.return {"hue": hue, "arm_angle": arm_angle, "parts": parts, "centre": centre, "spin": spin, "x": x, "y": y, "size": size, "start": start, "life": life}Create a blank list,
flakes, and then use aforloop to append snowflake data made by themake_flake()function to theflakeslist. We use theNUM_FLAKESconstant as the limit of theforloop.flakes = [] for i in range(NUM_FLAKES): flakes.append(make_flake())Create a new function to draw a single snowflake. The first steps in the function are to get the screen position and size of the snowflake in pixels.
def draw_flake(flake, age): cx = flake["x"] * screen.width cy = flake["y"] * screen.height size = flake["size"] * min(screen.width, screen.height)Slowly rotate the snowflake and then set the snowflake colour by setting the pen colour. We'll set the age (how long the snowflake has been on screen) later. For the colour we reuse the
flake["hue"]value to get a colour.rotation = age * flake["spin"] screen.pen = color.oklch(220, 100, flake["hue"], 255)Use a
forloop to draw each arm, rotated using thearm_anglevariable.for arm in range(6): for part in flake["parts"]: part.transform = mat3().translate(cx, cy).rotate(rotation + arm * flake["arm_angle"]).scale(size) screen.shape(part)Draw the centre of the snowflake. This ends the
draw_flake()function.flake["centre"].transform = mat3().translate(cx, cy).rotate(rotation).scale(size) screen.shape(flake["centre"])Create a function called
update(). Then set the pen colour to black and clear the screen.def update(): screen.pen = color.rgb(0, 0, 0) screen.clear()Use a
forloop to go through every snowflake in the listflakes. Check how long the snowflake has been on screen, and if it has been there long enough, swap it for another snowflake. Then reset theagevalue for the snowflake.for i in range(len(flakes)): age = time.ticks_diff(time.ticks_ms(), flakes[i]["start"]) if age > flakes[i]["life"]: flakes[i] = make_flake() age = 0Call the
draw_flake()function to draw the snowflakes to the display.draw_flake(flakes[i], age)Save the code to your Art Matrix (which Thonny calls a
Raspberry Pi Pico), inside the/lib/plugins/snowflakedirectory as__init__.py.
Complete Code Listing
import math
import random
import time
screen.antialias = image.X4
NUM_FLAKES = 3
MIN_LIFE = 500
MAX_LIFE = 2000
def make_flake():
hue = random.randint(190, 300)
arm_angle = 360 / 6
arm_length = random.uniform(0.8, 1.0)
arm_width = random.uniform(0.04, 0.09)
parts = []
parts.append(shape.line(0, 0, arm_length, 0, arm_width))
branches = random.randint(2, 4)
angle = math.radians(random.randint(20, 75))
length = random.uniform(0.2, 0.8)
dx = math.cos(angle) * length
dy = math.sin(angle) * length
for b in range(branches):
pos = arm_length * (b + 1) / (branches + 1)
parts.append(shape.line(pos, 0, pos + dx, dy, arm_width))
parts.append(shape.line(pos, 0, pos + dx, -dy, arm_width))
centre = shape.regular_polygon(0, 0, random.uniform(0.1, 0.2), 6)
spin = 0.02
x = random.uniform(0.1, 0.9)
y = random.uniform(0.1, 0.9)
size = random.uniform(0.08, 0.35)
start = time.ticks_ms()
life = random.randint(MIN_LIFE, MAX_LIFE)
return {"hue": hue, "arm_angle": arm_angle,
"parts": parts, "centre": centre, "spin": spin,
"x": x, "y": y, "size": size, "start": start, "life": life}
flakes = []
for i in range(NUM_FLAKES):
flakes.append(make_flake())
def draw_flake(flake, age):
cx = flake["x"] * screen.width
cy = flake["y"] * screen.height
size = flake["size"] * min(screen.width, screen.height)
rotation = age * flake["spin"]
screen.pen = color.oklch(220, 100, flake["hue"], 255)
for arm in range(6):
for part in flake["parts"]:
part.transform = mat3().translate(cx, cy).rotate(rotation + arm * flake["arm_angle"]).scale(size)
screen.shape(part)
flake["centre"].transform = mat3().translate(cx, cy).rotate(rotation).scale(size)
screen.shape(flake["centre"])
def update():
screen.pen = color.rgb(0, 0, 0)
screen.clear()
for i in range(len(flakes)):
age = time.ticks_diff(time.ticks_ms(), flakes[i]["start"])
if age > flakes[i]["life"]:
flakes[i] = make_flake()
age = 0
draw_flake(flakes[i], age)
Creating the Snowflake Plugin
Click on
File >> Newto create a new blank file.Inside the file, add this text. The text tells the Art Matrix web UI the name of the plugin, its version number, a brief description, the author's name, the category it belongs in, and whether the plugin requires an internet connection.
{ "name": "Snowflake", "version": "1.0.0", "description": "Pseudo-random snowflakes", "author": "Your name here", "category": "Visualisations", "requires_internet": false }Save the file inside the
/lib/plugins/snowflakedirectory aspackage.json.Create a 128 x 128 pixel icon in your favourite image editor and save it as
thumbnail.png. In Thonny’sThis computerpane, right-clickthumbnail.pngand chooseUpload to /lib/plugins/snowflake. You should now havepackage.json,thumbnail.pngand__init__.pyinside thesnowflakedirectory.
Using the Snowflake Plugin
- Open a web browser and go to your Art Matrix. The exact URL was created during the setup process detailed in the Quick Start Guide. It is the address in the box which ends in
.local. Our unit is athttp://artmatrix.local.
- Click on the toggle switch for
Snowflaketo activate it.
- Snowflakes will appear across Art Matrix. If you set
Snowflaketo be the only plugin, then Art Matrix will constantly show it. Otherwise, it will play for ten seconds, and then the next plugin will start. The rotation will continue until Art Matrix is turned off, or you change the active plugins.