MicroPython Tutorial II
Lesson II
Ok, now you know how to get the controls on the brick to do different things when you press them. Lets try editing the code and adding more functionality to it.
In this lesson we’re going to learn how to change the lights on the brick itself. We start by using the brick buttons template and adding the four lines you see here in bold.
Brick Lights
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Button, Color
from pybricks.tools import waitwhile True:
if Button.DOWN in brick.buttons():
brick.light(Color.RED)
wait(500)
if Button.UP in brick.buttons():
brick.light(Color.YELLOW)
wait(500)
What does it do, type it in and find out. Assuming you got it all right when you press the different buttons on the brick the LED lights on it will change. You have a three more colors than shown here, namely GREEN, ORANGE and BLACK. The latter turns the LED off.
Let’s add a little spice to our program by add a random number generator.
We need first import a couple of standard PYTHON libraries into our code. One for time and one for generating random numbers. Add these two lines under the “from” statements.
import time
import random
Then add these lines under that to define a subroutine. A subroutine that will generate a random number and return a random color associated with it.
def randomColor():
seedling = int(round(time.time()))
random.seed(seedling)
colorNo = random.randint(0,4)
colorList = [Color.RED, Color.YELLOW, Color.GREEN, Color.ORANGE, Color.BLACK]
return(Color.colorList[color])
Having defined a subroutine to generate a random color, we can then use it in our conditional if statements.

if Button.DOWN in brick.buttons():
color = randomColor()
brick.light(color)
This will return a random color every time you press the UP, DOWN buttons. Unfortunately you’ve only got five colors on LED panel, all of which I named I already mentioned.