5. MOVEMotor LEDs
5.1. NeoPixel module
import neopixel
.from microbit import *
import neopixel
5.2. Set up LEDs
- neopixel.NeoPixel(pin, n)
- Initialise a strip of RGB LEDs.
pin
is the pin that they are connected by.n
is the number of LEDs.
lights = neopixel.NeoPixel(pin8, 4)
.from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
5.3. Set LED colour and brightness
- lights[n] = (red, green, blue)
Set the red, green and blue brightness from 0 to 255 for a RGB LED at position n.
lights[0]
.(255, 255, 255)
, the colour is white.from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
lights[0] = (255, 255, 255)
lights.show()
from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
lights[0] = (255, 255, 255)
lights[1] = (255, 0, 0)
lights[2] = (0, 255, 0)
lights[3] = (0, 0, 255)
lights.show()
Tasks
Write code to set the last LEDS at position 1, 2 and 3 to yellow, cyan and magenta.
5.4. Show LEDs
show()
is used on the neopixel object that was set up. e.g. lights.show()
- show()
Show the LEDs using their colour settings. This must be called for any updates to the LEDs to become visible.
lights.show()
from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
lights[0] = (255, 255, 255)
lights.show()
5.5. Clear LEDs
- clear()
Clear all the LEDs so that they have no colours set and turns off the LEDs.
lights
for the neopixel object.clear()
.from microbit import *
import neopixel
lights = NeoPixel(pin8, 4)
dull_blue = [20, 20, 25]
dull_red = [25, 0, 0]
lights[0] = dull_blue
lights[1] = dull_blue
lights[2] = dull_red
lights[3] = dull_red
lights.show()
sleep(2000)
lights.clear()
Tasks
Modify the code to turn on the front lights for 2 sec then turn on the rear lights for 2 sec.
5.6. LED values
To read the colour of a specific RGB LED use its index position.
- lights[n]
Return the red, green and blue value for the RGB LED at position n.
(255, 0, 0)
.for
loop displays each colour value of the LED at position 0.from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
lights[0] = (255, 0, 0)
for rgb_value in lights[0]:
display.scroll(rgb_value)
5.7. Colour lists
for colour in colour_list:
loops through the colours.for led_num in range(4):
loops through each LED to set its colour.from microbit import *
import neopixel
lights = neopixel.NeoPixel(pin8, 4)
white = (255, 255, 255)
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 128, 0)
cyan = (0, 255, 255)
blue = (0, 0, 255)
magenta = (255, 0, 255)
colour_list = [white, red, yellow, green, cyan, blue, magenta]
for colour in colour_list:
for led_num in range(4):
lights[led_num] = colour
lights.show()
sleep(200)
5.8. Primary and secondary colours
Tasks
See https://www.indezine.com/products/powerpoint/learn/color/color-rgb.html
Modify the code to use a shorter list of colours, with just the primary colours.
Modify the code to use a shorter list of colours, with just the secondary colours.