Member-only story

MicroPython Tutorial II

Mark Lucking
2 min readAug 1, 2019

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 wait
while 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…

--

--

Mark Lucking
Mark Lucking

Written by Mark Lucking

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More

No responses yet