Since it’s nowhere near Christmas, I can’t justify posting this code sample except as a tribute to Frank Zappa’s “City of Tiny Lights”.
This sample uses randomisation to turn on pixels on the microbit display and then let them fade out over time to create a “twinkly” effect.
from microbit import * import random pixel_fully_on = 9 pixel_fully_off = 0 twinkle_probability = 3 fading_rate = 4 leds = [(x, y) for y in range(0, 5) for x in range(0, 5)] while True: # inspect pixels # can we turn on any pixels on? for led in leds: brightness = display.get_pixel(led, led) if brightness == pixel_fully_off: twinkle = random.randint(0, 100) if twinkle <= twinkle_probability: display.set_pixel(led, led, pixel_fully_on) sleep(50) # fade all lit pixels by fade factor for led in leds: brightness = display.get_pixel(led, led) if brightness > pixel_fully_off: faded_brightness = max(brightness - fading_rate, 0) display.set_pixel(led, led, faded_brightness)
The probablility of lighting a pixel and the rate at which they fade out are variables at the top of the program and contribute a lot to the actual effect. Too likely a probability and too many pixels are lit at once, too fast or slow a fade doesn’t give the right winter sparkle we are going for. The values I have here, and also the delay between the lighting and fading halves, are just what I found from playing around.
And here it is in action…