Skip to content

Instantly share code, notes, and snippets.

@jpwsutton
Created January 1, 2019 17:57
Show Gist options
  • Save jpwsutton/5f1c5bfbf3e27416b00f85b6e2a7e1de to your computer and use it in GitHub Desktop.
Save jpwsutton/5f1c5bfbf3e27416b00f85b6e2a7e1de to your computer and use it in GitHub Desktop.
Microbit Python Script to control a light up dragon egg
from microbit import *
from neopixel import NeoPixel
num_pixels = 47
purple = (64,0,64)
red = (255,0,0)
off = (0,0,0)
speed = 50 # in ms
steps = 20
currentColour = off
angryTimeout = 3500
pixels = NeoPixel(pin0, num_pixels)
# Set all LEDs to a colour.
def setAll(colour):
for pixel_id in range(0, len(pixels)):
pixels[pixel_id] = colour
pixels.show()
def fade(start, finish=(0,0,0), n=10, d=20, override=False):
''' returns a gradient list of (n) colors between
two rgb color tuples. start and finish.
n is the number of iterations per fade,
d is the speed between steps
override will ignore checking if shaken, only used
when the egg has been shaken.'''
# Starting and ending colors in RGB form
s = start
f = finish
# Initilize a list of the output colors with the starting color
# Calcuate a color at each evenly spaced value of t from 1 to n
for t in range(1, n):
# Interpolate RGB vector for color at the current value of t
curr = [
int(s[j] + (float(t)/(n-1))*(f[j]-s[j]))
for j in range(3)
]
currentColour = curr
setAll(curr)
if override is False:
checkforshake()
sleep(d)
return
# Check to see if the egg was shaken
# If it was, immediately fade to red,
# Sleep, then go back to normal.
def checkforshake():
if accelerometer.was_gesture('shake'):
fade(currentColour, red, steps, speed, True)
sleep(angryTimeout)
fade(red, currentColour, steps, speed, True)
# Loop forever, fading between purple and off.
while True:
fade(purple, off, steps, speed)
fade(off, purple, steps, speed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment