You are on page 1of 253

Pybricks Modules and Examples

Version v3.0.0a3

Nov 11, 2020


Table of Contents

1 EV3 Quick Start 2

2 Powered Up Quick Start 18

3 SPIKE Prime / Robot Inventor 23

4 hubs – Programmable Hubs 24

5 pupdevices – Powered Up Devices 61

6 ev3devices – EV3 Devices 173

7 nxtdevices – NXT Devices 180

8 iodevices – Generic I/O Devices 186

9 parameters – Parameters and Constants 195

10 tools – Timing and Data logging 201

11 robotics – Robotics 205

12 media – Sounds and Images 208

13 messaging – Messaging 230

14 geometry – Geometry and algebra 236

15 Signals and Units 237

16 More about Motors 241

Python Module Index 244

Index 245

i
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

This documentation has everything you need to install Pybricks and run your first scripts.
Step 1: Install Pybricks
Pybricks scripts are the same across all hubs. The only difference is in how you install Pybricks and how you run
scripts. To get started, click one of the platforms below.

MINDSTORMS EV3 Powered Up (Tech- SPIKE / MINDSTORMS Inven-


nic/City/BOOST) tor

Step 2: Start coding!


After you’ve followed the installation steps for your hub, check out the Pybricks modules in the left hand menu to see
what you can do.
Step 3: Share what you made (or ask for help!)
Got questions or issues? Please share your findings on our support page so we can make Pybricks even better. Thank
you!

1
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 1

EV3 Quick Start

Note: This guide and documentation is for Pybricks 3.0. It is under constant development. This version includes
support for LEGO MINDSTORMS EV3 and LEGO Powered Up.
Click here to view the documentation for version 2.0. This is is the stable version officially supported by LEGO
Education. It includes support for LEGO MINDSTORMS EV3 only.

1.1 Installation

This page guides you through the steps to collect and install everything you need to start programming.

1.1.1 What do you need?

To get started, you’ll need:


• A Windows 10 or Mac OS computer
• Internet access and administrator access
This is required during the installation only. You will not need special access to write and run pro-
grams later on.
• A microSD card
You’ll need a card with a minimum capacity of 4GB and a maximum capacity of 32GB. This type
of microSD card is also known as microSDHC. We recommend cards with Application Performance
Class A1.
• A microSD card slot or card reader in your computer
If your computer does not have a (micro)SD card slot, you can use an external USB (micro)SD card
reader.

2
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• A mini-USB cable, like the one included with your EV3 set
The typical configuration of this equipment is summarized in Figure 1.1.

Figure 1.1: Setup overview

1.1.2 Preparing your computer

You’ll write your MicroPython programs using Visual Studio Code. Follow the steps below to download, install, and
configure this application:
1. Download Visual Studio Code.
2. Follow the on-screen instructions to install the application.
3. Launch Visual Studio Code.
4. Open the extensions tab.
5. Install the EV3 MicroPython extension as shown in Figure 1.2.

1.1.3 Preparing the microSD card

To make it possible to run MicroPython programs on your EV3 Brick, you’ll now learn how to install the required
tools on your microSD card.
If the microSD card contains files you want to keep, make sure to create a backup of its contents first. See managing
files on the EV3 to learn how to backup your previous MicroPython programs if necessary.
This process erases everything on your microSD card, including any previous MicroPython programs on it.
To install the MicroPython tools on your microSD card:

3
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Figure 1.2: Installing the extension from the Visual Studio Code marketplace

1. Download the EV3 MicroPython microSD card image and save it in a convenient location. This file is approximately
360 MB. You do not need to unzip the file.
2. Download and install a microSD card flashing tool such as Etcher.
3. Insert the microSD card into your computer or card reader.
4. Launch the flashing tool and follow the steps on your screen to install the file you have just downloaded. If you
use Etcher, you can follow the instructions below, as shown in Figure 1.3.
(a) Select the EV3 MicroPython microSD card image file you have just downloaded.
(b) Select your microSD card. Make sure that the device and size correspond to your microSD card.
(c) Start the flashing process. This may take several minutes. Do not remove the card until the flashing process
is complete.

Figure 1.3: Using Etcher to flash the EV3 MicroPython microSD card image

4
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.1.4 Updating the microSD card

To update the microSD card, download a new image file using the link above and flash it to the microSD card as
described above. Be sure to back up any MicroPython programs you want to save.
You do not need to erase the contents of the microSD card first. This is done automatically when you flash the new
image file.

1.2 Using the EV3 Brick

Make sure the EV3 Brick is turned off. Insert the microSD card you prepared into the microSD card slot on the EV3
Brick, as shown in Figure 1.4.

Figure 1.4: Inserting the flashed microSD card into the EV3 Brick

1.2.1 Turning the EV3 Brick on and off

Turn on the EV3 Brick by pressing the dark gray center button.
The boot process may take several minutes. While booting, the EV3 Brick status light turns orange and blinks inter-
mittently, and you’ll see a lot of text on the EV3 screen. The EV3 Brick is ready for use when the status light turns
green.
To turn the EV3 Brick off, open the shutdown menu with the back button, and then select Power Off using the center
button, as shown in Figure 1.5.

5
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Figure 1.5: Turning the EV3 Brick off

1.2.2 Viewing motor and sensor values

When you’re not running a program, you can view motor and sensor values using the device browser, as shown in
Figure 1.6.

Figure 1.6: Viewing motor and sensor values

1.2.3 Running a program without a computer

You can run previously downloaded programs directly from the EV3 Brick.
To do so, find the program using the file browser on the EV3 screen and press the center button key to start the program
as shown in Figure 1.7.

1.2.4 Going back to the original firmware

You can go back to the LEGO® firmware and your LEGO programs at any time. To do so:
1. Turn the EV3 Brick off as shown above.

6
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Figure 1.7: Starting a program using the buttons on the EV3 Brick

2. Wait for the screen and brick status light to turn off.
3. Remove the microSD card.
4. Turn the EV3 on.

1.3 Creating and running programs

Now that you’ve set up your computer and EV3 Brick, you’re ready to start writing programs.
To make it easier to create and manage your programs, let’s first have a quick look at how MicroPython projects and
programs for your EV3 robots are organized.
Programs are organized into project folders, as shown in Figure 1.8. A project folder is a directory on your computer
that contains the main program (main.py) and other optional scripts or files. This project folder and all of its contents
will be copied to the EV3 Brick, where the main program will be run.
This page shows you how to create such a project and how to transfer it to the EV3 Brick.

Figure 1.8: A project contains a program called main.py and optional resources like sounds or MicroPython modules.

7
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.3.1 Creating a new project

To create a new project, open the EV3 MicroPython tab and click create a new project, as shown in Figure 1.9. Enter
a project name in the text field that appears and press Enter. When prompted, choose a location for this program and
confirm by clicking choose folder.

Figure 1.9: Creating a new project. This example is called getting_started, but you can choose any name.

When you create a new project, it already includes a file called main.py. To see its contents and to modify it, open it
from the file browser as shown in Figure 1.10. This is where you’ll write your programs.
If you are new to MicroPython programming, we recommend that you keep the existing code in place and add your
code to it.

Figure 1.10: Opening the default main.py program.

8
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.3.2 Opening an existing project

To open a project you created previously, click File and click Open Folder, as shown in Figure 1.11. Next, navigate
to your previously created project folder and click OK. You can also open your recently used projects using the Open
Recent menu option.

Figure 1.11: Opening a previously created project.

1.3.3 Connecting to the EV3 Brick with Visual Studio Code

To be able to transfer your code to the EV3 Brick, you’ll first need to connect the EV3 Brick to your computer with
the mini-USB cable and configure the connection with Visual Studio Code. To do so:
• Turn the EV3 Brick on
• Connect the EV3 Brick to your computer with the mini-USB cable
• Configure the USB connection as shown in Figure 1.12.

1.3.4 Downloading and running a program

You can press the F5 key to run the program. Alternatively, you can start it manually by going to the debug tab and
clicking the green start arrow, as shown in Figure 1.13.
When the program starts, a pop-up toolbar allows you to stop the program if necessary. You can also stop the program
at any time using the back button on the EV3 Brick.
If your program produces any output with the print command, this is shown in the output window.

9
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Figure 1.12: Configuring the USB connection between the computer and the EV3 Brick

Figure 1.13: Running a program

10
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.3.5 Expanding the example program

Now that you’ve run the basic code template, you can expand the program to make a motor move. First, attach a Large
Motor to Port B on the EV3 Brick, as shown in Figure 1.14.

Figure 1.14: The EV3 Brick with a Large Motor attached to port B.

Next, edit main.py to make it look like this:

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.parameters import Port

# Create your objects here

# Initialize the EV3 Brick.


ev3 = EV3Brick()

# Initialize a motor at port B.


test_motor = Motor(Port.B)

# Write your program here

(continues on next page)

11
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Play a sound.
ev3.speaker.beep()

# Run the motor up to 500 degrees per second. To a target angle of 90 degrees.
test_motor.run_target(500, 90)

# Play another beep sound.


ev3.speaker.beep(frequency=1000, duration=500)

This program makes your robot beep, rotate the motor, and beep again with a higher pitched tone. Run the program to
make sure that it works as expected.

1.3.6 Managing files on the EV3 Brick

After you’ve downloaded a project to the EV3 Brick, you can run, delete, or back up programs stored on it using the
device browser as shown in Figure 1.15.

Figure 1.15: Using the EV3 device browser to manage files on your EV3 Brick

12
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.4 Accessing advanced EV3 features

MicroPython runs on top of ev3dev, which is a specific version of Linux. Linux is an operating system. (Other
popular operating systems are Microsoft Windows and Apple macOS.) This means that your EV3 is almost like a real
computer, just much smaller.

Note: If you just want to write MicroPython programs, you can skip the remaining sections.
The remaining sections are aimed at curious users who want go beyond MicroPython and access some of the other
built-in features of Linux and ev3dev.

1.4.1 The Linux command line

Although your EV3 Brick is quite like a real computer, you do not interact with it using a big screen and a mouse.
Instead, you can access files and programs on it using the command line. It is also called the terminal.
Follow the steps in Figure 1.16 to access the command line. Now you can enter commands by typing them in and
pressing enter.

Figure 1.16: Opening the Linux command line and running the ls command.

Running basic commands


For example, if you type the following command and press enter:

ls

then you will see the contents of the current folder. Figure 1.16 shows the result: it listed the project folder of the
getting_started project that we just ran.
If you type the following command and press enter:

exit

then the command line will be closed. Alternatively, click the garbage icon shown in Figure 1.16.

13
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

You can copy text from the command line by selecting it and then pressing ctrl shift c. You can paste text into
the command line using ctrl shift v.
Running commands as an administrator
Some commands require a password to run. This is similar to administrative tasks on your computer or tablet, such as
installing a new app. These commands work like any other command, but you add sudo in front of them.
As an exercise, you can run the following command to turn the EV3 Brick off:

sudo poweroff

You will be prompted for a password. Type maker and then press Enter.

Warning: Only run commands with sudo if you know what you are doing.

Learning more about the command line


To learn more about the command line and many of the available commands, we recommend reading the beginner-
friendly free ebook called The Linux Command Line.
To learn more about ev3dev-specific tips and tricks, visit the ev3dev website.

1.4.2 Changing the EV3 Brick name

When you search for your EV3 using Visual Studio Code, you see all EV3 Bricks listed by their name. By default, all
EV3 Bricks are named ev3dev. Follow these steps to change that name:
1. Open Visual Studio Code and connect to your EV3 as usual.
2. Read the steps above about running commands as an administrator.
3. Think of a good name. In this example, we’ll call it autonomous-vehicle2
4. Enter the following command and press enter:

sudo hostnamectl set-hostname autonomous-vehicle2

5. Reboot the EV3 Brick for the change to take effect.


6. You may need to reboot your computer as well.
EV3 Brick names should only contain lowercase letters a through z, the digits 0 through 9, and the hyphen -. It must
start with a letter or digit. It cannot include spaces or other symbols.

1.5 Upgrading from v1.0 to v2.0

EV3 MicroPython version 2.0 was released on May 18, 2020.


This section is for users who have previously used LEGO MINDSTORMS EV3 MicroPython v1.0. We’ll explain
what’s changed and how you can upgrade to benefit from the latest improvements.
If you are a new user and you just got started using version 2.0, you may skip this section.

14
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

1.5.1 Upgrading the microSD Card

To upgrade, download the latest microSD card file and install it using the standard instructions.
Note that this will erase all your existing files on the SD Card. Before you upgrade, make sure that you still have all
your projects on your computer. If not, you can upload files back to your computer using these instructions.
As with any software update, be careful about when you update. For example, if you developed your code using
version v1.0 and you are halfway into your robotics competition season, you may want to stick with v1.0 for now.

1.5.2 Upgrading your existing programs

Most changes in v2.0 are new features, like support for additional sensors. Naturally, this will not affect your existing
code. However, some changes were made to existing features to improve performance.
All originally documented features in v1.0 will still work after you upgrade. This means that most programs originally
made for v1.0 will work with the v2.0 microSD card image without any changes.
To try this, simply download and run your original code as you did before.
However, it is recommended that you upgrade both the microSD card and your programs at the same time to ensure
everything works as expected.

The new EV3Brick() class replaces the ev3brick module

Version 2.0 introduces the EV3Brick() class. You can use it instead of the old ev3brick module. The old
ev3brick module can still be used, but it is no longer recommended or documented.
The EV3Brick() class improves the speed and reliability of the EV3 screen and the EV3 speaker. It also adds
functionality like speech and drawing shapes. The default font size is also bigger to make it easier to read text on the
screen.
You can use the following table as a starting point to upgrade your scripts. See the EV3Brick() class documentation
for complete details of all methods and arguments.

15
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Action v1.0 v2.0

from pybricks import from pybricks.hubs import


Initialize
˓→ev3brick as brick ˓→EV3Brick
your EV3
ev3 = EV3Brick()

brick.light(Color.RED) ev3.light.on(Color.RED)
Light on

brick.light(None) ev3.light.off()
Light off

if Button.LEFT in brick. if Button.LEFT in ev3.


Read
˓→buttons(): ˓→buttons.pressed():
Buttons print("Left is print("Left is
˓→pressed.") ˓→pressed.")

brick.sound.beep() ev3.speaker.beep()
Play a
beep

brick.sound. ev3.speaker.play_
Play a
˓→file(SoundFile.HELLO) ˓→file(SoundFile.HELLO)
sound file

ev3.speaker.say("I can
Text to
˓→say anything!")
speech

ev3.speaker.play_notes([
Play
˓→'C4/4', 'G4/4'])
notes

brick.display.text("Hello! ev3.screen.draw_text(50,
Write text
˓→", (50, 60)) ˓→60, "Hello!")
at a given
position

brick.display.text("Hello ev3.screen.print("Hello")
Write text
˓→") ev3.screen.print("world!")
and scroll brick.display.text("world!
automatically ˓→")

from pybricks.media.
Change font
˓→ev3dev import Font
size
big_font = Font(size=24)
ev3.screen.set_font(big_ 16
˓→font)

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors

from pybricks.parameters from pybricks.media.


Pybricks Modules and Examples Version v3.0.0a3

Other internal changes to existing features

• Most methods of the Motor() class now have Stop.HOLD as the default instead of Stop.COAST. This
improves accuracy in most applications. You can still select Stop.COAST if you like.
• The internal PID controllers for the motors are more accurate than before. If you give a motor command when
it is already running, it smoothly adjusts the speed to the newly given command. This works even if you keep
adjusting the speed in a fast loop.
• Methods to configure motor settings have changed. You can change settings using the control attribute now. The
old settings setters continue to exist in the implementation, but they are no longer documented.
• So-called Python keyword arguments are now supported. Previously, you could only enter the argument values.
For example:

my_motor.run_angle(500, 90, Stop.HOLD, False)

This is still possible. But you can now choose to omit optional arguments and specify others with keywords.
This can make your code easier to read. For example:

my_motor.run_angle(500, 90, wait=False)

• It is no longer necessary to import pybricks.tools.print. The print function is now built-in. It works
just like Python or MicroPython.
• Most parameters in the parameters now have a specific type and representation. For example, suppose you
measure a color and print the result. If you do print(Color.RED), you will see the parameter instead of a
technical number.
• Sound and image files have moved to a dedicated media module. Importing them from the old location will
continue to work in this release, to make sure existing scripts will still work.
Installing an older version of the Visual Studio Code extension
The Visual Studio Code extension and this documentation are updated automatically. You can still use your existing
scripts with the updated extension. If you absolutely wish to keep the old version, look for the EV3 extension on the
extension tab, click the gear icon, and click install another version.

17
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 2

Powered Up Quick Start

This page shows how you can install Pybricks on your hub and run your first program. When you’re ready, browse
through the Pybricks Modules in the left hand menu to modify the example program.

Note:
• This is still in beta! Not everything may work as expected yet.
• We welcome your questions, feedback and bug reports on our support page.
• For now, sensors/motors are detected automatically only once. So if you change the cables, you have to turn the
hub off and on again. You can turn it off by holding down the button for about 5 seconds.

2.1 Installing Google Chrome

Writing Pybricks programs requires a web browser with web Bluetooth functionality. Currently, only Google Chrome
supports this. Download Google Chrome from here.

18
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Show/hide extra steps for Linux users


• In Google Chrome go to chrome://flags/.
• Search for Experimental Web Platform features and enable it.
• Installing firmware will be slow if you have BlueZ < v5.51. Check your version: bluetoothd -v.

2.2 Installing the Pybricks firmware

Pybricks uses an improved firmware that can run autonomous programs. Installing it is easy:
1. Make sure you use fresh batteries.
2. Unplug all motors and sensors.
3. Follow the steps in the video below.
Click to show/hide written step-by-step instructions.
• Make sure you use fresh batteries.
• Unplug all motors and sensors.
• Make sure the hub is off.
• Press and hold the green button.
• Wait for the light to blink, but keep holding the button.
• On the Pybricks Code page, click the firmware update button.
• Select the LEGO Bootloader and click Pair.
• The light should change to a red/green/blue sequence.
• You can now release the button.
• Wait for the update to finish, indicated by a blinking blue light.
• If you use the recommended browser, this will take about 90 seconds.

2.3 Running programs

Once the firmware is installed, you can start coding! Use the Bluetooth button to search for and connect to your
Pybricks Hub. Then press run to start your program.
To get started, just copy and paste this snippet:

from pybricks.pupdevices import Motor


from pybricks.parameters import Port, Stop
from pybricks.tools import wait

# We'll use two motors. One is a dial


# to set the speed of the other motor.
motor = Motor(Port.B)
dial = Motor(Port.A)

# Say hello :)
print("Hello, Pybricks!")
(continues on next page)

19
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

20
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# First, we'll move the dial to zero.


dial.run_target(500, 0, Stop.COAST)

while True:
# Set the speed based on dial angle
speed = dial.angle()*3
if abs(speed) < 100:
speed = 0

# Run motor at desired speed


motor.run(speed)

# Wait briefly, then repeat


wait(10)

Show/hide beta steps to save a program permanently


Saving a program permanently (BETA)

Note:
• This functionality is in beta. It is currently only recommended for advanced users. In the long run, we’ll make
this easy to do with the online editor.
• All LEGO motors and sensors need a few seconds to boot. You don’t normally notice because you spend that
time connecting. But this is way faster. So if you experience problems, give your hub a few seconds before you
start your program.

When you run a program the normal way, it is deleted as soon as it’s done. That’s because Powered Up hubs don’t
have a file system to store programs. Fortunately, you can still save a script on the hub by including it in the firmware.
Of course, this is a bit slow to do every time. We recommend the using the standard procedure most of the time. When
you’re happy with your final program, you can save it permanently as described below. To change the program, just
repeat these steps:
1. Sign in to GitHub.
2. Go to our GitHub commits.
3. Click on the green checkmark next to the latest commit. On the dialog that pops up, click details.
4. Then click Artifacts on the right hand side of the page.
5. Download the firmware for your hub. The firmware is a ZIP archive containing the basic firmware and one
main.py script.
6. Modify the main.py file as you like.
7. Drag your modified ZIP file onto the firmware update button of the online editor.
8. The update now proceeds as usual.
Once installed, you can start that program with the green button. No connection required!

21
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

2.4 Restoring the LEGO Firmware

Pybricks uses the same update method as the LEGO apps; just with a different firmware file. This means you can go
back to the original firmware any time. As shown in the video below, just put the hub in update mode and connect
using a LEGO app.
This video shows the Powered Up app in create mode. It has firmware for all hubs. As usual, you may need to restart
the app to detect the hub. If it fails, try again with fresh batteries.

22
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 3

SPIKE Prime / Robot Inventor

Coming soon!

23
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 4

hubs – Programmable Hubs

4.1 BOOST Move Hub

class MoveHub
LEGO® Powered Up Move Hub.

Using the hub status light

Show/hide examples
Example 1: Turning the light on and off
from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = MoveHub()
(continues on next page)

24
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Turn the light on and off 5 times.


for i in range(5):

hub.light.on(Color.RED)
wait(1000)

hub.light.off()
wait(500)

Example 2: Changing brightness and using custom colors


from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = MoveHub()

# Use your own custom color.


hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.


for hue in range(360):
hub.light.on(Color(hue))
wait(10)

Example 3: Making the light blink


from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub


hub = MoveHub()

# Keep blinking red on and off.


hub.light.blink(Color.RED, [500, 500])

wait(10000)

# Keep blinking green slowly and then quickly.


hub.light.blink(Color.GREEN, [500, 500, 50, 900])

wait(10000)

Example 4: Creating light animations


from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = MoveHub()

(continues on next page)

25
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, None], interval=500)

wait(10000)

# Cycle through a rainbow of colors.


hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)

wait(10000)

light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
light.off()
Turns off the light.
light.blink(color, durations)
Blinks the light at a given color by turning it on and off for given durations.
The light keeps blinking indefinitely while the rest of your program keeps running.
This method provides a simple way to make basic but useful patterns. For more generic and multi-color
patterns, use animate() instead.
Parameters
• color (Color) – Color of the light.
• durations (list) – List of (time: ms) values of the form [on_1, off_1, on_2,
off_2, ...].
light.animate(colors, interval)
Animates the light with a list of colors. The next color in the list is shown after the given interval.
The animation runs in the background while the rest of your program keeps running. When the animation
completes, it repeats.
Parameters
• colors (list) – List of Color values.
• interval (time: ms) – Time between color updates.

Using the battery

battery.voltage()
Gets the voltage of the battery.
Returns Battery voltage.
Return type voltage: mV
battery.current()
Gets the current supplied by the battery.
Returns Battery current.
Return type current: mA

26
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

4.2 City Hub

class CityHub
LEGO® Powered Up City Hub.

Using the hub status light

Show/hide examples
Example 1: Turning the light on and off
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = CityHub()

# Turn the light on and off 5 times.


for i in range(5):

hub.light.on(Color.RED)
wait(1000)

hub.light.off()
wait(500)

Example 2: Changing brightness and using custom colors


from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = CityHub()

# Show the color at 30% brightness.


hub.light.on(Color.RED * 0.3)

wait(2000)

(continues on next page)

27
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Use your own custom color.
hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.


for hue in range(360):
hub.light.on(Color(hue))
wait(10)

Example 3: Making the light blink

from pybricks.hubs import CityHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub


hub = CityHub()

# Keep blinking red on and off.


hub.light.blink(Color.RED, [500, 500])

wait(10000)

# Keep blinking green slowly and then quickly.


hub.light.blink(Color.GREEN, [500, 500, 50, 900])

wait(10000)

Example 4: Creating light animations

from pybricks.hubs import CityHub


from pybricks.parameters import Color
from pybricks.tools import wait
from math import sin, pi

# Initialize the hub.


hub = CityHub()

# Make an animation with multiple colors.


hub.light.animate([Color.RED, Color.GREEN, None], interval=500)

wait(10000)

# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)

wait(10000)

# Cycle through a rainbow of colors.


hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)

wait(10000)

light.on(color)
Turns on the light at the specified color.

28
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Parameters color (Color) – Color of the light.


light.off()
Turns off the light.
light.blink(color, durations)
Blinks the light at a given color by turning it on and off for given durations.
The light keeps blinking indefinitely while the rest of your program keeps running.
This method provides a simple way to make basic but useful patterns. For more generic and multi-color
patterns, use animate() instead.
Parameters
• color (Color) – Color of the light.
• durations (list) – List of (time: ms) values of the form [on_1, off_1, on_2,
off_2, ...].
light.animate(colors, interval)
Animates the light with a list of colors. The next color in the list is shown after the given interval.
The animation runs in the background while the rest of your program keeps running. When the animation
completes, it repeats.
Parameters
• colors (list) – List of Color values.
• interval (time: ms) – Time between color updates.

Using the battery

battery.voltage()
Gets the voltage of the battery.
Returns Battery voltage.
Return type voltage: mV
battery.current()
Gets the current supplied by the battery.
Returns Battery current.
Return type current: mA

4.3 Technic Hub

class TechnicHub
LEGO® Technic Hub.

Using the hub status light

Show/hide examples
Example 1: Turning the light on and off

29
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.hubs import TechnicHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = TechnicHub()

# Turn the light on and off 5 times.


for i in range(5):

hub.light.on(Color.RED)
wait(1000)

hub.light.off()
wait(500)

Example 2: Changing brightness and using custom colors

from pybricks.hubs import TechnicHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = TechnicHub()

# Show the color at 30% brightness.


hub.light.on(Color.RED * 0.3)

wait(2000)

# Use your own custom color.


hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.


for hue in range(360):
hub.light.on(Color(hue))
wait(10)

Example 3: Making the light blink

30
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.hubs import TechnicHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub


hub = TechnicHub()

# Keep blinking red on and off.


hub.light.blink(Color.RED, [500, 500])

wait(10000)

# Keep blinking green slowly and then quickly.


hub.light.blink(Color.GREEN, [500, 500, 50, 900])

wait(10000)

Example 4: Creating light animations

from pybricks.hubs import TechnicHub


from pybricks.parameters import Color
from pybricks.tools import wait
from math import sin, pi

# Initialize the hub.


hub = TechnicHub()

# Make an animation with multiple colors.


hub.light.animate([Color.RED, Color.GREEN, None], interval=500)

wait(10000)

# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)

wait(10000)

# Cycle through a rainbow of colors.


hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)

wait(10000)

light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
light.off()
Turns off the light.
light.blink(color, durations)
Blinks the light at a given color by turning it on and off for given durations.
The light keeps blinking indefinitely while the rest of your program keeps running.
This method provides a simple way to make basic but useful patterns. For more generic and multi-color
patterns, use animate() instead.
Parameters

31
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• color (Color) – Color of the light.


• durations (list) – List of (time: ms) values of the form [on_1, off_1, on_2,
off_2, ...].
light.animate(colors, interval)
Animates the light with a list of colors. The next color in the list is shown after the given interval.
The animation runs in the background while the rest of your program keeps running. When the animation
completes, it repeats.
Parameters
• colors (list) – List of Color values.
• interval (time: ms) – Time between color updates.

Using the battery

battery.voltage()
Gets the voltage of the battery.
Returns Battery voltage.
Return type voltage: mV
battery.current()
Gets the current supplied by the battery.
Returns Battery current.
Return type current: mA

4.4 SPIKE Prime Hub

class PrimeHub
LEGO® SPIKE Prime Hub.
This class is identical to the InventorHub class, except for the name.

32
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Using the hub status light

Show/hide examples
Example 1: Turning the light on and off

from pybricks.hubs import PrimeHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Turn the light on and off 5 times.


for i in range(5):

hub.light.on(Color.RED)
wait(1000)

hub.light.off()
wait(500)

Example 2: Changing brightness and using custom colors

from pybricks.hubs import PrimeHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Show the color at 30% brightness.


hub.light.on(Color.RED * 0.3)

wait(2000)

# Use your own custom color.


hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.


for hue in range(360):
hub.light.on(Color(hue))
wait(10)

Example 3: Making the light blink

from pybricks.hubs import PrimeHub


from pybricks.parameters import Color
from pybricks.tools import wait
(continues on next page)

33
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Initialize the hub


hub = PrimeHub()

# Keep blinking red on and off.


hub.light.blink(Color.RED, [500, 500])

wait(10000)

# Keep blinking green slowly and then quickly.


hub.light.blink(Color.GREEN, [500, 500, 50, 900])

wait(10000)

Example 4: Creating light animations

from pybricks.hubs import PrimeHub


from pybricks.parameters import Color
from pybricks.tools import wait
from math import sin, pi

# Initialize the hub.


hub = PrimeHub()

# Make an animation with multiple colors.


hub.light.animate([Color.RED, Color.GREEN, None], interval=500)

wait(10000)

# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)

wait(10000)

# Cycle through a rainbow of colors.


hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)

wait(10000)

light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
light.off()
Turns off the light.
light.blink(color, durations)
Blinks the light at a given color by turning it on and off for given durations.
The light keeps blinking indefinitely while the rest of your program keeps running.
This method provides a simple way to make basic but useful patterns. For more generic and multi-color
patterns, use animate() instead.
Parameters
• color (Color) – Color of the light.

34
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• durations (list) – List of (time: ms) values of the form [on_1, off_1, on_2,
off_2, ...].
light.animate(colors, interval)
Animates the light with a list of colors. The next color in the list is shown after the given interval.
The animation runs in the background while the rest of your program keeps running. When the animation
completes, it repeats.
Parameters
• colors (list) – List of Color values.
• interval (time: ms) – Time between color updates.

Using the light matrix display

Show/hide examples
Example 1: Displaying images

from pybricks.hubs import PrimeHub


from pybricks.tools import wait
from pybricks.parameters import Icon

# Initialize the hub.


hub = PrimeHub()

# Display a big arrow pointing up.


hub.display.image(Icon.UP)

# Wait so we can see what is displayed.


wait(2000)

# Display a heart at half brightness.


hub.display.image(Icon.HEART / 2)

# Wait so we can see what is displayed.


wait(2000)

35
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Example 2: Displaying numbers


from pybricks.hubs import PrimeHub
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Count from 0 to 99.


for i in range(100):
hub.display.number(i)
wait(200)

Example 3: Displaying text


from pybricks.hubs import PrimeHub
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Display the letter A for two seconds.


hub.display.char('A')
wait(2000)

# Display text, one letter at a time.


hub.display.text('Hello, world!')

Example 4: Displaying individual pixels


from pybricks.hubs import PrimeHub
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Turn off all the pixels.


hub.display.off()

# Turn on the pixel at row 1, column 2.


hub.display.pixel(1, 2)
wait(2000)

# Turn on the pixel at row 2, column 4, at 50% brightness.


hub.display.pixel(2, 4, 50)
wait(2000)

# Turn off the pixel at row 1, column 2.


hub.display.pixel(1, 2, 0)
wait(2000)

Example 5: Changing the display orientation


from pybricks.hubs import PrimeHub
from pybricks.tools import wait
from pybricks.parameters import Side

# Initialize the hub.


(continues on next page)

36
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


hub = PrimeHub()

# Rotate the display. Now right is up.


hub.display.orientation(up=Side.RIGHT)

# Display a number. This will be shown sideways.


hub.display.number(23)

# Wait so we can see what is displayed.


wait(10000)

Example 6: Making your own images


from pybricks.hubs import PrimeHub
from pybricks.tools import wait
from pybricks.geometry import Matrix

# Initialize the hub.


hub = PrimeHub()

# Make a square that is bright on the outside and faint in the middle.
SQUARE = Matrix([
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
])

# Display the square.


hub.display.image(SQUARE)
wait(3000)

# Make an image using a Python list comprehension. In this image, the


# brightness of each pixel is the sum of the row and column index. So the
# light is faint in the top left and bright in the bottom right.
GRADIENT = Matrix([[(r + c) for c in range(5)] for r in range(5)]) * 12.5

# Display the generated gradient.


hub.display.image(GRADIENT)
wait(3000)

Example 7: Combining images to make expressions


from pybricks.hubs import PrimeHub
from pybricks.parameters import Icon, Side
from pybricks.tools import wait

from urandom import randint

# Initialize the hub.


hub = PrimeHub()
hub.display.orientation(up=Side.RIGHT)

while True:

# Start with random left brow: up or down.


(continues on next page)

37
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


if randint(0, 100) < 70:
brows = Icon.EYE_LEFT_BROW*0.5
else:
brows = Icon.EYE_LEFT_BROW_UP*0.5

# Add random right brow: up or down.


if randint(0, 100) < 70:
brows += Icon.EYE_RIGHT_BROW*0.5
else:
brows += Icon.EYE_RIGHT_BROW_UP*0.5

for i in range(3):
# Display eyes open plus the random brows.
hub.display.image(Icon.EYE_LEFT + Icon.EYE_RIGHT + brows)
wait(2000)

# Display eyes blinked plus the random brows.


hub.display.image(Icon.EYE_LEFT_BLINK*0.7 + Icon.EYE_RIGHT_BLINK*0.7 +
˓→brows)

wait(200)

Example 8: Displaying animations

from pybricks.hubs import PrimeHub


from pybricks.parameters import Icon
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

# Turn the hub light off (optional).


hub.light.off()

# Create a list of intensities from 0 to 100 and back.


brightness = list(range(0, 100, 4)) + list(range(100, 0, -4))

# Create an animation of the heart icon with changing brightness.


hub.display.animate([Icon.HEART * i/100 for i in brightness], 30)

# The animation repeats in the background. Here we just wait.


while True:
wait(100)

display.orientation(up)
Sets the orientation of the light matrix display.
Only new displayed images and pixels are affected. The existing display contents remain unchanged.
Parameters top (Side) – Which side of the light matrix display is “up” in your design. Choose
Side.TOP, Side.LEFT, Side.RIGHT, or Side.BOTTOM.
display.off()
Turns off all the pixels.
display.pixel(row, column, brightness=100)
Turns on one pixel at the specified brightness.
Parameters

38
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• row (int) – Vertical grid index, starting at 0 from the top.


• column (int) – Horizontal grid index, starting at 0 from the left.
• brightness (brightness: %) – Brightness of the pixel.
display.image(matrix)
Displays an image, represented by a matrix of brightness: % values.
Parameters matrix (Matrix) – Matrix of intensities (brightness: %). A 2D list is also ac-
cepted.
display.animate(matrices, interval)
Displays an animation made using a list of images.
Each image has the same format as above. Each image is shown for the given interval. The animation
repeats forever while the rest of your program keeps running.
Parameters
• matrix (list) – List of Matrix of intensities.
• interval (time: ms) – Time to display each image in the list.
display.number(number)
Displays a number in the range -99 to 99.
A minus sign (-) is shown as a faint dot in the center of the display. Numbers greater than 99 are shown
as >. Numbers less than -99 are shown as <.
Parameters number (int) – The number to be displayed.
display.char(char)
Displays a character or symbol on the light grid. This may be any letter (a–z), capital letter (A–Z) or one
of the following symbols: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}.
Parameters character (str) – The character or symbol to be displayed.
display.text(text, on=500, off=50)
Displays a text string, one character at a time, with a pause between each character. After the last character
is shown, all lights turn off.
Parameters
• text (str) – The text to be displayed.
• on (time: ms) – For how long a character is shown.
• off (time: ms) – For how long the display is off between characters.

Using the buttons

Show/hide examples
Example: Detecting button presses

from pybricks.hubs import PrimeHub


from pybricks.parameters import Button, Icon
from pybricks.tools import wait

# Initialize the hub.


hub = PrimeHub()

(continues on next page)

39
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Wait for any button to be pressed, and save the result.
pressed = []
while not any(pressed):
pressed = hub.buttons.pressed()
wait(10)

# Display a circle.
hub.display.image(Icon.CIRCLE)

# Wait for all buttons to be released.


while any(hub.buttons.pressed()):
wait(10)

# Display an arrow to indicate which button was pressed.


if Button.LEFT in pressed:
hub.display.image(Icon.ARROW_LEFT_DOWN)
elif Button.RIGHT in pressed:
hub.display.image(Icon.ARROW_RIGHT_DOWN)
elif Button.BT in pressed:
hub.display.image(Icon.ARROW_RIGHT_UP)

wait(3000)

buttons.pressed()
Checks which buttons are currently pressed.
Returns List of pressed buttons.
Return type List of Button

Using the battery

battery.voltage()
Gets the voltage of the battery.

40
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns Battery voltage.


Return type voltage: mV
battery.current()
Gets the current supplied by the battery.
Returns Battery current.
Return type current: mA

4.5 MINDSTORMS Inventor Hub

class InventorHub
LEGO® MINDSTORMS Inventor Hub.
This class is identical to the PrimeHub class, except for the name.

Using the hub status light

Show/hide examples
Example 1: Turning the light on and off

from pybricks.hubs import InventorHub


from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = InventorHub()

# Turn the light on and off 5 times.


for i in range(5):

hub.light.on(Color.RED)
(continues on next page)

41
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


wait(1000)

hub.light.off()
wait(500)

Example 2: Changing brightness and using custom colors


from pybricks.hubs import InventorHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.


hub = InventorHub()

# Show the color at 30% brightness.


hub.light.on(Color.RED * 0.3)

wait(2000)

# Use your own custom color.


hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.


for hue in range(360):
hub.light.on(Color(hue))
wait(10)

Example 3: Making the light blink


from pybricks.hubs import InventorHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub


hub = InventorHub()

# Keep blinking red on and off.


hub.light.blink(Color.RED, [500, 500])

wait(10000)

# Keep blinking green slowly and then quickly.


hub.light.blink(Color.GREEN, [500, 500, 50, 900])

wait(10000)

Example 4: Creating light animations


from pybricks.hubs import InventorHub
from pybricks.parameters import Color
from pybricks.tools import wait
from math import sin, pi

# Initialize the hub.


hub = InventorHub()
(continues on next page)

42
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Make an animation with multiple colors.


hub.light.animate([Color.RED, Color.GREEN, None], interval=500)

wait(10000)

# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)

wait(10000)

# Cycle through a rainbow of colors.


hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)

wait(10000)

light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
light.off()
Turns off the light.
light.blink(color, durations)
Blinks the light at a given color by turning it on and off for given durations.
The light keeps blinking indefinitely while the rest of your program keeps running.
This method provides a simple way to make basic but useful patterns. For more generic and multi-color
patterns, use animate() instead.
Parameters
• color (Color) – Color of the light.
• durations (list) – List of (time: ms) values of the form [on_1, off_1, on_2,
off_2, ...].
light.animate(colors, interval)
Animates the light with a list of colors. The next color in the list is shown after the given interval.
The animation runs in the background while the rest of your program keeps running. When the animation
completes, it repeats.
Parameters
• colors (list) – List of Color values.
• interval (time: ms) – Time between color updates.

Using the light matrix display

Show/hide examples
Example 1: Displaying images

43
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.hubs import InventorHub


from pybricks.tools import wait
from pybricks.parameters import Icon

# Initialize the hub.


hub = InventorHub()

# Display a big arrow pointing up.


hub.display.image(Icon.UP)

# Wait so we can see what is displayed.


wait(2000)

# Display a heart at half brightness.


hub.display.image(Icon.HEART / 2)

# Wait so we can see what is displayed.


wait(2000)

Example 2: Displaying numbers


from pybricks.hubs import InventorHub
from pybricks.tools import wait

# Initialize the hub.


hub = InventorHub()

# Count from 0 to 99.


for i in range(100):
hub.display.number(i)
wait(200)

Example 3: Displaying text


from pybricks.hubs import InventorHub
from pybricks.tools import wait

# Initialize the hub.


(continues on next page)

44
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


hub = InventorHub()

# Display the letter A for two seconds.


hub.display.char('A')
wait(2000)

# Display text, one letter at a time.


hub.display.text('Hello, world!')

Example 4: Displaying individual pixels


from pybricks.hubs import InventorHub
from pybricks.tools import wait

# Initialize the hub.


hub = InventorHub()

# Turn off all the pixels.


hub.display.off()

# Turn on the pixel at row 1, column 2.


hub.display.pixel(1, 2)
wait(2000)

# Turn on the pixel at row 2, column 4, at 50% brightness.


hub.display.pixel(2, 4, 50)
wait(2000)

# Turn off the pixel at row 1, column 2.


hub.display.pixel(1, 2, 0)
wait(2000)

Example 5: Changing the display orientation


from pybricks.hubs import InventorHub
from pybricks.tools import wait
from pybricks.parameters import Side

# Initialize the hub.


hub = InventorHub()

# Rotate the display. Now right is up.


hub.display.orientation(up=Side.RIGHT)

# Display a number. This will be shown sideways.


hub.display.number(23)

# Wait so we can see what is displayed.


wait(10000)

Example 6: Making your own images


from pybricks.hubs import InventorHub
from pybricks.tools import wait
from pybricks.geometry import Matrix

# Initialize the hub.


(continues on next page)

45
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


hub = InventorHub()

# Make a square that is bright on the outside and faint in the middle.
SQUARE = Matrix([
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
])

# Display the square.


hub.display.image(SQUARE)
wait(3000)

# Make an image using a Python list comprehension. In this image, the


# brightness of each pixel is the sum of the row and column index. So the
# light is faint in the top left and bright in the bottom right.
GRADIENT = Matrix([[(r + c) for c in range(5)] for r in range(5)]) * 12.5

# Display the generated gradient.


hub.display.image(GRADIENT)
wait(3000)

Example 7: Combining images to make expressions


from pybricks.hubs import InventorHub
from pybricks.parameters import Icon, Side
from pybricks.tools import wait

from urandom import randint

# Initialize the hub.


hub = InventorHub()
hub.display.orientation(up=Side.RIGHT)

while True:

# Start with random left brow: up or down.


if randint(0, 100) < 70:
brows = Icon.EYE_LEFT_BROW*0.5
else:
brows = Icon.EYE_LEFT_BROW_UP*0.5

# Add random right brow: up or down.


if randint(0, 100) < 70:
brows += Icon.EYE_RIGHT_BROW*0.5
else:
brows += Icon.EYE_RIGHT_BROW_UP*0.5

for i in range(3):
# Display eyes open plus the random brows.
hub.display.image(Icon.EYE_LEFT + Icon.EYE_RIGHT + brows)
wait(2000)

# Display eyes blinked plus the random brows.


hub.display.image(Icon.EYE_LEFT_BLINK*0.7 + Icon.EYE_RIGHT_BLINK*0.7 +
˓→brows) (continues on next page)

46
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


wait(200)

Example 8: Displaying animations

from pybricks.hubs import InventorHub


from pybricks.parameters import Icon
from pybricks.tools import wait

# Initialize the hub.


hub = InventorHub()

# Turn the hub light off (optional).


hub.light.off()

# Create a list of intensities from 0 to 100 and back.


brightness = list(range(0, 100, 4)) + list(range(100, 0, -4))

# Create an animation of the heart icon with changing brightness.


hub.display.animate([Icon.HEART * i/100 for i in brightness], 30)

# The animation repeats in the background. Here we just wait.


while True:
wait(100)

display.orientation(up)
Sets the orientation of the light matrix display.
Only new displayed images and pixels are affected. The existing display contents remain unchanged.
Parameters top (Side) – Which side of the light matrix display is “up” in your design. Choose
Side.TOP, Side.LEFT, Side.RIGHT, or Side.BOTTOM.
display.off()
Turns off all the pixels.
display.pixel(row, column, brightness=100)
Turns on one pixel at the specified brightness.
Parameters
• row (int) – Vertical grid index, starting at 0 from the top.
• column (int) – Horizontal grid index, starting at 0 from the left.
• brightness (brightness: %) – Brightness of the pixel.
display.image(matrix)
Displays an image, represented by a matrix of brightness: % values.
Parameters matrix (Matrix) – Matrix of intensities (brightness: %). A 2D list is also ac-
cepted.
display.animate(matrices, interval)
Displays an animation made using a list of images.
Each image has the same format as above. Each image is shown for the given interval. The animation
repeats forever while the rest of your program keeps running.
Parameters
• matrix (list) – List of Matrix of intensities.

47
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• interval (time: ms) – Time to display each image in the list.


display.number(number)
Displays a number in the range -99 to 99.
A minus sign (-) is shown as a faint dot in the center of the display. Numbers greater than 99 are shown
as >. Numbers less than -99 are shown as <.
Parameters number (int) – The number to be displayed.
display.char(char)
Displays a character or symbol on the light grid. This may be any letter (a–z), capital letter (A–Z) or one
of the following symbols: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}.
Parameters character (str) – The character or symbol to be displayed.
display.text(text, on=500, off=50)
Displays a text string, one character at a time, with a pause between each character. After the last character
is shown, all lights turn off.
Parameters
• text (str) – The text to be displayed.
• on (time: ms) – For how long a character is shown.
• off (time: ms) – For how long the display is off between characters.

Using the buttons

Show/hide examples
Example: Detecting button presses

from pybricks.hubs import InventorHub


from pybricks.parameters import Button, Icon
from pybricks.tools import wait

(continues on next page)

48
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Initialize the hub.
hub = InventorHub()

# Wait for any button to be pressed, and save the result.


pressed = []
while not any(pressed):
pressed = hub.buttons.pressed()
wait(10)

# Display a circle.
hub.display.image(Icon.CIRCLE)

# Wait for all buttons to be released.


while any(hub.buttons.pressed()):
wait(10)

# Display an arrow to indicate which button was pressed.


if Button.LEFT in pressed:
hub.display.image(Icon.ARROW_LEFT_DOWN)
elif Button.RIGHT in pressed:
hub.display.image(Icon.ARROW_RIGHT_DOWN)
elif Button.BT in pressed:
hub.display.image(Icon.ARROW_RIGHT_UP)

wait(3000)

buttons.pressed()
Checks which buttons are currently pressed.
Returns List of pressed buttons.
Return type List of Button

Using the battery

battery.voltage()
Gets the voltage of the battery.
Returns Battery voltage.
Return type voltage: mV
battery.current()
Gets the current supplied by the battery.
Returns Battery current.
Return type current: mA

4.6 MINDSTORMS EV3 Brick

class EV3Brick
LEGO® MINDSTORMS® EV3 Brick.

49
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Using the buttons

buttons.pressed()
Checks which buttons are currently pressed.
Returns List of pressed buttons.
Return type List of Button

Using the brick status light

light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
Show/hide example
Example: Turn the light on and change the color.

#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick


from pybricks.tools import wait
from pybricks.parameters import Color

# Initialize the EV3


ev3 = EV3Brick()

# Turn on a red light


ev3.light.on(Color.RED)

# Wait
wait(1000)

# Turn the light off


ev3.light.off()

light.off()
Turns off the light.

50
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Using the speaker

speaker.beep(frequency=500, duration=100)
Play a beep/tone.
Parameters
• frequency (frequency: Hz) – Frequency of the beep. Frequencies below 100 are treated
as 100.
• duration (time: ms) – Duration of the beep. If the duration is less than 0, then the
method returns immediately and the frequency play continues to play indefinitely.
speaker.play_notes(notes, tempo=120)
Plays a sequence of musical notes.
For example, you can play: ['C4/4', 'C4/4', 'G4/4', 'G4/4'].
Parameters
• notes (iter) – A sequence of notes to be played (see format below).
• tempo (int) – Beats per minute where a quarter note is one beat.
Show/hide musical note format
Each note is a string with the following format:
• The first character is the name of the note, A to G or R for a rest.
• Note names can also include an accidental # (sharp) or b (flat). B#/Cb and E#/Fb are not allowed.
• The note name is followed by the octave number 2 to 8. For example C4 is middle C. The octave
changes to the next number at the note C, for example, B3 is the note below middle C (C4).
• The octave is followed by / and a number that indicates the size of the note. For example /4 is a
quarter note, /8 is an eighth note and so on.
• This can optionally followed by a . to make a dotted note. Dotted notes are 1-1/2 times as long as
notes without a dot.
• The note can optionally end with a _ which is a tie or a slur. This causes there to be no pause between
this note and the next note.
speaker.play_file(file)
Plays a sound file.
Parameters file (str) – Path to the sound file, including the file extension.
speaker.say(text)
Says a given text string.
You can configure the language and voice of the text using set_speech_options().
Parameters text (str) – What to say.
speaker.set_speech_options(language=None, voice=None, speed=None, pitch=None)
Configures speech settings used by the say() method.
Any option that is set to None will not be changed. If an option is set to an invalid value say() will use
the default value instead.
Parameters
• language (str) – Language of the text. For example, you can choose 'en' (English)
or 'de' (German). A list of all available languages is given below.

51
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• voice (str) – The voice to use. For example, you can choose 'f1' (female voice
variant 1) or 'm3' (male voice variant 3). A list of all available voices is given below.
• speed (int) – Number of words per minute.
• pitch (int) – Pitch (0 to 99). Higher numbers make the voice higher pitched and lower
numbers make the voice lower pitched.
Show/hide available languages and voices
You can choose the following languages:
• 'af': Afrikaans
• 'an': Aragonese
• 'bg': Bulgarian
• 'bs': Bosnian
• 'ca': Catalan
• 'cs': Czech
• 'cy': Welsh
• 'da': Danish
• 'de': German
• 'el': Greek
• 'en': English (default)
• 'en-gb': English (United Kingdom)
• 'en-sc': English (Scotland)
• 'en-uk-north': English (United Kingdom, Northern)
• 'en-uk-rp': English (United Kingdom, Received Pronunciation)
• 'en-uk-wmids': English (United Kingdom, West Midlands)
• 'en-us': English (United States)
• 'en-wi': English (West Indies)
• 'eo': Esperanto
• 'es': Spanish
• 'es-la': Spanish (Latin America)
• 'et': Estonian
• 'fa': Persian
• 'fa-pin': Persian
• 'fi': Finnish
• 'fr-be': French (Belgium)
• 'fr-fr': French (France)
• 'ga': Irish
• 'grc': Greek
• 'hi': Hindi

52
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• 'hr': Croatian
• 'hu': Hungarian
• 'hy': Armenian
• 'hy-west': Armenian (Western)
• 'id': Indonesian
• 'is': Icelandic
• 'it': Italian
• 'jbo': Lojban
• 'ka': Georgian
• 'kn': Kannada
• 'ku': Kurdish
• 'la': Latin
• 'lfn': Lingua Franca Nova
• 'lt': Lithuanian
• 'lv': Latvian
• 'mk': Macedonian
• 'ml': Malayalam
• 'ms': Malay
• 'ne': Nepali
• 'nl': Dutch
• 'no': Norwegian
• 'pa': Punjabi
• 'pl': Polish
• 'pt-br': Portuguese (Brazil)
• 'pt-pt': Portuguese (Portugal)
• 'ro': Romanian
• 'ru': Russian
• 'sk': Slovak
• 'sq': Albanian
• 'sr': Serbian
• 'sv': Swedish
• 'sw': Swahili
• 'ta': Tamil
• 'tr': Turkish
• 'vi': Vietnamese
• 'vi-hue': Vietnamese (Hue)

53
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• 'vi-sgn': Vietnamese (Saigon)


• 'zh': Mandarin Chinese
• 'zh-yue': Cantonese Chinese
You can choose the following voices:
• 'f1': female variant 1
• 'f2': female variant 2
• 'f3': female variant 3
• 'f4': female variant 4
• 'f5': female variant 5
• 'm1': male variant 1
• 'm2': male variant 2
• 'm3': male variant 3
• 'm4': male variant 4
• 'm5': male variant 5
• 'm6': male variant 6
• 'm7': male variant 7
• 'croak': croak
• 'whisper': whisper
• 'whisperf': female whisper
speaker.set_volume(volume, which=’_all_’)
Sets the speaker volume.
Parameters
• volume (percentage: %) – Volume of the speaker.
• which (str) – Which volume to set. 'Beep' sets the volume for beep() and
play_notes(). 'PCM' sets the volume for play_file() and say(). '_all_'
sets both at the same time.

Using the screen

screen.clear()
Clears the screen. All pixels on the screen will be set to Color.WHITE.
screen.draw_text(x, y, text, text_color=Color(0, 0, 0, ’BLACK’), background_color=None)
Draws text on the screen.
The most recent font set using set_font() will be used or Font.DEFAULT if no font has been set yet.
Parameters
• x (int) – The x-axis value where the left side of the text will start.
• y (int) – The y-axis value where the top of the text will start.
• text (str) – The text to draw.

54
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• text_color (Color) – The color used for drawing the text.


• background_color (Color) – The color used to fill the rectangle behind the text or
None for transparent background.
screen.print(*args, sep=’ ’, end=’\n’)
Prints a line of text on the screen.
This method works like the builtin print() function, but it writes on the screen instead.
You can set the font using set_font(). If no font has been set, Font.DEFAULT will be used. The
text is always printed used black text with a white background.
Unlike the builtin print(), the text does not wrap if it is too wide to fit on the screen. It just gets cut
off. But if the text would go off of the bottom of the screen, the entire image is scrolled up and the text is
printed in the new blank area at the bottom of the screen.
Parameters
• * (object) – Zero or more objects to print.
• sep (str) – Separator that will be placed between each object that is printed.
• end (str) – End of line that will be printed after the last object.
Show/hide example
Example: Say hello. . . in several ways.

#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick


from pybricks.tools import wait
from pybricks.media.ev3dev import Font

# It takes some time for fonts to load from file, so it is best to only
# load them once at the beginning of the program like this:
tiny_font = Font(size=6)
big_font = Font(size=24, bold=True)
chinese_font = Font(size=24, lang='zh-cn')

# Initialize the EV3


ev3 = EV3Brick()

# Say hello
ev3.screen.print('Hello!')

# Say tiny hello


ev3.screen.set_font(tiny_font)
ev3.screen.print('hello')

# Say big hello


ev3.screen.set_font(big_font)
ev3.screen.print('HELLO')

# Say Chinese hello


ev3.screen.set_font(chinese_font)
ev3.screen.print('你好')

(continues on next page)

55
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Wait some time to look at the screen
wait(5000)

screen.set_font(font)
Sets the font used for writing on the screen.
The font is used for both draw_text() and print().
Parameters font (Font) – The font to use.
Example: See example in print().
screen.load_image(source)
Clears this image, then draws the source image centered in the screen.
Parameters source (Image or str) – The source Image. If the argument is a string, then
the source image is loaded from file.
Show/hide example
Example: Show an image on the screen.

#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick


from pybricks.tools import wait
from pybricks.media.ev3dev import Image, ImageFile

# It takes some time to load images from the SD card, so it is best to load
# them once at the beginning of a program like this:
ev3_img = Image(ImageFile.EV3_ICON)

# Initialize the EV3


ev3 = EV3Brick()

# Show an image
ev3.screen.load_image(ev3_img)

# Wait some time to look at the image


wait(5000)

screen.draw_image(x, y, source, transparent=None)


Draws the source image on the screen.
Parameters
• x (int) – The x-axis value where the left side of the image will start.
• y (int) – The y-axis value where the top of the image will start.
• source (Image or str) – The source Image. If the argument is a string, then the
source image is loaded from file.
• transparent (Color) – The color of image to treat as transparent or None for no
transparency.
screen.draw_pixel(x, y, color=Color(0, 0, 0, ’BLACK’))
Draws a single pixel on the screen.
Parameters

56
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• x (int) – The x coordinate of the pixel.


• y (int) – The y coordinate of the pixel.
• color (Color) – The color of the pixel.
screen.draw_line(x1, y1, x2, y2, width=1, color=Color(0, 0, 0, ’BLACK’))
Draws a line on the screen.
Parameters
• x1 (int) – The x coordinate of the starting point of the line.
• y1 (int) – The y coordinate of the starting point of the line.
• x2 (int) – The x coordinate of the ending point of the line.
• y2 (int) – The y coordinate of the ending point of the line.
• width (int) – The width of the line in pixels.
• color (Color) – The color of the line.
Show/hide example
Example: Draw some shapes on the screen.

#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick


from pybricks.tools import wait

# Initialize the EV3


ev3 = EV3Brick()

# Draw a rectangle
ev3.screen.draw_box(10, 10, 40, 40)

# Draw a solid rectangle


ev3.screen.draw_box(20, 20, 30, 30, fill=True)

# Draw a rectangle with rounded corners


ev3.screen.draw_box(50, 10, 80, 40, 5)

# Draw a circle
ev3.screen.draw_circle(25, 75, 20)

# Draw a triangle using lines


x1, y1 = 65, 55
x2, y2 = 50, 95
x3, y3 = 80, 95
ev3.screen.draw_line(x1, y1, x2, y2)
ev3.screen.draw_line(x2, y2, x3, y3)
ev3.screen.draw_line(x3, y3, x1, y1)

# Wait some time to look at the shapes


wait(5000)

screen.draw_box(x1, y1, x2, y2, r=0, fill=False, color=Color(0, 0, 0, ’BLACK’))


Draws a box on the screen.

57
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Parameters
• x1 (int) – The x coordinate of the left side of the box.
• y1 (int) – The y coordinate of the top of the box.
• x2 (int) – The x coordinate of the right side of the box.
• y2 (int) – The y coordinate of the bottom of the box.
• r (int) – The radius of the corners of the box.
• fill (bool) – If True, the box will be filled with color, otherwise only the outline of
the box will be drawn.
• color (Color) – The color of the box.
Example: See example in draw_line().
screen.draw_circle(x, y, r, fill=False, color=Color(0, 0, 0, ’BLACK’))
Draws a circle on the screen.
Parameters
• x (int) – The x coordinate of the center of the circle.
• y (int) – The y coordinate of the center of the circle.
• r (int) – The radius of the circle.
• fill (bool) – If True, the circle will be filled with color, otherwise only the circum-
ference will be drawn.
• color (Color) – The color of the circle.
Example: See example in draw_line().
screen.width
Gets the width of the screen in pixels.
screen.height
Gets the height of the screen in pixels.
screen.save(filename)
Saves the screen as a .png file.
Parameters filename (str) – The path to the file to be saved.
Raises
• TypeError – filename is not a string.
• OSError – There was a problem saving the file.

Using the battery

battery.voltage()
Gets the voltage of the battery.
Returns Battery voltage.
Return type voltage: mV
battery.current()
Gets the current supplied by the battery.

58
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns Battery current.


Return type current: mA

class MoveHub
LEGO® Powered Up Move Hub.

class CityHub
LEGO® Powered Up City Hub.

class TechnicHub
LEGO® Technic Hub.
class PrimeHub
LEGO® SPIKE Prime Hub.
class InventorHub
LEGO® MINDSTORMS Inventor Hub.
class EV3Brick
LEGO® MINDSTORMS® EV3 Brick.

59
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

60
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 5

pupdevices – Powered Up Devices

LEGO® Powered Up motor, sensors, and lights.

5.1 Motors without Rotation Sensors

Figure 5.1: Powered Up motors without rotation sensors. The arrows indicate the default positive direction.

Show/hide examples
Example 1: Making the motor move back and forth

from pybricks.pupdevices import DCMotor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor without rotation sensors on port A.


example_motor = DCMotor(Port.A)

# Make the motor go clockwise (forward) at 70% duty cycle ("70% power").
example_motor.dc(70)
(continues on next page)

61
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Wait for three seconds.


wait(3000)

# Make the motor go counterclockwise (backward) at 70% duty cycle.


example_motor.dc(-70)

# Wait for three seconds.


wait(3000)

Example 2: Seting the positive direction as counterclockwise

from pybricks.pupdevices import DCMotor


from pybricks.parameters import Port, Direction
from pybricks.tools import wait

# Initialize a motor without rotation sensors on port A,


# with the positive direction as counterclockwise.
example_motor = DCMotor(Port.A, Direction.COUNTERCLOCKWISE)

# When we choose a positive duty cycle, the motor now goes counterclockwise.
example_motor.dc(70)

# This is useful when your (train) motor is mounted in reverse or upside down.
# By changing the positive direction, your script will be easier to read,
# because a positive value now makes your train/robot go forward.

# Wait for three seconds.


wait(3000)

Example 3: Starting and stopping

from pybricks.pupdevices import DCMotor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor without rotation sensors on port A.


example_motor = DCMotor(Port.A)

# Start and stop 10 times.


for count in range(10):
print("Counter:", count)

example_motor.dc(70)
wait(1000)

example_motor.stop()
wait(1000)

class DCMotor(port, positive_direction=Direction.CLOCKWISE)


Generic class to control simple motors without rotation sensors, such as train motors.
Parameters
• port (Port) – Port to which the motor is connected.
• positive_direction (Direction) – Which direction the motor should turn when
you give a positive duty cycle value.

62
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

dc(duty)
Rotates the motor at a given duty cycle (also known as “power”).
Parameters duty (percentage: %) – The duty cycle (-100.0 to 100).
stop()
Stops the motor and lets it spin freely.
The motor gradually stops due to friction.
brake()
Passively brakes the motor.
The motor stops due to friction, plus the voltage that is generated while the motor is still moving.

5.2 Motors with Rotation Sensors

class Motor(port, positive_direction=Direction.CLOCKWISE, gears=None)


Generic class to control motors with built-in rotation sensors.
Parameters
• port (Port) – Port to which the motor is connected.
• positive_direction (Direction) – Which direction the motor should turn when
you give a positive speed value or angle.
• gears (list) – List of gears linked to the motor.
For example: [12, 36] represents a gear train with a 12-tooth and a 36-tooth gear. Use a
list of lists for multiple gear trains, such as [[12, 36], [20, 16, 40]].
When you specify a gear train, all motor commands and settings are automatically adjusted
to account for the resulting gear ratio. The motor direction remains unchanged by this.
Show/hide examples
Example 1: Making the motor move back and forth

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# Make the motor run clockwise at 500 degrees per second.


example_motor.run(500)

# Wait for three seconds.


wait(3000)

# Make the motor run counterclockwise at 500 degrees per second.


example_motor.run(-500)

# Wait for three seconds.


wait(3000)

Example 2: Using more than one motor

63
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize motors on port A and B.


track_motor = Motor(Port.A)
gripper_motor = Motor(Port.B)

# Make both motors run at 500 degrees per second.


track_motor.run(500)
gripper_motor.run(500)

# Wait for three seconds.


wait(3000)

Example 3: Seting the positive direction as counterclockwise


from pybricks.pupdevices import Motor
from pybricks.parameters import Port, Direction
from pybricks.tools import wait

# Initialize a motor on port A with the positive direction as counterclockwise.


example_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)

# When we choose a positive speed value, the motor now goes counterclockwise.
example_motor.run(500)

# This is useful when your motor is mounted in reverse or upside down.


# By changing the positive direction, your script will be easier to read,
# because a positive value now makes your robot/mechanism go forward.

# Wait for three seconds.


wait(3000)

Example 4: Using gears


from pybricks.pupdevices import Motor
from pybricks.parameters import Port, Direction
from pybricks.tools import wait

# Initialize a motor on port A with the positive direction as counterclockwise.


# Also specify one gear train with a 12-tooth and a 36-tooth gear. The 12-tooth
# gear is attached to the motor axle. The 36-tooth gear is at the output axle.
geared_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE, [12, 36])

# Make the output axle run at 100 degrees per second. The motor speed
# is automatically increased to compensate for the gears.
geared_motor.run(100)

# Wait for three seconds.


wait(3000)

Measuring

Show/hide examples
Example 1: Measuring the angle and speed

64
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# Start moving at 300 degrees per second.


example_motor.run(300)

# Display the angle and speed 50 times.


for i in range(100):

# Read the angle (degrees) and speed (degrees per second).


angle = example_motor.angle()
speed = example_motor.speed()

# Print the values.


print(angle, speed)

# Wait some time so we can read what is displayed.


wait(200)

Example 2: Resetting the measured angle

from pybricks.pupdevices import Motor


from pybricks.parameters import Port

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# Reset the angle to 0.


example_motor.reset_angle(0)

# Reset the angle to 1234.


example_motor.reset_angle(1234)

# Reset the angle to the absolute angle.


# This is only supported on motors that have
# an absolute encoder. For other motors, this
# will raise an error.
example_motor.reset_angle()

speed()
Gets the speed of the motor.
Returns Motor speed.
Return type rotational speed: deg/s
angle()
Gets the rotation angle of the motor.
Returns Motor angle.
Return type angle: deg
reset_angle(angle=None)
Sets the accumulated rotation angle of the motor to a desired value.

65
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

If you don’t specify an angle, the absolute angle will be used if your motor supports it.
Parameters angle (angle: deg) – Value to which the angle should be reset.

Stopping

Show/hide example
Example: Stopping the motor in different ways

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# Run at 500 deg/s and then stop by coasting.


example_motor.run(500)
wait(1500)
example_motor.stop()
wait(1500)

# Run at 500 deg/s and then stop by braking.


example_motor.run(500)
wait(1500)
example_motor.brake()
wait(1500)

# Run at 500 deg/s and then stop by holding.


example_motor.run(500)
wait(1500)
example_motor.hold()
wait(1500)

# Run at 500 deg/s and then stop by running at 0 speed.


example_motor.run(500)
wait(1500)
example_motor.run(0)
wait(1500)

stop()
Stops the motor and lets it spin freely.
The motor gradually stops due to friction.
brake()
Passively brakes the motor.
The motor stops due to friction, plus the voltage that is generated while the motor is still moving.
hold()
Stops the motor and actively holds it at its current angle.

Action

Show/hide examples

66
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Example 1: Basic usage of all action methods

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# Run at 500 deg/s and then stop by coasting.


print("Demo of run")
example_motor.run(500)
wait(1500)
example_motor.stop()
wait(1500)

# Run at 70% duty cycle ("power") and then stop by coasting.


print("Demo of dc")
example_motor.dc(50)
wait(1500)
example_motor.stop()
wait(1500)

# Run at 500 deg/s for two seconds.


print("Demo of run_time")
example_motor.run_time(500, 2000)
wait(1500)

# Run at 500 deg/s for 90 degrees.


print("Demo of run_angle")
example_motor.run_angle(500, 180)
wait(1500)

# Run at 500 deg/s back to the 0 angle


print("Demo of run_target to 0")
example_motor.run_target(500, 0)
wait(1500)

# Run at 500 deg/s back to the -90 angle


print("Demo of run_target to -90")
example_motor.run_target(500, -90)
wait(1500)

# Run at 500 deg/s until the motor stalls


print("Demo of run_until_stalled")
example_motor.run_until_stalled(500)
print("Done")
wait(1500)

Example 2: Using the then argument to change how a motor stops

from pybricks.pupdevices import Motor


from pybricks.parameters import Port, Stop
from pybricks.tools import wait

# Initialize a motor on port A.


example_motor = Motor(Port.A)

(continues on next page)

67
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# By default, the motor holds the position. It keeps
# correcting the angle if you move it.
example_motor.run_angle(500, 360)
wait(1000)

# This does exactly the same as above.


example_motor.run_angle(500, 360, then=Stop.HOLD)
wait(1000)

# You can also brake. This applies some resistance


# but the motor does not move back if you move it.
example_motor.run_angle(500, 360, then=Stop.BRAKE)
wait(1000)

# This makes the motor coast freely after it stops.


example_motor.run_angle(500, 360, then=Stop.COAST)
wait(1000)

Example 3: Using the wait argument to run motors in parallel

from pybricks.pupdevices import Motor


from pybricks.parameters import Port

# Initialize motors on port A and B.


track_motor = Motor(Port.A)
gripper_motor = Motor(Port.B)

# Make the track motor start moving,


# but don't wait for it to finish.
track_motor.run_angle(500, 360, wait=False)

# Now make the gripper motor rotate. This


# means they move at the same time.
gripper_motor.run_angle(200, 720)

Example 4: Waiting for two actions to complete in parallel

from pybricks.pupdevices import Motor


from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize motors on port A and B.


track_motor = Motor(Port.A)
gripper_motor = Motor(Port.B)

# Make both motors perform an action with wait=False


track_motor.run_angle(500, 360, wait=False)
gripper_motor.run_angle(200, 720, wait=False)

# While one or both of the motors are not done yet,


# do something else. In this example, just wait.
while not track_motor.control.done() or not gripper_motor.control.done():
wait(10)

print("Both motors are done!")

Example 5: Running a motor until a mechanical endpoint

68
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from pybricks.pupdevices import Motor


from pybricks.parameters import Port

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# We'll use a speed of 200 deg/s in all our commands.


speed = 200

# Run the motor in reverse until it hits a mechanical stop.


# The duty_limit=30 setting means that it will apply only 30%
# of the maximum torque against the mechanical stop. This way,
# you don't push against it with too much force.
example_motor.run_until_stalled(-speed, duty_limit=30)

# Reset the angle to 0. Now whenever the angle is 0, you know


# that it has reached the mechanical endpoint.
example_motor.reset_angle(0)

# Now make the motor go back and forth in a loop.


# This will now work the same regardless of the
# initial motor angle, because we always start
# from the mechanical endpoint.
for count in range(10):
example_motor.run_target(speed, 180)
example_motor.run_target(speed, 90)

Example 6: Centering a steering mechanism

from pybricks.pupdevices import Motor


from pybricks.parameters import Port

# Initialize a motor on port A.


example_motor = Motor(Port.A)

# We'll use a speed of 200 deg/s in all our commands.


speed = 200

# Run the motor in reverse until it hits a mechanical stop.


# The duty_limit=30 setting means that it will apply only 30%
# of the maximum torque against the mechanical stop. This way,
# you don't push against it with too much force.
example_motor.run_until_stalled(-speed, duty_limit=30)

# Reset the angle to 0. Now whenever the angle is 0, you know


# that it has reached the mechanical endpoint.
example_motor.reset_angle(0)

# Now make the motor go back and forth in a loop.


# This will now work the same regardless of the
# initial motor angle, because we always start
# from the mechanical endpoint.
for count in range(10):
example_motor.run_target(speed, 180)
example_motor.run_target(speed, 90)

run(speed)
Runs the motor at a constant speed.

69
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

The motor accelerates to the given speed and keeps running at this speed until you give a new command.
Parameters speed (rotational speed: deg/s) – Speed of the motor.
run_time(speed, time, then=Stop.HOLD, wait=True)
Runs the motor at a constant speed for a given amount of time.
The motor accelerates to the given speed, keeps running at this speed, and then decelerates. The total
maneuver lasts for exactly the given amount of time.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• time (time: ms) – Duration of the maneuver.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the maneuver to complete before continuing with the rest of the
program.
run_angle(speed, rotation_angle, then=Stop.HOLD, wait=True)
Runs the motor at a constant speed by a given angle.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• rotation_angle (angle: deg) – Angle by which the motor should rotate.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the maneuver to complete before continuing with the rest of the
program.
run_target(speed, target_angle, then=Stop.HOLD, wait=True)
Runs the motor at a constant speed towards a given target angle.
The direction of rotation is automatically selected based on the target angle. It does matter if speed is
positive or negative.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• target_angle (angle: deg) – Angle that the motor should rotate to.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the motor to reach the target before continuing with the rest of
the program.
run_until_stalled(speed, then=Stop.COAST, duty_limit=None)
Runs the motor at a constant speed until it stalls.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• then (Stop) – What to do after coming to a standstill.
• duty_limit (percentage: %) – Torque limit during this command. This is useful to
avoid applying the full motor torque to a geared or lever mechanism.
Returns Angle at which the motor becomes stalled.
Return type angle: deg

70
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

dc(duty)
Rotates the motor at a given duty cycle (also known as “power”).
This method lets you use a motor just like a simple DC motor.
Parameters duty (percentage: %) – The duty cycle (-100.0 to 100).

Advanced motion control

track_target(target_angle)
Tracks a target angle. This is similar to run_target(), but the usual smooth acceleration is skipped: it
will move to the target angle as fast as possible. This method is useful if you want to continuously change
the target angle.
Parameters target_angle (angle: deg) – Target angle that the motor should rotate to.
control
The motors use PID control to accurately track the speed and angle targets that you specify. You can
change its behavior through the control attribute of the motor. See The Control Class for an overview
of available methods.

5.3 Color
and
Dis-
tance
Sen-
sor

Show/hide
ex-
am-
ples
Example
1:
Mea-
sur-
ing
color

71
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorDista

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorDista

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→the

˓→color.

˓→

˓→

˓→

˓→

˓→color
˓→=
˓→sensor.

˓→color()

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→measured

˓→color.
(continues on next page)
˓→

72
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→print(colo

˓→

˓→

˓→

˓→

˓→#
˓→Move
˓→the

˓→sensor

˓→around

˓→and

˓→see

˓→how

˓→

˓→

˓→

˓→

˓→#
˓→well
˓→you

˓→can

˓→detect

˓→colors.

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→the

˓→value.

˓→

˓→

˓→

˓→

˓→wait(100)

Example
2:
Wait-
ing
for

73
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

a
color
from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorDista

from
˓→pybricks.

˓→parameters

˓→import

˓→Port,

˓→

˓→Color

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorDista

˓→A)

˓→#
˓→This
˓→is

˓→a

˓→function

˓→that

˓→waits

˓→for

˓→a

˓→desired

˓→color.

˓→

def
˓→wait_

˓→for_

˓→color(desi

˓→color):

˓→

˓→

˓→

˓→

˓→#
˓→While
(continues on next page) ˓→the

˓→color

˓→is

74 ˓→not

˓→the

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors ˓→desired

˓→color,
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→while
˓→sensor.
˓→color()

˓→!

˓→=

˓→desired_

˓→color:

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→wait(20)

˓→#
˓→Now
˓→we

˓→use

˓→the

˓→function

˓→we

˓→just

˓→created

˓→above.

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Here
˓→you

˓→can

˓→make

˓→your

˓→train/

˓→vehicle

˓→go

˓→forward.

˓→

˓→

˓→
(continues on next page) ˓→

˓→print(
˓→"Waiting
75 ˓→for

˓→red
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→.

˓→.
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→wait_
˓→for_
˓→color(Colo

˓→RED)

˓→

˓→

˓→

˓→

˓→#
˓→Here
˓→you

˓→can

˓→make

˓→your

˓→train/

˓→vehicle

˓→go

˓→backward.

˓→

˓→

˓→

˓→

˓→print(
˓→"Waiting
˓→for

˓→blue

˓→.

˓→.

˓→.

˓→

˓→")

˓→

˓→

˓→

˓→wait_
˓→for_
˓→color(Colo

˓→BLUE)

Example
3:
Mea-
sur-
ing
dis-
tance

76
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorDista

from
˓→pybricks.

˓→parameters

˓→import

˓→Port,

˓→

˓→Color

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorDista

˓→A)

˓→#
˓→Repeat
˓→forever.

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→If
˓→the

˓→sensor

˓→sees

˓→an

˓→object

˓→nearby.

˓→

˓→

˓→

˓→

˓→if
˓→sensor.
˓→distance()
(continues on next page)
˓→

˓→<=
˓→40:
77
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Then
˓→blink

˓→the

˓→light

˓→red/

˓→blue

˓→5

˓→times.

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→for
˓→i
˓→in

˓→range(5):

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→sensor.
˓→light.
˓→on(Color.

˓→RED)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→
(continues on next page) ˓→

˓→

˓→
78 wait(30)
˓→

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→sensor.
˓→light.
˓→on(Color.

˓→BLUE)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(30)
˓→

˓→

˓→

˓→

else:
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→If
˓→the

˓→sensor

˓→sees

˓→nothing

˓→

˓→

˓→

˓→

˓→

˓→

˓→
(continues on next page) ˓→

#
˓→

nearby,
˓→
79 ˓→

˓→just
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→wait
˓→briefly.
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→wait(10)

class ColorDist
LEGO®
Pow-
ered
Up
Color
and
Dis-
tance
Sen-
sor.
Parameters
port
(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
color()
Scans
the
color
of
a
sur-
face.
You
choose
which
col-
ors
are
de-
tected
us-
ing

80
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

the
detectable_
method.
By
de-
fault,
it
de-
tects Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.WHITE, or None.
Returns
Detected
color.
Return type
Color
reflection()
Measures
the
re-
flec-
tion
of
a
sur-
face.
Returns
Reflection,
rang-
ing
from
0.0
(no
re-
flec-
tion)
to
100.0
(high
re-
flec-
tion).
Return type
percentage:
%
ambient()
Measures
the
am-
bi-
ent
light
in-

81
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ten-
sity.
Returns
Ambient
light
in-
ten-
sity,
rang-
ing
from
0
(dark)
to
100
(bright).
Return type
percentage:
%
distance()
Measures
the
rel-
a-
tive
dis-
tance
be-
tween
the
sen-
sor
and
an
ob-
ject
us-
ing infrared light.
Returns
Relative
dis-
tance
rang-
ing
from
0
(clos-
est)
to
100
(far-
thest).

82
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Return type
relative
dis-
tance:
%

Advanced
color
sens-
ing

Show/hide
ex-
am-
ples
Example
1:
Read-
ing
hue,
sat-
u-
ra-
tion,
and
value

from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param

˓→impor

˓→Port

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

(continues on next page)

83
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→The
˓→stand

˓→color

˓→metho

˓→alway

˓→

˓→"roun
˓→"
˓→the

˓→

˓→

˓→

˓→

˓→#
˓→measu
˓→to

˓→the

˓→neare

˓→

˓→"whol
˓→"
˓→color

˓→

˓→

˓→

˓→

˓→

˓→#
˓→That
˓→'s

˓→usefu

˓→for

˓→most

˓→appli

˓→

˓→

˓→

˓→

˓→

˓→#
˓→But
˓→you

˓→can

˓→get

˓→the
(continues on next page) ˓→origi

˓→hue,

˓→
84 ˓→satur
˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→and
˓→value

˓→witho

˓→

"roun
˓→

",
˓→

˓→

as
˓→

follo
˓→

˓→

˓→

˓→

˓→color
˓→=
˓→senso

˓→hsv()

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→resul

˓→

˓→

˓→

˓→

print
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→the

˓→value

˓→

˓→

˓→
(continues on next page) ˓→

wait(
˓→

85
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

Example
2:
Chang-
ing
the
de-
tectable
col-
ors
By
de-
fault,
the
sen-
sor
is
con-
fig-
ured
to
de-
tect
red,
yel-
low,
green,
blue,
white, or None, which suits many applications.
For
bet-
ter
re-
sults
in
your
ap-
pli-
ca-
tion,
you
can
mea-
sure
your
de-
sired
colors in advance, and tell the sensor to look only for those colors. Be sure to measure them at the same distance and
light conditions as in your final application. Then you’ll get very accurate results even for colors that are otherwise
hard to detect.

86
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param

˓→impor

˓→Port,

˓→

˓→Color

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

˓→#
˓→First
˓→

˓→decid
˓→which
˓→objec

˓→you

˓→want

˓→to

˓→detec

˓→

˓→#
˓→Then
˓→measu

˓→their

˓→color

˓→with

˓→the

˓→hsv()

˓→metho

˓→

˓→#
˓→as
˓→shown

˓→in

˓→the
(continues on next page)
˓→previ

˓→examp

˓→
87
˓→Write
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→them
˓→down
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→as
˓→shown

˓→below

˓→

˓→The
˓→name
˓→is

˓→optio

˓→

˓→but
˓→it
˓→is

˓→#
˓→usefu
˓→when

˓→you

˓→print

˓→the

˓→color

˓→value

˓→

green
˓→=

˓→Color

˓→

˓→s=94,
˓→

˓→v=26,
˓→

˓→ name=
˓→ 'GREE
˓→BRICK

˓→')

magenta
˓→=

˓→Color

˓→

˓→s=96,
˓→

˓→v=40,
˓→

˓→ name=
˓→ 'MAGE
˓→BRICK

˓→')

brown
˓→=

˓→Color

˓→

˓→s=78,
˓→

˓→v=15,
˓→

˓→name=
(continues on next page) ˓→'BROW
˓→BRICK

˓→')
88
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


red
˓→=

˓→Color

˓→

˓→s=97,
˓→

˓→v=39,
˓→

˓→name=
˓→'RED_
˓→BRICK

˓→')

˓→#
˓→Put
˓→your

˓→color

˓→in

˓→a

˓→list

˓→or

˓→tuple

˓→

˓→#
˓→Inclu
˓→None

˓→is

˓→optio

˓→

˓→Just
˓→omit
˓→it

˓→if

˓→#
˓→you
˓→alway

˓→want

˓→to

˓→get

˓→one

˓→of

˓→your

˓→color

˓→

my_
˓→color

˓→=

˓→(gree

˓→

˓→magen
˓→

˓→brown
˓→

˓→red,
(continues on next page) ˓→

˓→None)

89
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→Save
˓→your

˓→color

˓→

sensor.
˓→detec

˓→color

˓→color

˓→#
˓→color
˓→works

˓→as

˓→usual

˓→

˓→but
˓→it
˓→only

˓→#
˓→retur
˓→one

˓→of

˓→your

˓→speci

˓→color

˓→

while
˓→True:

˓→

˓→

˓→

˓→color
˓→=
˓→senso

˓→color

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→color

˓→

˓→

˓→

˓→

˓→print
(continues on next page)

90
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Check
˓→which

˓→one

˓→it

˓→is.

˓→

˓→

˓→

˓→

˓→if
˓→color
˓→==

˓→magen

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→print
˓→"It
˓→works

˓→

")
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→it.

˓→

˓→

˓→

˓→

wait(
˓→

hsv()
Scans
the

91
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

color
of
a
sur-
face.
This
method
is
sim-
i-
lar
to
color(),
but
it
gives
the
full
range
of
hue,
sat-
u-
ration and brightness values, instead of rounding it to the nearest detectable color.
Returns
Measured
color.
The
color
is
de-
scribed
by
a
hue
(0–359),
a
sat-
u-
ra-
tion
(0–100),
and a brightness value (0–100).
Return type
Color
detectable_colo
Configures
which
col-
ors
the
color()

92
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

method
should
de-
tect.
Specify
only
col-
ors
that
you
wish
to
de-
tect
in
your
ap-
pli-
ca-
tion.
This
way,
the full-color measurements are rounded to the nearest desired color, and other colors are ignored. This improves
reliability.
If
you
give
no
ar-
gu-
ments,
the
cur-
rently
cho-
sen
col-
ors
will
be
re-
turned
as a tuple.
Parameters
colors
(list)

List
of
Color
ob-
jects:

93
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

the
col-
ors
that
you
want
to
de-
tect.
You can pick standard colors such as Color.MAGENTA, or provide your own colors like Color(h=348, s=96,
v=40, name='MY_MAGENTA_BRICK') for even better results. You measure your own colors with the hsv()
method.

Built-
in
light

This
sen-
sor
has
a
built-
in
light.
You
can
make
it
red,
green,
blue,
or
turn
it
off. If you use the sensor to measure something afterwards, the light automatically turns back on at the default color
for that sensing method.
Show/hide
ex-
am-
ples
Example:
Blink-
ing
the
built-
in
light
from
˓→pybri

˓→pupde

(continues on next page) ˓→impor

˓→Color

94
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


from
˓→pybri

˓→param

˓→impor

˓→Port,

˓→

˓→Color

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

˓→#
˓→Repea
˓→forev

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→If
˓→the

˓→senso

˓→sees

˓→an

˓→objec

˓→nearb

˓→

˓→

˓→

˓→

˓→if
˓→senso
˓→dista

˓→

˓→<=
˓→40:

(continues on next page)

95
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Then
˓→blink

˓→the

˓→light

˓→red/

˓→blue

˓→5

˓→times

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→for
˓→i
˓→in

˓→range

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→on(Co

˓→RED)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→
(continues on next page) ˓→

˓→

wait(
˓→
96
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→on(Co

˓→BLUE)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(
˓→

˓→

˓→

˓→

else:
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→If
˓→the

˓→senso

˓→sees

˓→nothi

˓→

˓→

˓→

˓→

˓→

˓→

˓→
(continues on next page) ˓→

#
˓→

nearb
˓→
97 ˓→

˓→just
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→wait
˓→brief
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(
˓→

light.on(color)
Turns
on
the
light
at
the
spec-
i-
fied
color.
Parameters
color
(Color)

Color
of
the
light.
light.off()
Turns
off
the
light.

5.4 Powe
Func-
tions

The
ColorDistan
can
send
in-
frared
sig-
nals
to
con-
trol

98
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Power
Func-
tions
in-
frared
re-
ceivers.
You can use this technique to control medium, large, extra large, and train motors. The infrared range is limited to
about 30 cm, depending on the angle and ambient conditions.

Figure 5.3: Powered Up ColorDistanceSensor (left), Power Functions infrared receiver (middle), and a Power
Functions motor (right). Here, the receiver uses channel 1 with a motor on the red port.

Show/hide
ex-
am-
ples
Example
1:
Con-
trol
a
Power
Func-
tions
mo-
tor
from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorDista

˓→

˓→PFMotor

from
˓→pybricks.

˓→parameters

˓→import

˓→Port,

˓→

˓→Color

from
˓→pybricks.
(continues on next page)
˓→tools

˓→import

99 ˓→wait

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorDista

˓→B)

˓→#
˓→Initialize
˓→a

˓→motor

˓→on

˓→channel

˓→1,

˓→

˓→on
˓→the
˓→red

˓→output.

˓→

motor
˓→=

˓→PFMotor(se

˓→

˓→1,
˓→

˓→Color.
˓→RED)

˓→#
˓→Rotate
˓→and

˓→then

˓→stop.

˓→

motor.
˓→dc(100)

wait(1000)
motor.
˓→stop()

wait(1000)

˓→#
˓→Rotate
˓→the

˓→other

˓→way

˓→at

˓→half
(continues on next page) ˓→speed,

˓→

˓→and
100 ˓→then
˓→stop.
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


motor.
˓→dc(-

˓→50)

wait(1000)
motor.
˓→stop()

Example
2:
Con-
trol-
ling
mul-
ti-
ple
Power
Func-
tions
mo-
tors
from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorDista

˓→

˓→PFMotor

from
˓→pybricks.

˓→parameters

˓→import

˓→Port,

˓→

˓→Color,
˓→

˓→Direction

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorDista

˓→B)

˓→#
(continues on next page) ˓→You
˓→can

˓→use
101 ˓→multiple

˓→motors
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→on

˓→different
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


arm
˓→=

˓→PFMotor(se

˓→

˓→1,
˓→

˓→ Color.
˓→ BLUE)
wheel
˓→=

˓→PFMotor(se

˓→

˓→4,
˓→

˓→Color.
˓→RED,
˓→

˓→Direction.
˓→COUNTERCLO

˓→#
˓→Accelerate
˓→both

˓→motors.

˓→

˓→Only
˓→these
˓→values

˓→are

˓→available.

˓→

˓→#
˓→Other
˓→values

˓→will

˓→be

˓→rounded

˓→down

˓→to

˓→the

˓→nearest

˓→match.

˓→

for
˓→duty

˓→in

˓→[15,

˓→

˓→30,
˓→

˓→45,
˓→

˓→60,
˓→

˓→75,
(continues on next page) ˓→

˓→90,
˓→
102 ˓→100]:
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

arm.
˓→

dc(duty)
˓→

˓→

˓→

˓→

wheel.
˓→

dc(duty)
˓→

˓→

˓→

˓→

wait(1000)
˓→

˓→#
˓→To
˓→make

˓→the

˓→signal

˓→more

˓→reliable,

˓→

˓→there
˓→is
˓→a

˓→short

˓→#
˓→pause
˓→between

˓→commands.

˓→

So,
˓→

˓→

˓→they
˓→change
˓→speed

˓→and

˓→#
˓→stop
˓→at

˓→a

˓→slightly

˓→different

˓→time.

˓→

˓→#
˓→Brake
˓→both
(continues on next page) ˓→motors.

˓→

103
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


arm.
˓→brake()

wheel.
˓→brake()

class PFMotor(s
Control
Power
Func-
tions
mo-
tors
with
the
in-
frared
func-
tion-
al-
ity
of
the
ColorDistan
Parameters


sensor
(ColorDista

Sen-
sor
ob-
ject.

channel
(int)

Chan-
nel
num-
ber
of
the
re-
ceiver:
1,
2,
3,
or
4.

104
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

color
(Color)

Color
marker
on
the
re-
ceiver:
Color.
BLUE
or
Color.
RED

positive_di
(Direction)

Which
di-
rec-
tion
the
mo-
tor
should
turn
when
you
give
a
pos-
itive duty cycle value.
dc(duty)
Rotates
the
mo-
tor
at
a
given
duty
cy-
cle
(also
known
as
“power”).
Parameters
duty
(per-
cent-

105
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

age:
%)

The
duty
cy-
cle
(-
100.0
to
100).
stop()
Stops
the
mo-
tor
and
lets
it
spin
freely.
The
mo-
tor
grad-
u-
ally
stops
due
to
fric-
tion.
brake()
Passively
brakes
the
mo-
tor.
The
mo-
tor
stops
due
to
fric-
tion,
plus
the
volt-
age
that
is

106
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

gen-
er-
ated
while
the motor is still moving.

5.5 Color
Sen-
sor

Show/hide
ex-
am-
ples
Example
1:
Mea-
sur-
ing
color
and
re-
flec-
tion

from
˓→pybricks.

˓→pupdevices

˓→import

˓→ColorSenso

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

(continues on next page)

107
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorSenso

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→the

˓→color

˓→and

˓→reflection

˓→

˓→

˓→

˓→color
˓→=
˓→sensor.

˓→color()

˓→

˓→

˓→

˓→reflection
˓→=
˓→sensor.

˓→reflection

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→measured

˓→color

˓→and

˓→reflection

˓→

˓→

˓→
(continues on next page) ˓→

˓→print(colo
˓→
108 ˓→reflection
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Move
˓→the

˓→sensor

˓→around

˓→and

˓→see

˓→how

˓→

˓→

˓→

˓→

˓→#
˓→well
˓→you

˓→can

˓→detect

˓→colors.

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→the

˓→value.

˓→

˓→

˓→

˓→

˓→wait(100)

Example
2:
Wait-
ing
for
a
color
from
˓→pybricks.
(continues on next page)
˓→pupdevices

˓→import

109 ˓→ColorSenso

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


from
˓→pybricks.

˓→parameters

˓→import

˓→Port,

˓→

˓→Color

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

sensor
˓→=

˓→ColorSenso

˓→A)

˓→#
˓→This
˓→is

˓→a

˓→function

˓→that

˓→waits

˓→for

˓→a

˓→desired

˓→color.

˓→

def
˓→wait_

˓→for_

˓→color(desi

˓→color):

˓→

˓→

˓→

˓→

˓→#
˓→While
˓→the

˓→color

˓→is

˓→not

˓→the

˓→desired

˓→color,
(continues on next page) ˓→

˓→we
˓→keep
110 ˓→waiting.

˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→while
˓→sensor.
˓→color()

˓→!

˓→=

˓→desired_

˓→color:

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→wait(20)

˓→#
˓→Now
˓→we

˓→use

˓→the

˓→function

˓→we

˓→just

˓→created

˓→above.

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Here
˓→you

˓→can

˓→make

˓→your

˓→train/

˓→vehicle

˓→go

˓→forward.

˓→

˓→

˓→
(continues on next page) ˓→

˓→print(
˓→"Waiting
111 ˓→for

˓→red
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→.

˓→.
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→wait_
˓→for_
˓→color(Colo

˓→RED)

˓→

˓→

˓→

˓→

˓→#
˓→Here
˓→you

˓→can

˓→make

˓→your

˓→train/

˓→vehicle

˓→go

˓→backward.

˓→

˓→

˓→

˓→

˓→print(
˓→"Waiting
˓→for

˓→blue

˓→.

˓→.

˓→.

˓→

")
˓→

˓→

˓→

˓→

˓→wait_
˓→for_
˓→color(Colo

˓→BLUE)

class ColorSens
LEGO®
SPIKE
Color
Sen-
sor.
Parameters
port

112
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
color(surface=Tru
Scans
the
color
of
a
sur-
face
or
an
ex-
ter-
nal
light
source.
You
choose
which
col-
ors
are
de-
tected
us-
ing
the
detectable_
method.
By
de-
fault,
it
de-
tects Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.WHITE, or None.
Parameters
surface
(bool)

Choose
true
to

113
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

scan
the
color
of
ob-
jects
and
sur-
faces.
Choose
false
to scan the color of screens and other external light sources.
Returns
Detected
color.
Return type
Color
reflection()
Measures
the
re-
flec-
tion
of
a
sur-
face.
Returns
Reflection,
rang-
ing
from
0.0
(no
re-
flec-
tion)
to
100.0
(high
re-
flec-
tion).
Return type
percentage:
%
ambient()
Measures
the
am-
bi-

114
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ent
light
in-
ten-
sity.
Returns
Ambient
light
in-
ten-
sity,
rang-
ing
from
0
(dark)
to
100
(bright).
Return type
percentage:
%

Advanced
color
sens-
ing

Show/hide
ex-
am-
ples
Example
1:
Read-
ing
hue,
sat-
u-
ra-
tion,
and
value
from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param
(continues on next page) ˓→impor

˓→Port

115
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→The
˓→stand

˓→color

˓→metho

˓→alway

˓→

˓→"roun
˓→"
˓→the

˓→

˓→

˓→

˓→

˓→#
˓→measu
˓→to

˓→the

˓→neare

˓→

˓→"whol
˓→"
˓→color

˓→

˓→

˓→

˓→

˓→

˓→#
˓→That
˓→'s
(continues on next page) ˓→usefu

˓→for

˓→most
116 ˓→appli

˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→But
˓→you

˓→can

˓→get

˓→the

˓→origi

˓→hue,

˓→

satur
˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→and
˓→value

˓→witho

˓→

"roun
˓→

",
˓→

˓→

as
˓→

follo
˓→

˓→

˓→

˓→

˓→color
˓→=
˓→senso

˓→hsv()

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→resul

˓→

˓→

˓→

˓→

print
˓→

(continues on next page)

117
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→the

˓→value

˓→

˓→

˓→

˓→

wait(
˓→

Example
2:
Chang-
ing
the
de-
tectable
col-
ors
By
de-
fault,
the
sen-
sor
is
con-
fig-
ured
to
de-
tect
red,
yel-
low,
green,
blue,
white, or None, which suits many applications.
For
bet-
ter
re-
sults

118
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

in
your
ap-
pli-
ca-
tion,
you
can
mea-
sure
your
de-
sired
colors in advance, and tell the sensor to look only for those colors. Be sure to measure them at the same distance and
light conditions as in your final application. Then you’ll get very accurate results even for colors that are otherwise
hard to detect.
from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param

˓→impor

˓→Port,

˓→

˓→Color

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

˓→#
˓→First
˓→

˓→decid
˓→which
˓→objec

˓→you

˓→want

˓→to

˓→detec

(continues on next page) ˓→

119
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→Then
˓→measu

˓→their

˓→color

˓→with

˓→the

˓→hsv()

˓→metho

˓→

˓→#
˓→as
˓→shown

˓→in

˓→the

˓→previ

˓→examp

˓→

˓→Write
˓→them
˓→down

˓→#
˓→as
˓→shown

˓→below

˓→

˓→The
˓→name
˓→is

˓→optio

˓→

˓→but
˓→it
˓→is

˓→#
˓→usefu
˓→when

˓→you

˓→print

˓→the

˓→color

˓→value

˓→

green
˓→=

˓→Color

˓→

˓→s=94,
˓→

˓→v=26,
˓→

˓→name=
˓→'GREE
(continues on next page) ˓→BRICK

˓→')

120
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


magenta
˓→=

˓→Color

˓→

˓→s=96,
˓→

˓→v=40,
˓→

˓→ name=
˓→ 'MAGE
˓→BRICK

˓→')

brown
˓→=

˓→Color

˓→

˓→s=78,
˓→

˓→v=15,
˓→

˓→ name=
˓→ 'BROW
˓→BRICK

˓→')

red
˓→=

˓→Color

˓→

˓→s=97,
˓→

˓→v=39,
˓→

˓→name=
˓→'RED_
˓→BRICK

˓→')

˓→#
˓→Put
˓→your

˓→color

˓→in

˓→a

˓→list

˓→or

˓→tuple

˓→

˓→#
˓→Inclu
˓→None

˓→is

˓→optio

˓→

˓→Just
˓→omit
(continues on next page) ˓→it

˓→if

121
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→you
˓→alway

˓→want

˓→to

˓→get

˓→one

˓→of

˓→your

˓→color

˓→

my_
˓→color

˓→=

˓→(gree

˓→

˓→magen
˓→

˓→brown
˓→

˓→red,
˓→

˓→None)

˓→#
˓→Save
˓→your

˓→color

˓→

sensor.
˓→detec

˓→color

˓→color

˓→#
˓→color
˓→works

˓→as

˓→usual

˓→

˓→but
˓→it
˓→only

˓→#
˓→retur
˓→one

˓→of

˓→your

˓→speci

˓→color

˓→

while
˓→True:
(continues on next page)

122
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→color
˓→=
˓→senso

˓→color

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→color

˓→

˓→

˓→

˓→

print
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Check
˓→which

˓→one

˓→it

˓→is.

˓→

˓→

˓→

˓→

˓→if
˓→color
˓→==

˓→magen

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→print
˓→"It
˓→works

˓→
(continues on next page) ")
˓→

123
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→it.

˓→

˓→

˓→

˓→

wait(
˓→

Example
3:
Read-
ing
am-
bi-
ent
hue,
sat-
u-
ra-
tion,
value,
and
color
from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param

˓→impor

˓→Port

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the
(continues on next page)
˓→senso

˓→

124
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


sensor
˓→=

˓→Color

˓→A)

˓→#
˓→Repea
˓→forev

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Get
˓→the

˓→ambie

˓→color

˓→value

˓→

˓→Inste
˓→of
˓→scann

˓→the

˓→color

˓→of

˓→ a surface,

˓→

˓→

˓→

˓→

˓→#
˓→this
˓→lets

˓→you

˓→scan

˓→the

˓→color

˓→of

˓→light

˓→sourc

˓→like

˓→lamps

˓→or

˓→ screens.

˓→

˓→

˓→

˓→hsv
˓→=
(continues on next page) ˓→senso

˓→hsv(s

125
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→color
˓→=
˓→senso

˓→color

˓→

˓→

˓→

˓→

˓→#
˓→Get
˓→the

˓→ambie

˓→light

˓→inten

˓→

˓→

˓→

˓→

˓→ambie
˓→=
˓→senso

˓→ambie

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→measu

˓→

˓→

˓→

˓→

print
˓→

˓→

color
˓→

˓→

ambie
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Point
(continues on next page) ˓→the

˓→senso

˓→at
126 ˓→a

˓→compu
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→scree

˓→or
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

#
˓→

Also,
˓→

˓→

˓→cover
˓→the
˓→senso

˓→with

˓→your

˓→hands

˓→and

˓→watch

˓→the

˓→ambie

˓→ value.

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→so

˓→we

˓→can

˓→read

˓→the

˓→print

˓→line

˓→

˓→

˓→

wait(
˓→

hsv(surface=True)
Scans
the
color
of
a
sur-
face
or
an
ex-
ter-
nal
light
source.

127
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

This
method
is
sim-
i-
lar
to
color(),
but
it
gives
the
full
range
of
hue,
sat-
u-
ration and brightness values, instead of rounding it to the nearest detectable color.
Parameters
surface
(bool)

Choose
true
to
scan
the
color
of
ob-
jects
and
sur-
faces.
Choose
false
to scan the color of screens and other external light sources.
Returns
Measured
color.
The
color
is
de-
scribed
by
a
hue
(0–359),
a
sat-
u-

128
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ra-
tion
(0–100),
and a brightness value (0–100).
Return type
Color
detectable_colo
Configures
which
col-
ors
the
color()
method
should
de-
tect.
Specify
only
col-
ors
that
you
wish
to
de-
tect
in
your
ap-
pli-
ca-
tion.
This
way,
the full-color measurements are rounded to the nearest desired color, and other colors are ignored. This improves
reliability.
If
you
give
no
ar-
gu-
ments,
the
cur-
rently
cho-
sen
col-
ors
will

129
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

be
re-
turned
as a tuple.
Parameters
colors
(list)

List
of
Color
ob-
jects:
the
col-
ors
that
you
want
to
de-
tect.
You can pick standard colors such as Color.MAGENTA, or provide your own colors like Color(h=348, s=96,
v=40, name='MY_MAGENTA_BRICK') for even better results. You measure your own colors with the hsv()
method.

Built-
in
lights

This
sen-
sor
has
3
built-
in
lights.
You
can
ad-
just
the
bright-
ness
of
each
light.
If you use the sensor to measure something, the lights will be turned on or off as needed for the measurement.
Show/hide
ex-
am-

130
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ples
Example:
Blink-
ing
the
built-
in
lights
from
˓→pybri

˓→pupde

˓→impor

˓→Color

from
˓→pybri

˓→param

˓→impor

˓→Port

from
˓→pybri

˓→tools

˓→impor

˓→wait

˓→#
˓→Initi
˓→the

˓→senso

˓→

sensor
˓→=

˓→Color

˓→A)

˓→#
˓→Repea
˓→forev

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→on

˓→one

˓→light

˓→at

˓→a

˓→time,

(continues on next page) ˓→

˓→at
˓→half
131 ˓→the

˓→brigh
LEGO, the LEGO
˓→ logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Do
˓→this

˓→for

˓→all

˓→3

˓→light

˓→and

˓→repea

˓→that

˓→5

˓→times

˓→

˓→

˓→

˓→

˓→for
˓→i
˓→in

˓→range

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→on(50

˓→

0,
˓→

˓→

0)
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(
˓→

˓→

˓→

˓→

˓→

˓→

˓→
(continues on next page) ˓→

˓→senso
˓→light
132 ˓→on(0,

˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
50,
˓→

˓→
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→on(0,

˓→

0,
˓→

˓→

50)
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→all

˓→light

˓→on

˓→at

˓→maxim

˓→brigh

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→on(10

˓→
(continues on next page) ˓→

˓→

wait(
˓→
133
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→all

˓→light

˓→off.

˓→

˓→

˓→

˓→

˓→senso
˓→light
˓→off()

˓→

˓→

˓→

wait(
˓→

lights.on(bright
Turns
on
the
lights
at
the
spec-
i-
fied
bright-
ness.
Parameters
brightness
(tu-
ple
of
bright-
ness:
%)

Bright-
ness
of
each
light,
in
the
or-

134
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

der
shown above. If you give one brightness value instead of a tuple, all lights get the same brightness.
lights.off()
Turns
off
all
the
lights.

5.6 Ultras
Sen-
sor

Show/hide
ex-
am-
ples
Example
1:
Mea-
sur-
ing
dis-
tance
and
switch-
ing
on
the
lights
from
˓→pybricks.

˓→pupdevices

˓→import

˓→Ultrasonic

from
˓→pybricks.

˓→parameters

˓→import

˓→Port
(continues on next page)

135
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

eyes
˓→=

˓→Ultrasonic

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→measured

˓→distance.

˓→

˓→

˓→

˓→

˓→print(eyes
˓→distance()

˓→

˓→

˓→

˓→

˓→#
˓→If
˓→an

˓→object

˓→is

˓→detected

˓→closer

˓→than

˓→500mm:

˓→

˓→

˓→

˓→if
˓→eyes.
(continues on next page) ˓→distance()

˓→

˓→<
136 ˓→500:
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→the

˓→lights

˓→on.

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→eyes.
˓→lights.
˓→on(100)

˓→

˓→

˓→

else:
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→the

˓→lights

˓→off.

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→eyes.
˓→lights.
˓→off()
(continues on next page)

137
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→some

˓→time

˓→so

˓→we

˓→can

˓→read

˓→what

˓→is

˓→printed.

˓→

˓→

˓→

˓→

˓→wait(100)

Example
2:
Us-
ing
math
to
grad-
u-
ally
change
the
bright-
ness
of
the
lights
from
˓→pybricks.

˓→pupdevices

˓→import

˓→Ultrasonic

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait,
(continues on next page)
˓→

˓→StopWatch
138
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→The
˓→math

˓→module

˓→is

˓→part

˓→of

˓→standard

˓→MicroPytho

˓→ #
˓→ https:/
˓→/

˓→docs.

˓→micropytho

˓→org/

˓→en/

˓→latest/

˓→library/

˓→math.

˓→html

from
˓→math

˓→import

˓→pi,

˓→

˓→sin

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

eyes
˓→=

˓→Ultrasonic

˓→A)

˓→#
˓→Initialize
˓→a

˓→timer.

˓→

watch
˓→=

˓→StopWatch(

˓→#
˓→We
˓→want

˓→one

˓→full
(continues on next page) ˓→light

˓→cycle

˓→to
139 ˓→last

˓→three
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→seconds.

˓→
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


PERIOD
˓→=

˓→3000

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→The
˓→phase

˓→is

˓→where

˓→we

˓→are

˓→in

˓→the

˓→unit

˓→circle

˓→now.

˓→

˓→

˓→

˓→

˓→phase
˓→=
˓→watch.

˓→time()/

˓→PERIOD*2*p

˓→

˓→

˓→

˓→

˓→#
˓→Each
˓→light

˓→follows

˓→a

˓→sine

˓→wave

˓→with

˓→a

˓→mean

˓→of

˓→50,

˓→

˓→ with an amplitude of 50.

˓→

˓→

˓→
(continues on next page) ˓→

˓→#
˓→We
140 ˓→offset

˓→this
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→sine

˓→wave
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→lights
˓→do

˓→something

˓→different.

˓→

˓→

˓→

˓→

˓→brightness
˓→=
˓→[sin(phase

˓→+

˓→offset*pi/

˓→2)

˓→*

˓→50

˓→+

˓→50

˓→for

˓→offset

˓→in

˓→range(4)]

˓→

˓→

˓→

˓→

˓→#
˓→Set
˓→the

˓→brightness

˓→values

˓→for

˓→all

˓→lights.

˓→

˓→The
˓→*
˓→symbol

˓→unpacks

˓→ the list

˓→

˓→

˓→

˓→

˓→#
˓→of
˓→brightness
(continues on next page) ˓→values

˓→into

˓→separate
141 ˓→arguments.

˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→eyes.
˓→lights.
˓→on(*bright

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→some

˓→time.

˓→

˓→

˓→

˓→

wait(50)
˓→

class Ultrasoni
LEGO®
SPIKE
Color
Sen-
sor.
Parameters
port
(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
distance()
Measures
the
dis-
tance
be-
tween
the
sen-
sor
and

142
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

an
ob-
ject
us-
ing
ul-
tra-
sonic sound waves.
Returns
Measured
dis-
tance.
If
no
valid
dis-
tance
was
mea-
sured,
it
re-
turns
2000
mm.
Return type
distance:
mm
presence()
Checks
for
the
pres-
ence
of
other
ul-
tra-
sonic
sen-
sors
by
de-
tect-
ing
ul-
trasonic sounds.
Returns
True
if
ul-
tra-

143
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

sonic
sounds
are
de-
tected,
False
if
not.
Return type
bool

Built-
in
lights

This
sen-
sor
has
4
built-
in
lights.
You
can
ad-
just
the
bright-
ness
of
each
light.

lights.on(bright
Turns
on
the
lights
at
the
spec-
i-
fied
bright-
ness.
Parameters
brightness
(tu-
ple
of

144
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

bright-
ness:
%)

Bright-
ness
of
each
light,
in
the
or-
der
shown above. If you give one brightness value instead of a tuple, all lights get the same brightness.
lights.off()
Turns
off
all
the
lights.

5.7 Force
Sen-
sor

Show/hide
ex-
am-
ples
Example
1:
Mea-
sur-
ing
force
and
move-
ment

145
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

from
˓→pybricks.

˓→pupdevices

˓→import

˓→ForceSenso

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

button
˓→=

˓→ForceSenso

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→all

˓→the

˓→informatio

˓→we

˓→can

˓→get

˓→from

˓→this

˓→sensor.

˓→

˓→

˓→

˓→

˓→force
˓→=
˓→button.

˓→force()

˓→

˓→

˓→
(continues on next page)
˓→dist
˓→=
˓→button.
146
˓→distance()

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→press
˓→=
˓→button.

˓→pressed()

˓→

˓→

˓→

˓→touch
˓→=
˓→button.

˓→touched()

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→values

˓→

˓→

˓→

˓→print(
˓→"Force
˓→",

˓→

force,
˓→

˓→

˓→

"Dist:
˓→

",
˓→

˓→

dist,
˓→

˓→

˓→

"Pressed:
˓→

˓→ ", press, "Touched:", touch)

˓→

˓→

˓→

˓→

˓→#
˓→Push
˓→the

˓→sensor

˓→button

˓→see
(continues on next page) ˓→what

˓→happens

˓→to
147 ˓→the

˓→values.
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→some

˓→time

˓→so

˓→we

˓→can

˓→read

˓→what

˓→is

˓→printed.

˓→

˓→

˓→

˓→

˓→wait(200)

Example
2:
Mea-
sur-
ing
peak
force
from
˓→pybricks.

˓→pupdevices

˓→import

˓→ForceSenso

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

button
˓→=

˓→ForceSenso
(continues on next page)
˓→A)

148
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→This
˓→function

˓→waits

˓→until

˓→the

˓→button

˓→is

˓→pushed.

˓→

˓→It
˓→keeps
˓→track

˓→of

˓→the

˓→maximum

˓→#
˓→detected
˓→force

˓→until

˓→the

˓→button

˓→is

˓→released.

˓→

˓→Then
˓→it
˓→returns

˓→the

˓→maximum.

˓→

def
˓→wait_

˓→for_

˓→force():

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→for

˓→a

˓→force,

˓→

˓→by
˓→doing
˓→nothing

˓→for

˓→as

˓→long
(continues on next page) ˓→the

˓→ force is nearly zero.

149
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→print(
˓→"Waiting
˓→for

˓→force.

˓→

")
˓→

˓→

˓→

˓→

˓→while
˓→button.
˓→force()

˓→

˓→<=
˓→0.
˓→1:

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(10)
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Now
˓→we

˓→wait

˓→for

˓→the

˓→release,

˓→

˓→by
˓→waiting
˓→for

˓→the

˓→force

˓→ to be zero again.

˓→

˓→

˓→

˓→print(
˓→"Waiting
˓→for
(continues on next page) ˓→release.

˓→

")
˓→
150
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→While
˓→we

˓→wait

˓→for

˓→that

˓→to

˓→happen,

˓→

˓→we
˓→keep
˓→reading

˓→the

˓→ force and remember

˓→

˓→

˓→

˓→

˓→#
˓→the
˓→maximum

˓→force.

˓→

˓→We
˓→do
˓→this

˓→by

˓→initializi

˓→the

˓→maximum

˓→at

˓→ 0, and

˓→

˓→

˓→

˓→

˓→#
˓→updating
˓→it

˓→each

˓→time

˓→we

˓→detect

˓→a

˓→bigger

˓→force.

˓→

˓→
(continues on next page) ˓→

˓→

˓→maximum
151 ˓→=
˓→0
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→force
˓→=
˓→10

˓→

˓→

˓→

˓→while
˓→force
˓→>

˓→

0.
˓→

1:
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→the

˓→force.

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→force
˓→=
˓→button.

˓→force()

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Update
˓→the

˓→maximum
(continues on next page) ˓→if

˓→the

˓→measured
152 ˓→force

˓→is
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→ larger.
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→if
˓→force
˓→>

˓→

maximum:
˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→maximum
˓→=
˓→force

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→and

˓→then

˓→measure

˓→again.

˓→

˓→

˓→

˓→

˓→

˓→

˓→

˓→

wait(10)
˓→

˓→
(continues on next page) ˓→

˓→

˓→
153 ˓→#
˓→Return
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→the

˓→maximum
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→return
˓→maximum

˓→#
˓→Keep
˓→waiting

˓→for

˓→the

˓→sensor

˓→button

˓→to

˓→be

˓→pushed.

˓→

˓→When
˓→it
˓→is,

˓→

˓→display

˓→#
˓→the
˓→peak

˓→force

˓→and

˓→repeat.

˓→

while
˓→True:

˓→

˓→

˓→

˓→peak
˓→=
˓→wait_

˓→for_

˓→force()

˓→

˓→

˓→

˓→print(
˓→"Released.
˓→

˓→Peak
˓→force:
˓→

˓→{0}
˓→

˓→N\n
(continues on next page) ˓→".
˓→format(pea

154
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

class ForceSens
LEGO®
SPIKE
Force
Sen-
sor.
Parameters
port
(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
force()
Measures
the
force
ex-
erted
on
the
sen-
sor.
Returns
Measured
force
(up
to
ap-
prox-
i-
mately
10.00
N).
Return type
force:
N
distance()
Measures
by
how
much
the

155
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

sen-
sor
but-
ton
has
moved.
Returns
How
much
the
sen-
sor
but-
ton
has
moved
(up
to
ap-
prox-
i-
mately
8.00
mm).
Return type
distance:
mm
pressed(force=3)
Checks
if
the
sen-
sor
but-
ton
is
pressed.
Parameters
force
(force:
N)

Min-
i-
mum
force
to
be
con-
sid-
ered
pressed.

156
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns
True
if
the
sen-
sor
is
pressed,
False
if
it
is
not.
Return type
bool
touched()
Checks
if
the
sen-
sor
is
touched.
This
is
sim-
i-
lar
to
pressed(),
but
it
de-
tects
slight
move-
ments
of
the
but-
ton
even when the measured force is still considered zero.
Returns
True
if
the
sen-
sor
is
touched
or
pressed,

157
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

False
if
it
is
not.
Return type
bool

5.8 Infrar
Sen-
sor

Show/hide
ex-
am-
ple
Example:
Mea-
sur-
ing
dis-
tance,
ob-
ject
count,
and
re-
flec-
tion

from
˓→pybricks.

˓→pupdevices

˓→import

˓→InfraredSe

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

(continues on next page)

158
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

ir
˓→=

˓→InfraredSe

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→all

˓→the

˓→informatio

˓→we

˓→can

˓→get

˓→from

˓→this

˓→sensor.

˓→

˓→

˓→

˓→

˓→dist
˓→=
˓→ir.

˓→distance()

˓→

˓→

˓→

˓→count
˓→=
˓→ir.

˓→count()

˓→

˓→

˓→

˓→ref
(continues on next page) ˓→=
˓→ir.

˓→reflection
159
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→values

˓→

˓→

˓→

˓→print(
˓→"Distance:
˓→",

˓→

dist,
˓→

˓→

˓→

"Count:
˓→

",
˓→

˓→

count,
˓→

˓→

˓→

"Reflectio
˓→

˓→ ", ref)

˓→

˓→

˓→

˓→

˓→#
˓→Move
˓→the

˓→sensor

˓→around

˓→and

˓→move

˓→your

˓→hands

˓→in

˓→front

˓→

˓→

˓→

˓→

˓→#
˓→of
˓→it

˓→to

˓→see

˓→what
(continues on next page) ˓→happens

˓→to

˓→the
160 ˓→values.

˓→
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→some

˓→time

˓→so

˓→we

˓→can

˓→read

˓→what

˓→is

˓→printed.

˓→

˓→

˓→

˓→

wait(200)
˓→

class InfraredS
LEGO®
Pow-
ered
Up
In-
frared
Sen-
sor.
Parameters
port
(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
distance()
Measures
the
rel-
a-
tive
dis-
tance

161
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

be-
tween
the
sen-
sor
and
an
ob-
ject
us-
ing infrared light.
Returns
Relative
dis-
tance
rang-
ing
from
0
(clos-
est)
to
100
(far-
thest).
Return type
relative
dis-
tance:
%
reflection()
Measures
the
re-
flec-
tion
of
a
sur-
face
us-
ing
an
in-
frared
light.
Returns
Reflection,
rang-
ing
from
0.0

162
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(no
re-
flec-
tion)
to
100.0
(high
re-
flec-
tion).
Return type
percentage:
%
count()
Counts
the
num-
ber
of
ob-
jects
that
have
passed
by
the
sen-
sor.
Returns
Number
of
ob-
jects
counted.
Return type
int

5.9 Tilt
Sen-
sor

Show/hide
ex-
am-
ple
Example:
Mea-
sur-
ing

163
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

pitch
and
roll
from
˓→pybricks.

˓→pupdevices

˓→import

˓→TiltSensor

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→sensor.

˓→

accel
˓→=

˓→TiltSensor

˓→A)

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Read
˓→the

˓→tilt

˓→angles

˓→relative

˓→to

˓→the

˓→horizontal
(continues on next page)
˓→plane.

˓→

164
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

pitch,
˓→

˓→

˓→roll
˓→=
˓→accel.

˓→tilt()

˓→

˓→

˓→

˓→

˓→#
˓→Print
˓→the

˓→values

˓→

˓→

˓→

˓→print(
˓→"Pitch:
˓→",

˓→

pitch,
˓→

˓→

˓→

"Roll:
˓→

",
˓→

˓→

roll)
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Wait
˓→some

˓→time

˓→so

˓→we

˓→can

˓→read

˓→what

˓→is

˓→printed.

˓→

˓→

˓→

˓→
(continues on next page) wait(100)
˓→

165
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

class TiltSenso
LEGO®
Pow-
ered
Up
Tilt
Sen-
sor.
Parameters
port
(Port)

Port
to
which
the
sen-
sor
is
con-
nected.
tilt()
Measures
the
tilt
rel-
a-
tive
to
the
hor-
i-
zon-
tal
plane.
Returns
Tuple
of
pitch
and
roll
an-
gles.
Return type
(angle:
deg,
an-
gle:
deg)

166
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

5.10 Ligh

Show/hide
ex-
am-
ples
Example
1:
Mak-
ing
the
light
blink
from
˓→pybricks.

˓→pupdevices

˓→import

˓→Light

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait

˓→#
˓→Initialize
˓→the

˓→light.

˓→

light
˓→=

˓→Light(Port

˓→A)

˓→#
˓→Blink
(continues on next page)
˓→the

˓→light

˓→forever.
167
˓→

LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→the

˓→light

˓→on

˓→at

˓→100

˓→%

˓→brightness

˓→

˓→

˓→

˓→

˓→light.
˓→on(100)

˓→

˓→

˓→

˓→wait(500)

˓→

˓→

˓→

˓→

˓→#
˓→Turn
˓→the

˓→light

˓→off.

˓→

˓→

˓→

˓→

˓→light.
˓→off()

˓→

˓→

˓→

˓→wait(500)

Example
2:
Us-
ing
math

168
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

to
grad-
u-
ally
change
the
bright-
ness
of
the
light
from
˓→pybricks.

˓→pupdevices

˓→import

˓→Light

from
˓→pybricks.

˓→parameters

˓→import

˓→Port

from
˓→pybricks.

˓→tools

˓→import

˓→wait,

˓→

˓→StopWatch

˓→#
˓→The
˓→math

˓→module

˓→is

˓→part

˓→of

˓→standard

˓→MicroPytho

˓→ #
˓→ https:/
˓→/

˓→docs.

˓→micropytho

˓→org/

˓→en/

˓→latest/

˓→library/

˓→math.

˓→html

from
˓→math

˓→import

˓→pi,

˓→

(continues on next page)


˓→cos

169
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→#
˓→Initialize
˓→the

˓→light

˓→and

˓→a

˓→StopWatch.

˓→

light
˓→=

˓→Light(Port

˓→A)

watch
˓→=

˓→StopWatch(

˓→#
˓→Cosine
˓→pattern

˓→properties

˓→

PERIOD
˓→=

˓→2000

MAX
˓→=

˓→100

˓→#
˓→Make
˓→the

˓→brightness

˓→fade

˓→in

˓→and

˓→out.

˓→

while
˓→True:

˓→

˓→

˓→

˓→

˓→#
˓→Get
˓→phase

˓→of

˓→the

˓→cosine.

˓→

˓→
(continues on next page) ˓→

˓→

˓→phase
170 ˓→=
˓→watch.
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
˓→time()/

˓→PERIOD*2*p
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

˓→

˓→

˓→

˓→

˓→#
˓→Evaluate
˓→the

˓→brightness

˓→

˓→

˓→

˓→

˓→brightness
˓→=
˓→(0.

˓→5

˓→-

˓→

0.
˓→

5*cos(phas
˓→

˓→

˓→

˓→

˓→

˓→#
˓→Set
˓→light

˓→brightness

˓→and

˓→wait

˓→a

˓→bit.

˓→

˓→

˓→

˓→

light.
˓→

on(brightn
˓→

˓→

˓→

˓→

wait(10)
˓→

class Light(port
LEGO®
Pow-
ered
Up
Light.

171
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Parameters
port
(Port)

Port
to
which
the
de-
vice
is
con-
nected.
on(brightness=100)
Turns
on
the
light
at
the
spec-
i-
fied
bright-
ness.
Parameters
brightness
(bright-
ness:
%)

Bright-
ness
of
the
light.
off()
Turns
off
the
light.

172
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 6

ev3devices – EV3 Devices

LEGO® MINDSTORMS® EV3 motors and sensors.

6.1 Motors

Figure 6.1: EV3-compatible motors. The arrows indicate the default positive direction.

class Motor(port, positive_direction=Direction.CLOCKWISE, gears=None)


Generic class to control motors with built-in rotation sensors.
Parameters
• port (Port) – Port to which the motor is connected.
• positive_direction (Direction) – Which direction the motor should turn when
you give a positive speed value or angle.
• gears (list) – List of gears linked to the motor.
For example: [12, 36] represents a gear train with a 12-tooth and a 36-tooth gear. Use a
list of lists for multiple gear trains, such as [[12, 36], [20, 16, 40]].
When you specify a gear train, all motor commands and settings are automatically adjusted
to account for the resulting gear ratio. The motor direction remains unchanged by this.

173
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Measuring

speed()
Gets the speed of the motor.
Returns Motor speed.
Return type rotational speed: deg/s
angle()
Gets the rotation angle of the motor.
Returns Motor angle.
Return type angle: deg
reset_angle(angle)
Sets the accumulated rotation angle of the motor to a desired value.
Parameters angle (angle: deg) – Value to which the angle should be reset.

Stopping

stop()
Stops the motor and lets it spin freely.
The motor gradually stops due to friction.
brake()
Passively brakes the motor.
The motor stops due to friction, plus the voltage that is generated while the motor is still moving.
hold()
Stops the motor and actively holds it at its current angle.

Action

run(speed)
Runs the motor at a constant speed.
The motor accelerates to the given speed and keeps running at this speed until you give a new command.
Parameters speed (rotational speed: deg/s) – Speed of the motor.
run_time(speed, time, then=Stop.HOLD, wait=True)
Runs the motor at a constant speed for a given amount of time.
The motor accelerates to the given speed, keeps running at this speed, and then decelerates. The total
maneuver lasts for exactly the given amount of time.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• time (time: ms) – Duration of the maneuver.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the maneuver to complete before continuing with the rest of the
program.

174
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

run_angle(speed, rotation_angle, then=Stop.HOLD, wait=True)


Runs the motor at a constant speed by a given angle.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• rotation_angle (angle: deg) – Angle by which the motor should rotate.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the maneuver to complete before continuing with the rest of the
program.
run_target(speed, target_angle, then=Stop.HOLD, wait=True)
Runs the motor at a constant speed towards a given target angle.
The direction of rotation is automatically selected based on the target angle. It does matter if speed is
positive or negative.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• target_angle (angle: deg) – Angle that the motor should rotate to.
• then (Stop) – What to do after coming to a standstill.
• wait (bool) – Wait for the motor to reach the target before continuing with the rest of
the program.
run_until_stalled(speed, then=Stop.COAST, duty_limit=None)
Runs the motor at a constant speed until it stalls.
Parameters
• speed (rotational speed: deg/s) – Speed of the motor.
• then (Stop) – What to do after coming to a standstill.
• duty_limit (percentage: %) – Torque limit during this command. This is useful to
avoid applying the full motor torque to a geared or lever mechanism.
Returns Angle at which the motor becomes stalled.
Return type angle: deg
dc(duty)
Rotates the motor at a given duty cycle (also known as “power”).
This method lets you use a motor just like a simple DC motor.
Parameters duty (percentage: %) – The duty cycle (-100.0 to 100).

Advanced motion control

track_target(target_angle)
Tracks a target angle. This is similar to run_target(), but the usual smooth acceleration is skipped: it
will move to the target angle as fast as possible. This method is useful if you want to continuously change
the target angle.
Parameters target_angle (angle: deg) – Target angle that the motor should rotate to.

175
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

control
The motors use PID control to accurately track the speed and angle targets that you specify. You can
change its behavior through the control attribute of the motor. See The Control Class for an overview
of available methods.

6.2 Touch Sensor

class TouchSensor(port)
LEGO® MINDSTORMS® EV3 Touch Sensor.
Parameters port (Port) – Port to which the sensor is connected.
pressed()
Checks if the sensor is pressed.
Returns True if the sensor is pressed, False if it is not pressed.
Return type bool

6.3 Color Sensor

class ColorSensor(port)
LEGO® MINDSTORMS® EV3 Color Sensor.
Parameters port (Port) – Port to which the sensor is connected.
color()
Measures the color of a surface.
Returns Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED,
Color.WHITE, Color.BROWN or None.
Return type Color, or None if no color is detected.
ambient()
Measures the ambient light intensity.
Returns Ambient light intensity, ranging from 0 (dark) to 100 (bright).

176
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Return type percentage: %


reflection()
Measures the reflection of a surface using a red light.
Returns Reflection, ranging from 0 (no reflection) to 100 (high reflection).
Return type percentage: %
rgb()
Measures the reflection of a surface using a red, green, and then a blue light.
Returns Tuple of reflections for red, green, and blue light, each ranging from 0.0 (no reflection)
to 100.0 (high reflection).
Return type (percentage: %, percentage: %, percentage: %)

6.4 Infrared Sensor and Beacon

Each method of this class puts the sensor in a different mode. Switching modes takes about one second on this sensor.
To make sure that your program runs quickly, use only of these methods in your program.

class InfraredSensor(port)
LEGO® MINDSTORMS® EV3 Infrared Sensor and Beacon.
Parameters port (Port) – Port to which the sensor is connected.
distance()
Measures the relative distance between the sensor and an object using infrared light.
Returns Relative distance ranging from 0 (closest) to 100 (farthest).
Return type relative distance: %
beacon(channel)
Measures the relative distance and angle between the remote and the infrared sensor.
Parameters channel (int) – Channel number of the remote.
Returns Tuple of relative distance (0 to 100) and approximate angle (-75 to 75 degrees) between
remote and infrared sensor.
Return type (relative distance: %, angle: deg) or (None, None) if no remote is detected.
buttons(channel)
Checks which buttons on the infrared remote are pressed.
This method can detect up to two buttons at once. If you press more buttons, you may not get useful data.
Parameters channel (int) – Channel number of the remote.
Returns List of pressed buttons on the remote on selected channel.

177
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Return type List of Button


keypad()
Checks which buttons on the infrared remote are pressed.
This method can independently detect all 4 up/down buttons, but it cannot detect the beacon button.
This method only works with the remote in channel 1.
Returns List of pressed buttons on the remote on selected channel.
Return type List of Button

6.5 Ultrasonic Sensor

class UltrasonicSensor(port)
LEGO® MINDSTORMS® EV3 Ultrasonic Sensor.
Parameters port (Port) – Port to which the sensor is connected.
distance(silent=False)
Measures the distance between the sensor and an object using ultrasonic sound waves.
Parameters silent (bool) – Choose True to turn the sensor off after measuring the distance.
This reduces interference with other ultrasonic sensors. If you do this too frequently, the
sensor can freeze. If this happens, unplug it and plug it back in.
Returns Distance.
Return type distance: mm
presence()
Checks for the presence of other ultrasonic sensors by detecting ultrasonic sounds.
If the other ultrasonic sensor is operating in silent mode, you can only detect the presence of that sensor
while it is taking a measurement.
Returns True if ultrasonic sounds are detected, False if not.
Return type bool

6.6 Gyroscopic Sensor

class GyroSensor(port, positive_direction=Direction.CLOCKWISE)


LEGO® MINDSTORMS® EV3 Gyro Sensor.
Parameters
• port (Port) – Port to which the sensor is connected.

178
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• positive_direction (Direction) – Positive rotation direction when looking at the


red dot on top of the sensor.
speed()
Gets the speed (angular velocity) of the sensor.
Returns Sensor angular velocity.
Return type rotational speed: deg/s
angle()
Gets the accumulated angle of the sensor.
Returns Rotation angle.
Return type angle: deg
If you use the angle() method, you cannot use the speed() method in the same program. Doing so
would reset the sensor angle to zero every time you read the speed.
reset_angle(angle)
Sets the rotation angle of the sensor to a desired value.
Parameters angle (angle: deg) – Value to which the angle should be reset.

179
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 7

nxtdevices – NXT Devices

Use LEGO® MINDSTORMS® NXT motors and sensors with the EV3 brick.

7.1 NXT Motor

This motor works just like a LEGO MINDSTORMS EV3 Large Motor. You can use it in your programs using the
Motor class.

7.2 NXT Touch Sensor

class TouchSensor(port)
LEGO® MINDSTORMS® NXT Touch Sensor.
Parameters port (Port) – Port to which the sensor is connected.
pressed()
Checks if the sensor is pressed.
Returns True if the sensor is pressed, False if it is not pressed.
Return type bool

180
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

7.3 NXT Light Sensor

class LightSensor(port)
LEGO® MINDSTORMS® NXT Color Sensor.
Parameters port (Port) – Port to which the sensor is connected.
ambient()
Measures the ambient light intensity.
Returns Ambient light intensity, ranging from 0 (dark) to 100 (bright).
Return type percentage: %
reflection()
Measures the reflection of a surface using a red light.
Returns Reflection, ranging from 0 (no reflection) to 100 (high reflection).
Return type percentage: %

7.4 NXT Color Sensor

class ColorSensor(port)
LEGO® MINDSTORMS® NXT Color Sensor.
Parameters port (Port) – Port to which the sensor is connected.
color()
Measures the color of a surface.
Returns Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED,
Color.WHITE or None.
Return type Color, or None if no color is detected.
ambient()
Measures the ambient light intensity.
Returns Ambient light intensity, ranging from 0 (dark) to 100 (bright).

181
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Return type percentage: %


reflection()
Measures the reflection of a surface.
Returns Reflection, ranging from 0 (no reflection) to 100 (high reflection).
Return type percentage: %
rgb()
Measures the reflection of a surface using a red, green, and then a blue light.
Returns Tuple of reflections for red, green, and blue light, each ranging from 0.0 (no reflection)
to 100.0 (high reflection).
Return type (percentage: %, percentage: %, percentage: %)

Built-in light

This sensor has a built-in light. You can make it red, green, blue, or turn it off.
light.on(color)
Turns on the light at the specified color.
Parameters color (Color) – Color of the light.
light.off()
Turns off the light.

7.5 NXT Ultrasonic Sensor

class UltrasonicSensor(port)
LEGO® MINDSTORMS® NXT Ultrasonic Sensor.
Parameters port (Port) – Port to which the sensor is connected.
distance()
Measures the distance between the sensor and an object using ultrasonic sound waves.
Returns Distance.
Return type distance: mm

7.6 NXT Sound Sensor


class SoundSensor(port)
LEGO® MINDSTORMS® NXT Sound Sensor.

182
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Parameters port (Port) – Port to which the sensor is connected.


intensity(audible_only=True)
Measures the ambient sound intensity (loudness).
Parameters audible_only (bool) – Detect only audible sounds. This tries to filter out
frequencies that cannot be heard by the human ear.
Returns Sound intensity.
Return type percentage: %

7.7 NXT Temperature Sensor

class TemperatureSensor(port)
LEGO® MINDSTORMS® NXT Temperature Sensor.
Parameters port (Port) – Port to which the sensor is connected.
temperature()
Measures the temperature.
Returns Measured temperature.
Return type temperature: °C

7.8 NXT Energy Meter


class EnergyMeter(port)
LEGO® MINDSTORMS® Education NXT Energy Meter.
Parameters port (Port) – Port to which the sensor is connected.
storage()
Gets the total available energy stored in the battery.

183
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns Remaining stored energy.


Return type energy: J
input()
Measures the electrical signals at the input (bottom) side of the energy meter. It measures the voltage
applied to it and the current passing through it. The product of these two values is power. This power
value is the rate at which the stored energy increases. This power is supplied by an energy source such as
the provided solar panel or an externally driven motor.
Returns Voltage, current, and power measured at the input port.
Return type (voltage: mV, current: mA, power: mW)
output()
Measures the electrical signals at the output (top) side of the energy meter. It measures the voltage applied
to the external load and the current passing to it. The product of these two values is power. This power
value is the rate at which the stored energy decreases. This power is consumed by the load, such as a light
or a motor.
Returns Voltage, current, and power measured at the output port.
Return type (voltage: mV, current: mA, power: mW)

7.9 Vernier Adapter

class VernierAdapter(port, conversion=None)


LEGO® MINDSTORMS® Education NXT/EV3 Adapter for Vernier Sensors.
Parameters
• port (Port) – Port to which the sensor is connected.
• conversion (callable) – Function of the format conversion(). This function is
used to convert the raw analog voltage to the sensor-specific output value. Each Vernier Sen-
sor has its own conversion function. The example given below demonstrates the conversion
for the Surface Temperature Sensor.
voltage()
Measures the raw analog sensor voltage.
Returns Analog voltage.
Return type voltage: mV
conversion(voltage)
Converts the raw voltage (mV) to a sensor value.

184
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

If you did not provide a conversion function earlier, no conversion will be applied.
Parameters voltage (voltage: mV) – Analog sensor voltage
Returns Converted sensor value.
Return type float
value()
Measures the sensor voltage() and then applies your conversion() to give you the sensor value.
Returns Converted sensor value.
Return type float
Show/hide example
Example: Using the Surface Temperature Sensor.

#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.nxtdevices import VernierAdapter

from math import log

# Conversion formula for Surface Temperature Sensor


def convert_raw_to_temperature(voltage):

# Convert the raw voltage to the NTC resistance


# according to the Vernier Adapter EV3 block.
counts = voltage/5000*4096
ntc = 15000*(counts)/(4130-counts)

# Handle log(0) safely: make sure that ntc value is positive.


if ntc <= 0:
ntc = 1

# Apply Steinhart-Hart equation as given in the sensor documentation.


K0 = 1.02119e-3
K1 = 2.22468e-4
K2 = 1.33342e-7
return 1/(K0 + K1*log(ntc) + K2*log(ntc)**3)

# Initialize the adapter on port 1


thermometer = VernierAdapter(Port.S1, convert_raw_to_temperature)

# Get the measured value and print it


temp = thermometer.value()
print(temp)

185
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 8

iodevices – Generic I/O Devices

Generic input/output devices.

Note: This module provides classes to interact with unofficial motors, sensors, and other custom electronics. You
should only connect custom electronics or unofficial devices if you know what you are doing. Proceed with caution.

8.1 LUMP Device

class LUMPDevice(port)
Devices using the LEGO UART Messaging Protocol.
Parameters port (Port) – Port to which the device is connected.
read(mode)
Reads values from a given mode.
Parameters mode (int) – Device mode.

186
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns Values read from the sensor.


Return type tuple
write(mode, values)
Writes values to the sensor. Only selected sensors and modes support this.
Parameters
• mode (int) – Device mode.
• data (tuple) – Values to be written.
The classes listed below are only available on the EV3.

8.2 Analog Sensor

class AnalogSensor(port)
Generic or custom analog sensor.
Parameters port (Port) – Port to which the sensor is connected.
voltage()
Measures analog voltage.
Returns Analog voltage.
Return type voltage: mV
resistance()
Measures resistance.
This value is only meaningful if the analog device is a passive load such as a resistor or thermistor.
Returns Resistance of the analog device.
Return type resistance: Ω
active()
Sets sensor to active mode. This sets pin 5 of the sensor port to high.
This is used in some analog sensors to control a switch. For example, if you use the NXT Light Sensor
as a custom analog sensor, this method will turn the light on. From then on, voltage() returns the raw
reflected light value.
passive()
Sets sensor to passive mode. This sets pin 5 of the sensor port to low.
This is used in some analog sensors to control a switch. For example, if you use the NXT Light Sensor
as a custom analog sensor, this method will turn the light off. From then on, voltage() returns the raw
ambient light value.

187
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

8.3 I2C Device

class I2CDevice(port, address)


Generic or custom I2C device.
Parameters
• port (Port) – Port to which the device is connected.
• address (int) – I2C address of the client device. See I2C Addresses.
read(reg, length=1)
Reads bytes, starting at a given register.
Parameters
• reg (int) – Register at which to begin reading: 0–255 or 0x00–0xFF.
• length (int) – How many bytes to read.
Returns Bytes returned from the device.
Return type bytes
write(reg, data=None)
Writes bytes, starting at a given register.
Parameters
• reg (int) – Register at which to begin writing: 0–255 or 0x00–0xFF.
• data (bytes) – Bytes to be written.
Show/hide example
Example: Read and write to an I2C device.

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port

# Initialize the EV3


ev3 = EV3Brick()

# Initialize I2C Sensor


device = I2CDevice(Port.S2, 0xD2 >> 1)

# Read one byte from the device.


# For this device, we can read the Who Am I
# register (0x0F) for the expected value: 211.
if 211 not in device.read(0x0F):
raise OSError("Device is not attached")

(continues on next page)

188
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# To write data, create a bytes object of one
# or more bytes. For example:
# data = bytes((1, 2, 3))

# Write one byte (value 0x08) to register 0x22


device.write(0x22, bytes((0x08,)))

8.3.1 I2C Addresses

I2C addresses are 7-bit values. However, most vendors who make LEGO compatible sensors provide an 8-bit address
in their documentation. To use those addresses, you must shift them by 1 bit. For example, if the documented address
is 0xD2, you can do address = 0xD2 >> 1.

8.3.2 Advanced I2C Commands

Some rudimentary I2C devices do not require a register argument or even any data. You can achieve this behavior as
shown in the examples below.
Show/hide example
Example: Advanced I2C read and write techniques.

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port

# Initialize the EV3


ev3 = EV3Brick()

# Initialize I2C Sensor


device = I2CDevice(Port.S2, 0xD2 >> 1)

# Recommended for reading


result, = device.read(reg=0x0F, length=1)

# Read 1 byte from no particular register:


device.read(reg=None, length=1)

# Read 0 bytes from no particular register:


device.read(reg=None, length=0)

# I2C write operations consist of a register byte followed


# by a series of data bytes. Depending on your device, you
# can choose to skip the register or data as follows:

# Recommended for writing:


device.write(reg=0x22, data=b'\x08')

# Write 1 byte to no particular register:


device.write(reg=None, data=b'\x08')

# Write 0 bytes to a particular register:


device.write(reg=0x08, data=None)
(continues on next page)

189
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Write 0 bytes to no particular register:


device.write(reg=None, data=None)

Additional technical resources


The I2CDevice class methods call functions from the Linux SMBus driver. To find out which commands are called
under the hood, check the Pybricks source code. More details about using I2C without MicroPython can be found on
the ev3dev I2C page.

8.4 UART Device

class UARTDevice(port, baudrate, timeout=None)


Generic UART device.
Parameters
• port (Port) – Port to which the device is connected.
• baudrate (int) – Baudrate of the UART device.
• timeout (time: ms) – How long to wait during read() before giving up. If you choose
None, it will wait forever.
read(length=1)
Reads a given number of bytes from the buffer.
Your program will wait until the requested number of bytes are received. If this takes longer than
timeout, the ETIMEDOUT exception is raised.
Parameters length (int) – How many bytes to read.
Returns Bytes returned from the device.
Return type bytes
read_all()
Reads all bytes from the buffer.
Returns Bytes returned from the device.
Return type bytes
write(data)
Writes bytes.
Parameters data (bytes) – Bytes to be written.
waiting()
Gets how many bytes are still waiting to be read.
Returns Number of bytes in the buffer.

190
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Return type int


clear()
Empties the buffer.
Show/hide example
Example: Read and write to a UART device.

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import UARTDevice
from pybricks.parameters import Port
from pybricks.media.ev3dev import SoundFile

# Initialize the EV3


ev3 = EV3Brick()

# Initialize sensor port 2 as a uart device


ser = UARTDevice(Port.S2, baudrate=115200)

# Write some data


ser.write(b'\r\nHello, world!\r\n')

# Play a sound while we wait for some data


for i in range(3):
ev3.speaker.play_file(SoundFile.HELLO)
ev3.speaker.play_file(SoundFile.GOOD)
ev3.speaker.play_file(SoundFile.MORNING)
print("Bytes waiting to be read:", ser.waiting())

# Read all data received while the sound was playing


data = ser.read_all()
print(data)

8.5 DC Motor

class DCMotor(port, positive_direction=Direction.CLOCKWISE)


Generic class to control simple motors without rotation sensors, such as train motors.
Parameters
• port (Port) – Port to which the motor is connected.

191
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• positive_direction (Direction) – Which direction the motor should turn when


you give a positive duty cycle value.
dc(duty)
Rotates the motor at a given duty cycle (also known as “power”).
Parameters duty (percentage: %) – The duty cycle (-100.0 to 100).
stop()
Stops the motor and lets it spin freely.
The motor gradually stops due to friction.

8.6 Ev3dev sensors

EV3 MicroPython is built on top of ev3dev, which means that a sensor may be supported even if it is not listed in this
documentation. If so, you can use it with the Ev3devSensor class. This is easier and faster than using the custom
device classes given above.
To check whether you can use the Ev3devSensor class:
• Plug the sensor into your EV3 Brick.
• Go to the main menu of the EV3 Brick.
• Select Device Browser and then Sensors.
• If your sensor shows up, you can use it.
Now select your sensor from the menu and choose set mode. This shows all available modes for this sensor. You can
use these mode names as the mode setting below.
To learn more about compatible devices and what each mode does, visit the ev3dev sensors page.
class Ev3devSensor(port)
Read values of an ev3dev-compatible sensor.
Parameters port (Port) – Port to which the device is connected.
sensor_index
Index of the ev3dev sysfs lego-sensor class.
port_index
Index of the ev3dev sysfs lego-port class.
read(mode)
Reads values at a given mode.
Parameters mode (str) – Mode name.
Returns Values read from the sensor.
Return type tuple

192
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Show/hide example: Reading values with the Ev3devSensor class


Example
In this example we use the LEGO MINDSTORMS EV3 Color Sensor with the raw RGB mode. This gives uncalibrated
red, green, and blue reflection values.

#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.iodevices import Ev3devSensor

# Initialize an Ev3devSensor.
# In this example we use the
# LEGO MINDSTORMS EV3 Color Sensor.
sensor = Ev3devSensor(Port.S3)

while True:
# Read the raw RGB values
r, g, b = sensor.read('RGB-RAW')

# Print results
print('R: {0}\t G: {1}\t B: {2}'.format(r, g, b))

# Wait
wait(200)

Show/hide example: Extending the Ev3devSensor class


Example
This example shows how to extend the Ev3devSensor class by accessing additional features found in the Linux
system folder for this device.

#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.iodevices import Ev3devSensor

class MySensor(Ev3devSensor):
"""Example of extending the Ev3devSensor class."""

def __init__(self, port):


"""Initialize the sensor."""

# Initialize the parent class.


super().__init__(port)

# Get the sysfs path.


self.path = '/sys/class/lego-sensor/sensor' + str(self.sensor_index)

def get_modes(self):
"""Get a list of mode strings so we don't have to look them up."""

# The path of the modes file.


modes_path = self.path + '/modes'

# Open the modes file.


with open(modes_path, 'r') as m:
(continues on next page)

193
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# Read the contents.


contents = m.read()

# Strip the newline symbol, and split at every space symbol.


return contents.strip().split(' ')

# Initialize the sensor


sensor = MySensor(Port.S3)

# Show where this sensor can be found


print(sensor.path)

# Print the available modes


modes = sensor.get_modes()
print(modes)

# Read mode 0 of this sensor


val = sensor.read(modes[0])
print(val)

194
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 9

parameters – Parameters and Constants

Constant parameters/arguments for the Pybricks API.


class Port
Port on the programmable brick or hub.
Powered Up
Input/Output ports:
A
B
C
D
E
F
EV3
Motor ports:
A
B
C
D
Sensor ports:
S1
S2
S3
S4

195
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

class Direction
Rotational direction for positive speed or angle values.
CLOCKWISE
A positive speed value should make the motor move clockwise.
COUNTERCLOCKWISE
A positive speed value should make the motor move counterclockwise.

positive_direction = Positive speed: Negative speed:


Direction.CLOCKWISE clockwise counterclockwise
Direction.COUNTERCLOCKWISE counterclockwise clockwise

In general, clockwise is defined by looking at the motor shaft, just like looking at a clock.
Some motors have two shafts. If in doubt, refer to the following diagrams:
• Clockwise direction for EV3/NXT motors
• Clockwise direction for Powered Up Motors
• Clockwise direction for Move Hub Motors
class Stop
Action after the motor stops: coast, brake, or hold.
COAST
Let the motor move freely.
BRAKE
Passively resist small external forces.
HOLD
Keep controlling the motor to hold it at the commanded angle. This is only available on motors with
encoders.
The following table show how each stop type adds an extra level of resistance to motion. In these examples, m
is a Motor and and d is a DriveBase. The examples also show how running at zero speed compares to these
stop types.

196
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Type Friction Back Speed Angle kept Examples


EMF kept at 0 at target

Coast

m.stop()
m.
run_target(500,
90,
Stop.
COAST)

Brake
• •
m.brake()
m.
run_target(500,
90,
Stop.
BRAKE)

• • •
m.run(0)
d.drive(0,
0)

Hold
• • • •
m.hold()
m.
run_target(500,
90,
Stop.HOLD)
d.
straight(0)
d.
straight(100)

class Color(h, s=100, v=100, name=None)


Light or surface color.

Saturated colors

RED = Color(0, 100, 100, 'RED')

ORANGE = Color(30, 100, 100, 'ORANGE')

YELLOW = Color(60, 100, 100, 'YELLOW')

197
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

GREEN = Color(120, 100, 100, 'GREEN')

CYAN = Color(180, 100, 100, 'CYAN')

BLUE = Color(240, 100, 100, 'BLUE')

VIOLET = Color(270, 100, 100, 'VIOLET')

MAGENTA = Color(300, 100, 100, 'MAGENTA')

Unsaturated colors

BLACK = Color(0, 0, 0, 'BLACK')

GRAY = Color(0, 0, 50, 'GRAY')

WHITE = Color(0, 0, 100, 'WHITE')

class Button
Buttons on a brick or remote:
LEFT_DOWN
DOWN
RIGHT_DOWN
LEFT
CENTER
RIGHT
LEFT_UP
UP
BEACON
RIGHT_UP

LEFT_UP UP/BEACON RIGHT_UP


LEFT CENTER RIGHT
LEFT_DOWN DOWN RIGHT_DOWN

class Side
Side of a hub or a sensor. These devices are mostly rectangular boxes with six sides:
TOP
BOTTOM
FRONT

198
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

BACK
LEFT
RIGHT
Screens or light matrices have only four sides. For those, TOP is treated the same as FRONT, and BOTTOM is
treated the same as BACK.
Click a tab below to see the sides for relevant devices.
Prime Hub

Inventor Hub

Move Hub
Technic Hub
Tilt Sensor

199
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

200
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 10

tools – Timing and Data logging

Common tools for timing and data logging.


wait(time)
Pauses the user program for a specified amount of time.
Parameters time (time: ms) – How long to wait.
class StopWatch
A stopwatch to measure time intervals. Similar to the stopwatch feature on your phone.
time()
Gets the current time of the stopwatch.
Returns Elapsed time.
Return type time: ms
pause()
Pauses the stopwatch.
resume()
Resumes the stopwatch.
reset()
Resets the stopwatch time to 0.
The run state is unaffected:
• If it was paused, it stays paused (but now at 0).
• If it was running, it stays running (but starting again from 0).
class DataLog(*headers, name=’log’, timestamp=True, extension=’csv’, append=False)
Create a file and log data.
Parameters
• headers (col1, col2, . . . ) – Column headers. These are the names of the data columns.
For example, choose 'time' and 'angle'.

201
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• name (str) – Name of the file.


• timestamp (bool) – Choose True to add the date and time to the file name. This way,
your file has a unique name. Choose False to omit the timestamp.
• extension (str) – File extension.
• append (bool) – Choose True to reopen an existing data log file and append data to it.
Choose False to clear existing data. If the file does not exist yet, an empty file will be
created either way.
log(*values)
Saves one or more values on a new line in the file.
Parameters values (object, object, . . . ) – One or more objects or values.
By default, this class creates a csv file on the EV3 brick with the name log and the current date and time.
For example, if you use this class on 13 February 2020 on 10:07 and 44.431260 seconds, the file is called
log_2020_02_13_10_07_44_431260.csv.
See managing files on the EV3 to learn how to upload the log file back to your computer.
Show/hide example: Logging and visualizing measurements
Example
This example shows how to log the angle of a rotating wheel as time passes.

#!/usr/bin/env pybricks-micropython
from pybricks.ev3devices import Motor
from pybricks.parameters import Port
from pybricks.tools import DataLog, StopWatch, wait

# Create a data log file in the project folder on the EV3 Brick.
# * By default, the file name contains the current date and time, for example:
# log_2020_02_13_10_07_44_431260.csv
# * You can optionally specify the titles of your data columns. For example,
# if you want to record the motor angles at a given time, you could do:
data = DataLog('time', 'angle')

# Initialize a motor and make it move


wheel = Motor(Port.B)
wheel.run(500)

# Start a stopwatch to measure elapsed time


watch = StopWatch()

# Log the time and the motor angle 10 times


for i in range(10):
# Read angle and time
angle = wheel.angle()
time = watch.time()

# Each time you use the log() method, a new line with data is added to
# the file. You can add as many values as you like.
# In this example, we save the current time and motor angle:
data.log(time, angle)

# Wait some time so the motor can move a bit


wait(100)
(continues on next page)

202
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)

# You can now upload your file to your computer

In this example, the generated file has the following contents:


time, angle
3, 0
108, 6
212, 30
316, 71
419, 124
523, 176
628, 228
734, 281
838, 333
942, 385

When you upload the file to your computer as shown above, you can open it in a spreadsheet editor. You can then
generate a graph of the data, as shown in Figure 10.1.
In this example, we see that the motor angle changes slowly at first. Then the angle begins to change faster, and the
graph becomes a straight line. This means that the motor has reached a constant speed. You can verify that the angle
increases by 500 degrees per second.

Figure 10.1: Original file contents (left) and a generated graph (right).

Show/hide example: Using the optional arguments


Example
This example shows how to log data beyond just numbers. It also shows how you can use the optional arguments of
the DataLog class to choose the file name and extension.
In this example, timestamp=False, which means that the date and time are not added to the file name. This can be
convenient because the file name will always be the same. However, this means that the contents of my_file.txt
will be overwritten every time you run this script.

203
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Color
from pybricks.tools import DataLog

# Create a data log file called my_file.txt


data = DataLog('time', 'angle', name='my_file', timestamp=False, extension='txt')

# The log method uses the print() method to add a line of text.
# So, you can do much more than saving numbers. For example:
data.log('Temperature', 25)
data.log('Sunday', 'Monday', 'Tuesday')
data.log({'Kiwi': Color.GREEN}, {'Banana': Color.YELLOW})

# You can upload the file to your computer, but you can also print the data:
print(data)

204
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 11

robotics – Robotics

Robotics module for the Pybricks API.


class DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
A robotic vehicle with two powered wheels and an optional support wheel or caster.
By specifying the dimensions of your robot, this class makes it easy to drive a given distance in millimeters or
turn by a given number of degrees.
Positive distances and drive speeds mean driving forward. Negative means backward.
Positive angles and turn rates mean turning right. Negative means left. So when viewed from the top, positive
means clockwise and negative means counterclockwise.
Parameters
• left_motor (Motor) – The motor that drives the left wheel.
• right_motor (Motor) – The motor that drives the right wheel.
• wheel_diameter (dimension: mm) – Diameter of the wheels.
• axle_track (dimension: mm) – Distance between the points where both wheels touch
the ground.

Driving for a given distance or by an angle

Use the following commands to drive a given distance, or turn by a given angle.
This is measured using the internal rotation sensors. Because wheels may slip while moving, the traveled
distance and angle are only estimates.
straight(distance)
Drives straight for a given distance and then stops.
Parameters distance (distance: mm) – Distance to travel.
turn(angle)
Turns in place by a given angle and then stops.

205
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Parameters angle (angle: deg) – Angle of the turn.


settings(straight_speed, straight_acceleration, turn_rate, turn_acceleration)
Configures the speed and acceleration used by straight() and turn().
If you give no arguments, this returns the current values as a tuple.
You can only change the settings while the robot is stopped. This is either before you begin driving or after
you call stop().
Parameters
• straight_speed (speed: mm/s) – Speed of the robot during straight().
• straight_acceleration (linear acceleration: mm/s/s) – Acceleration and deceler-
ation of the robot at the start and end of straight().
• turn_rate (rotational speed: deg/s) – Turn rate of the robot during turn().
• turn_acceleration (rotational acceleration: deg/s/s) – Angular acceleration and
deceleration of the robot at the start and end of turn().

Drive forever

Use drive() to begin driving at a desired speed and steering.


It keeps going until you use stop() or change course by using drive() again. For example, you can drive
until a sensor is triggered and then stop or turn around.
drive(speed, turn_rate)
Starts driving at the specified speed and turn rate. Both values are measured at the center point between
the wheels of the robot.
Parameters
• speed (speed: mm/s) – Speed of the robot.
• turn_rate (rotational speed: deg/s) – Turn rate of the robot.
stop()
Stops the robot by letting the motors spin freely.

Measuring

distance()
Gets the estimated driven distance.
Returns Driven distance since last reset.
Return type distance: mm
angle()
Gets the estimated rotation angle of the drive base.
Returns Accumulated angle since last reset.
Return type angle: deg
state()
Gets the state of the robot.
This returns the current distance(), the drive speed, the angle(), and the turn rate.

206
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns Distance, drive speed, angle, turn rate


Return type (distance: mm, speed: mm/s, angle: deg, rotational speed: deg/s)
reset()
Resets the estimated driven distance and angle to 0.

Measuring and validating the robot dimensions

As a first estimate, you can measure the wheel_diameter and the axle_track with a ruler. Because it is
hard to see where the wheels effectively touch the ground, you can estimate the axle_track as the distance
between the midpoint of the wheels.
In practice, most wheels compress slightly under the weight of your robot. To verify, make your robot drive 1000
mm using my_robot.straight(1000) and measure how far it really traveled. Compensate as follows:
• If your robot drives not far enough, decrease the wheel_diameter value slightly.
• If your robot drives too far, increase the wheel_diameter value slightly.
Motor shafts and axles bend slightly under the load of the robot, causing the ground contact point of the wheels
to be closer to the midpoint of your robot. To verify, make your robot turn 360 degrees using my_robot.
turn(360) and check that it is back in the same place:
• If your robot turns not far enough, increase the axle_track value slightly.
• If your robot turns too far, decrease the axle_track value slightly.
When making these adjustments, always adjust the wheel_diameter first, as done above. Be sure to test
both turning and driving straight after you are done.

Using the DriveBase motors individually

Suppose you make a DriveBase object using two Motor objects called left_motor and right_motor.
You cannot use these motors individually while the DriveBase is active.
The DriveBase is active if it is driving, but also when it is actively holding the wheels in place after a
straight() or turn() command. To deactivate the DriveBase, call stop().

Advanced Settings

The settings() method is used to adjust commonly used settings like the default speed and acceleration for
straight maneuvers and turns. Use the following attributes to adjust more advanced control setttings.
You can only change the settings while the robot is stopped. This is either before you begin driving or after you
call stop().
distance_control
The traveled distance and drive speed are controlled by a PID controller. You can use this attribute to
change its settings. See The Control Class for an overview of available methods.
heading_control
The robot turn angle and turn rate are controlled by a PID controller. You can use this attribute to change
its settings. See The Control Class for an overview of available methods.

207
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 12

media – Sounds and Images

This module describes media such as sound and images that you can use in your projects. Media are divided into
submodules that indicate on which platform they are available.

12.1 media.ev3dev – Sounds and Images

EV3 MicroPython is built on top of ev3dev, which comes with a variety of image and sound files. You can access
them using the classes below.
You can also use your own sound and image files by placing them in your project folder.

12.1.1 Image Files

class ImageFile
Paths to standard EV3 images.
Information
ACCEPT

BACKWARD

208
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

DECLINE

FORWARD

LEFT

NO_GO

QUESTION_MARK

RIGHT

STOP_1

STOP_2

THUMBS_DOWN

THUMBS_UP

209
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

WARNING

LEGO
EV3

EV3_ICON

Objects
TARGET

Eyes
ANGRY

AWAKE

BOTTOM_LEFT

BOTTOM_RIGHT

210
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

CRAZY_1

CRAZY_2

DIZZY

DOWN

EVIL

KNOCKED_OUT

MIDDLE_LEFT

MIDDLE_RIGHT

NEUTRAL

PINCHED_LEFT

211
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

PINCHED_MIDDLE

PINCHED_RIGHT

SLEEPING

TIRED_LEFT

TIRED_MIDDLE

TIRED_RIGHT

UP

WINKING

212
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

12.1.2 Sound Files

class SoundFile
Paths to standard EV3 sounds.
Expressions
BOING

Download
BOO

Download
CHEERING

Download
CRUNCHING

Download
CRYING

Download
FANFARE

Download
KUNG_FU

Download
LAUGHING_1

Download
LAUGHING_2

Download
MAGIC_WAND

Download
OUCH

Download
SHOUTING

Download

213
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

SMACK

Download
SNEEZING

Download
SNORING

Download
UH_OH

Download
Information
ACTIVATE

Download
ANALYZE

Download
BACKWARDS

Download
COLOR

Download
DETECTED

Download
DOWN

Download
ERROR

Download
ERROR_ALARM

Download
FLASHING

Download

214
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

FORWARD

Download
LEFT

Download
OBJECT

Download
RIGHT

Download
SEARCHING

Download
START

Download
STOP

Download
TOUCH

Download
TURN

Download
UP

Download
Communication
BRAVO

Download
EV3

Download
FANTASTIC

Download

215
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

GAME_OVER

Download
GO

Download
GOOD_JOB

Download
GOOD

Download
GOODBYE

Download
HELLO

Download
HI

Download
LEGO

Download
MINDSTORMS

Download
MORNING

Download
NO

Download
OKAY

Download
OKEY_DOKEY

Download

216
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

SORRY

Download
THANK_YOU

Download
YES

Download
Movement sounds
SPEED_DOWN

Download
SPEED_IDLE

Download
SPEED_UP

Download
Colors
BLACK

Download
BLUE

Download
BROWN

Download
GREEN

Download
RED

Download
WHITE

Download
YELLOW

217
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Download
Mechanical
AIR_RELEASE

Download
AIRBRAKE

Download
BACKING_ALERT

Download
HORN_1

Download
HORN_2

Download
LASER

Download
MOTOR_IDLE

Download
MOTOR_START

Download
MOTOR_STOP

Download
RATCHET

Download
SONAR

Download
TICK_TACK

Download
Animal sounds

218
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

CAT_PURR

Download
DOG_BARK_1

Download
DOG_BARK_2

Download
DOG_GROWL

Download
DOG_SNIFF

Download
DOG_WHINE

Download
ELEPHANT_CALL

Download
INSECT_BUZZ_1

Download
INSECT_BUZZ_2

Download
INSECT_CHIRP

Download
SNAKE_HISS

Download
SNAKE_RATTLE

Download
T_REX_ROAR

Download
Numbers

219
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ZERO

Download
ONE

Download
TWO

Download
THREE

Download
FOUR

Download
FIVE

Download
SIX

Download
SEVEN

Download
EIGHT

Download
NINE

Download
TEN

Download
System sounds
CLICK

Download
CONFIRM

Download

220
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

GENERAL_ALERT

Download
OVERPOWER

Download
READY

Download

12.1.3 Fonts

class Font(family=None, size=12, bold=False, monospace=False, lang=None, script=None)


Object that represents a font for writing text.
The font object will be a font that is the “best” match based on the parameters given and available fonts installed.
Parameters
• family (str) – The preferred font family or None to use the default value.
• size (int) – The preferred font size. Most fonts have sizes between 6 and 24. This is the
“point” size and not the same as height.
• bold (bool) – When True, prefer bold fonts.
• monospace (bool) – When True prefer monospaced fonts. This is useful for aligning
multiple rows of text.
• lang (str) – A language code, such as 'en' or 'zh-cn' or None to use the default
language.1
1

Language codes
Note: Languages depend on installed fonts. Additional language codes are possible and some listed language codes may not have a satisfactory
font.
– 'aa': Afar
– 'af': Afrikaans
– 'an': Aragonese
– 'av': Avaric
– 'ay': Aymara
– 'az-az': Azerbaijani
– 'be': Belarusian
– 'bg': Bulgarian
– 'bi': Bislama
– 'bm': Bambara
– 'br': Breton
– 'bs': Bosnian
– 'bua': Buriat
– 'ca': Catalan
– 'ce': Chechen

221
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• script (str) – A unicode script identifier such as 'Runr' or None.


DEFAULT = Font('Lucida', 12)
The default font.
family
Gets the family name of the font.
– 'ch': Chamorro
– 'co': Corsican
– 'crh': Crimean
– 'cs': Czech
– 'csb': Kashubian
– 'cy': Welsh
– 'da': Danish
– 'de': German
– 'ee': Ewe
– 'el': Greek
– 'en': English
– 'eo': Esperanto
– 'es': Spanish
– 'et': Estonian
– 'eu': Basque
– 'ff': Fulah
– 'fi': Finnish
– 'fil': Filipino
– 'fj': Fijian
– 'fo': Faroese
– 'fr': French
– 'fur': Friulian
– 'fy': Western Frisian
– 'ga': Irish
– 'gd': Gaelic
– 'gl': Galician
– 'gv': Manx
– 'ha': Hausa
– 'haw': Hawaiian
– 'he': Hebrew
– 'ho': Hiri Motu
– 'hr': Croatian
– 'hsb': Upper Sorbian
– 'ht': Haitian
– 'hu': Hungarian
– 'ia': Interlingua
– 'id': Indonesian

222
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

style
Gets a string describing the font style.
Can be “Regular” or “Bold”.
width
Gets the width of the widest character of the font.
– 'ie': Interlingue
– 'ik': Inupiaq
– 'io': Ido
– 'is': Icelandic
– 'it': Italian
– 'ja': Japanese
– 'jv': Javanese
– 'ki': Kikuyu
– 'kj': Kuanyama
– 'kl': Kalaallisut
– 'ko': Korean
– 'ku-tr': Kurdish
– 'kum': Kumyk
– 'kw': Cornish
– 'kwm': Kwambi
– 'la': Latin
– 'lb': Luxembourgish
– 'lez': Lezghian
– 'lg': Ganda
– 'li': Limburgan
– 'ln': Lingala
– 'lt': Lithuanian
– 'lv': Latvian
– 'mg': Malagasy
– 'mh': Marshallese
– 'mi': Maori
– 'mk': Macedonian
– 'mn-mn': Mongolian
– 'mo': Moldavian
– 'ms': Malay
– 'mt': Maltese
– 'na': Nauru
– 'nb': Norwegian Bokmål
– 'nds': Low German
– 'ng': Ndonga
– 'nl': Dutch
– 'nn': Norwegian Nynorsk

223
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

height
Gets the height of the font.
text_width(text)
Gets the width of the text when the text is drawn using this font.
Parameters text (str) – The text.
– 'no': Norwegian
– 'nr': South Ndebele
– 'nso': Northern Sotho
– 'nv': Navajo
– 'ny': Chichewa
– 'oc': Occitan
– 'om': Oromo
– 'os': Ossetian
– 'pap-an': Papiamento, Netherlands Antilles
– 'pap-aw': Papiamento, Aruba
– 'pl': Polish
– 'pt': Portuguese
– 'qu': Quechua
– 'quz': Cusco Quechua
– 'rm': Romansh
– 'rn': Rundi
– 'ro': Romanian
– 'ru': Russian
– 'rw': Kinyarwanda
– 'sc': Sardinian
– 'sco': Scots
– 'se': Northern Sami
– 'sel': Selkup
– 'sg': Sango
– 'sk': Slovak
– 'sl': Slovenian
– 'sm': Samoan
– 'sma': Southern Sami
– 'smj': Lule Sami
– 'smn': Inari Sami
– 'sms': Skolt Sami
– 'sn': Shona
– 'so': Somali
– 'sq': Albanian
– 'sr': Serbian
– 'ss': Swati
– 'st': Southern Sotho

224
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Returns The width in pixels.


Return type int
text_height(text)
Gets the height of the text when the text is drawn using this font.
Parameters text (str) – The text.
Returns The height in pixels.
Return type int
Exploring more fonts
Behind the scenes, Pybricks uses Fontconfig for fonts. The Fontconfig command line tools can be used to
explore available fonts in more detail. To do so, go to the ev3dev device browser, right click on your EV3 brick,
and click Open SSH Terminal. Then you can enter one of these commands:

# List available font families.


fc-list :scalable=false family
# Perform lookup similar to Font.DEFAULT
fc-match :scalable=false:dpi=119:family=Lucida:size=12
(continues on next page)

– 'su': Sundanese
– 'sv': Swedish
– 'sw': Swahili
– 'tk': Turkmen
– 'tl': Tagalog
– 'tn': Tswana
– 'to': Tonga
– 'tr': Turkish
– 'ts': Tsonga
– 'ty': Tahitian
– 'uk': Ukrainian
– 'uz': Uzbek
– 'vo': Volapük
– 'vot': Votic
– 'wa': Walloon
– 'wen': Sorbian
– 'wo': Wolof
– 'xh': Xhosa
– 'yap': Yapese
– 'yi': Yiddish
– 'za': Zhuang
– 'zh-cn': Chinese, China
– 'zh-sg': Chinese, Singapore
– 'zh-tw': Chinese, Taiwan
– 'zu': Zulu

225
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

(continued from previous page)


# Perform lookup similar to Font(size=24,lang=zh-cn)
fc-match :scalable=false:dpi=119:size=24:lang=zh-cn

Pybricks only allows the use of bitmap fonts (scalable=false) and the screen on the EV3 has 119 pixels
per inch (dpi=119).

12.1.4 Image Manipulation

Instead of drawing directly on the EV3 screen, you can make and interact with image files using the Image class
given below.
class Image(source, sub=False)
Object representing a graphics image. This can either be an in-memory copy of an image or the image displayed
on a screen.
Parameters
• source (str or Image) – The source of the image.
If source is a string, then the image will be loaded from the file path given by the string.
Only .png files are supported. As a special case, if the string is _screen_, the image will
be configured to draw directly on the screen.
If an Image is given, the new object will contain a copy of the source image object.
• sub (bool) – If sub is True, then the image object will act as a sub-image of the source
image (this only works if the type of source is Image and not when it is a str).
Additional keyword arguments x1, y1, x2, y2 are needed when sub=True. These specify
the top-left and bottom-right coordinates in the source image that will be used as the
bounds for the sub-image.
static empty(width=<screen width>, height=<screen height>)
Creates a new empty Image object.
Parameters
• width (int) – The width of the image in pixels.
• height (int) – The height of the image in pixels.
Returns A new image with all pixels set to Color.WHITE.
Return type Image
Raises
• TypeError – width or height is not a number.
• ValueError – width or height is less than 1.
• RuntimeError – There was a problem allocating a new image.

Drawing text

There are two ways to draw text on images. draw_text() lets text be placed precisely on the image or
print() can be used to automatically print text on a new line.

226
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

draw_text(x, y, text, text_color=Color(0, 0, 0, ’BLACK’), background_color=None)


Draws text on this image.
The most recent font set using set_font() will be used or Font.DEFAULT if no font has been set yet.
Parameters
• x (int) – The x-axis value where the left side of the text will start.
• y (int) – The y-axis value where the top of the text will start.
• text (str) – The text to draw.
• text_color (Color) – The color used for drawing the text.
• background_color (Color) – The color used to fill the rectangle behind the text or
None for transparent background.
print(*args, sep=’ ’, end=’\n’)
Prints a line of text on this image.
This method works like the builtin print() function, but it writes on this image instead.
You can set the font using set_font(). If no font has been set, Font.DEFAULT will be used. The
text is always printed used black text with a white background.
Unlike the builtin print(), the text does not wrap if it is too wide to fit on this image. It just gets cut
off. But if the text would go off of the bottom of this image, the entire image is scrolled up and the text is
printed in the new blank area at the bottom of this image.
Parameters
• * (object) – Zero or more objects to print.
• sep (str) – Separator that will be placed between each object that is printed.
• end (str) – End of line that will be printed after the last object.
set_font(font)
Sets the font used for writing on this image.
The font is used for both draw_text() and print().
Parameters font (Font) – The font to use.

Drawing images

A copy of another image can be drawn on an image. Also consider using sub-images to copy part of an image.
draw_image(x, y, source, transparent=None)
Draws the source image on this image.
Parameters
• x (int) – The x-axis value where the left side of the image will start.
• y (int) – The y-axis value where the top of the image will start.
• source (Image or str) – The source Image. If the argument is a string, then the
source image is loaded from file.
• transparent (Color) – The color of image to treat as transparent or None for no
transparency.

227
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Drawing shapes

These are the methods to draw basic shapes, including points, lines, rectangles and circles.
draw_pixel(x, y, color=Color(0, 0, 0, ’BLACK’))
Draws a single pixel on this image.
Parameters
• x (int) – The x coordinate of the pixel.
• y (int) – The y coordinate of the pixel.
• color (Color) – The color of the pixel.
draw_line(x1, y1, x2, y2, width=1, color=Color(0, 0, 0, ’BLACK’))
Draws a line on this image.
Parameters
• x1 (int) – The x coordinate of the starting point of the line.
• y1 (int) – The y coordinate of the starting point of the line.
• x2 (int) – The x coordinate of the ending point of the line.
• y2 (int) – The y coordinate of the ending point of the line.
• width (int) – The width of the line in pixels.
• color (Color) – The color of the line.
draw_box(x1, y1, x2, y2, r=0, fill=False, color=Color(0, 0, 0, ’BLACK’))
Draws a box on this image.
Parameters
• x1 (int) – The x coordinate of the left side of the box.
• y1 (int) – The y coordinate of the top of the box.
• x2 (int) – The x coordinate of the right side of the box.
• y2 (int) – The y coordinate of the bottom of the box.
• r (int) – The radius of the corners of the box.
• fill (bool) – If True, the box will be filled with color, otherwise only the outline of
the box will be drawn.
• color (Color) – The color of the box.
draw_circle(x, y, r, fill=False, color=Color(0, 0, 0, ’BLACK’))
Draws a circle on this image.
Parameters
• x (int) – The x coordinate of the center of the circle.
• y (int) – The y coordinate of the center of the circle.
• r (int) – The radius of the circle.
• fill (bool) – If True, the circle will be filled with color, otherwise only the circum-
ference will be drawn.
• color (Color) – The color of the circle.

228
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Image properties

width
Gets the width of this image in pixels.
height
Gets the height of this image in pixels.

Replacing the entire image

clear()
Clears this image. All pixels on this image will be set to Color.WHITE.
load_image(source)
Clears this image, then draws the source image centered in this image.
Parameters source (Image or str) – The source Image. If the argument is a string, then
the source image is loaded from file.

Saving the image

save(filename)
Saves this image as a .png file.
Parameters filename (str) – The path to the file to be saved.
Raises
• TypeError – filename is not a string.
• OSError – There was a problem saving the file.

229
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 13

messaging – Messaging

An EV3 Brick can send information to another EV3 Brick using Bluetooth. This page shows you how to connect
multiple bricks and how to write scripts to send messages between them.

13.1 Pairing two EV3 Bricks

Before two EV3 bricks can exchange messages, they must be paired. You’ll need to do this only the first time. First,
activate bluetooth on all EV3 bricks as shown in Figure 13.1.

Figure 13.1: Turn on Bluetooth and make Bluetooth visible.

Now you can make one EV3 Brick search for the other and pair with it, as shown in Figure 13.2.
Once they are paired, do not click connect in the menu that appears. The connection will be made when you run your
programs, as described below.
When you scan for Bluetooth devices, you’ll see a list of device names. By default, all EV3 Bricks are named ev3dev.
Click here to learn how to change that name. This makes it easy to tell them apart.
Repeat the steps in Figure 13.2 if you want to pair more than two EV3 Bricks.

230
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

Figure 13.2: Pairing one EV3 Brick to another EV3 Brick.

13.2 Server and Client

A wireless network consists of EV3 Bricks acting as servers or clients. A example with one server and one client is
shown in Figure 13.3. Messages can be sent in both ways: the server can send a message to the client, and the client
can send a message to the server.

Figure 13.3: An example network with one server and one clients.

Show/hide full server example


Example: EV3 Bluetooth Server.
This is the full version of the excerpt shown in Figure 13.3.

231
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

#!/usr/bin/env pybricks-micropython

# Before running this program, make sure the client and server EV3 bricks are
# paired using Bluetooth, but do NOT connect them. The program will take care
# of establishing the connection.

# The server must be started before the client!

from pybricks.messaging import BluetoothMailboxServer, TextMailbox

server = BluetoothMailboxServer()
mbox = TextMailbox('greeting', server)

# The server must be started before the client!


print('waiting for connection...')
server.wait_for_connection()
print('connected!')

# In this program, the server waits for the client to send the first message
# and then sends a reply.
mbox.wait()
print(mbox.read())
mbox.send('hello to you!')

Show/hide full client example


Example: EV3 Bluetooth Client.
This is the full version of the excerpt shown in Figure 13.3.

#!/usr/bin/env pybricks-micropython

# Before running this program, make sure the client and server EV3 bricks are
# paired using Bluetooth, but do NOT connect them. The program will take care
# of establishing the connection.

# The server must be started before the client!

from pybricks.messaging import BluetoothMailboxClient, TextMailbox

# This is the name of the remote EV3 or PC we are connecting to.


SERVER = 'ev3dev'

client = BluetoothMailboxClient()
mbox = TextMailbox('greeting', client)

print('establishing connection...')
client.connect(SERVER)
print('connected!')

# In this program, the client sends the first message and then waits for the
# server to reply.
mbox.send('hello!')
mbox.wait()
print(mbox.read())

The only difference between the client and the server is which one initiates the connection at the beginning of the
program:

232
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• The server must always be started first. It uses the BluetoothMailboxServer class. Then it waits for
clients using the wait_for_connection method.
• The client uses the BluetoothMailboxClient class. It connects to the server using the connect method.
• After that, sending and receiving messages is done in the same way on both EV3 Bricks.
class BluetoothMailboxServer
Object that represents a Bluetooth connection from one or more remote EV3s.
The remote EV3s can either be running MicroPython or the standard EV3 firmware.
A “server” waits for a “client” to connect to it.
wait_for_connection(count=1)
Waits for a BluetoothMailboxClient on a remote device to connect.
Parameters count (int) – The number of remote connections to wait for.
Raises OSError – There was a problem establishing the connection.
close()
Closes all connections.
class BluetoothMailboxClient
Object that represents a Bluetooth connection to one or more remote EV3s.
The remote EV3s can either be running MicroPython or the standard EV3 firmware.
A “client” initiates a connection to a waiting “server”.
connect(brick)
Connects to an BluetoothMailboxServer on another device.
The remote device must be paired and waiting for a connection. See BluetoothMailboxServer.
wait_for_connection().
Parameters brick (str) – The name or Bluetooth address of the remote EV3 to connect to.
Raises OSError – There was a problem establishing the connection.
close()
Closes all connections.

13.3 Mailboxes

Mailboxes are used to send data to and from other EV3 Bricks.
A Mailbox has a name, similar to the “subject” of an email. If two EV3 Bricks have a Mailbox with the same name,
they can send messages between them. Each EV3 Brick can read its own Mailbox, and send messages to the Mailbox
on the other EV3 Brick.
Depending on the type of messages you would like to exchange (bytes, booleans, numbers, or text), you can choose
one of the Mailboxes below.
class Mailbox(name, connection, encode=None, decode=None)
Object that represents a mailbox containing data.
You can read data that is delivered by other EV3 bricks, or send data to other bricks that have the same mailbox.
By default, the mailbox reads and send only bytes. To send other data, you can provide an encode function
that encodes your Python object into bytes, and a decode function to convert bytes back to a Python object.
Parameters

233
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• name (str) – The name of this mailbox.


• connection – A connection object such as BluetoothMailboxClient.
• encode (callable) – Function that encodes a Python object to bytes.
• decode (callable) – Function that creates a new Python object from bytes.
read()
Gets the current value of the mailbox.
Returns The current value or None if the mailbox is empty.
send(value, brick=None)
Sends a value to this mailbox on connected devices.
Parameters
• value – The value that will be delivered to the mailbox.
• brick (str) – The name or Bluetooth address of the brick or None to to broadcast to
all connected devices.
Raises OSError – There is a problem with the connection.
wait()
Waits for the mailbox to be updated by remote device.
wait_new()
Waits for a new value to be delivered to the mailbox that is not equal to the current value in the mailbox.
Returns The new value.
class LogicMailbox(name, connection)
Object that represents a mailbox containing boolean data.
This works just like a regular Mailbox, but values must be True or False.
This is compatible with the “logic” mailbox type in EV3-G.
Parameters
• name (str) – The name of this mailbox.
• connection – A connection object such as BluetoothMailboxClient.
class NumericMailbox(name, connection)
Object that represents a mailbox containing numeric data.
This works just like a regular Mailbox, but values must be a number, such as 15 or 12.345
This is compatible with the “numeric” mailbox type in EV3-G.
Parameters
• name (str) – The name of this mailbox.
• connection – A connection object such as BluetoothMailboxClient.
class TextMailbox(name, connection)
Object that represents a mailbox containing text data.
This works just like a regular Mailbox, but data must be a string, such as 'hello!' or 'My name is
EV3'.
This is compatible with the “text” mailbox type in EV3-G.
Parameters

234
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

• name (str) – The name of this mailbox.


• connection – A connection object such as BluetoothMailboxClient.

13.4 Making bigger networks

The classes in this module are not limited to just two EV3 Bricks. for example, you can add more clients to your
network. An example with pseudo-code is shown in Figure 13.4.

Figure 13.4: An example network with one server and two clients.

235
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 14

geometry – Geometry and algebra

class Matrix(rows)
Mathematical representation of a matrix. It supports common operations such as matrix addition (+), subtraction
(-), and multiplication (*). A Matrix object is immutable.
Parameters rows (list) – List of rows. Each row is itself a list of numbers.
T
Returns a new Matrix that is the transpose of the original.
shape
Returns a tuple (m, n), where m is the number of rows and n is the number of columns.
vector(x, y, z=None)
Convenience function to create a Matrix with the shape (3, 1) or (2, 1).
Parameters
• x (float) – x-coordinate of the vector.
• y (float) – y-coordinate of the vector.
• z (float) – z-coordinate of the vector (optional).
Returns A matrix with the shape of a column vector.
Return type Matrix

236
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 15

Signals and Units

Many commands allow you to specify arguments in terms of well-known physical quantities. This page gives an
overview of each quantity and its unit.

15.1 Time

15.1.1 time: ms

All time and duration values are measured in milliseconds (ms).


For example, the duration of motion with run_time, and the duration of wait are specified in milliseconds.

15.2 Angles and angular motion

15.2.1 angle: deg

All angles are measured in degrees (deg). One full rotation corresponds to 360 degrees.
For example, the angle values of a Motor or the GyroSensor are expressed in degrees.

15.2.2 rotational speed: deg/s

Rotational speed, or angular velocity describes how fast something rotates, expressed as the number of degrees per
second (deg/s).
For example, the rotational speed values of a Motor or the GyroSensor are expressed in degrees per second.
While we recommend working with degrees per second in your programs, you can use the following table to convert
between commonly used units.

237
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

deg/s rpm
1 deg/s = 1 1/6=0.167
1 rpm = 6 1

15.2.3 rotational acceleration: deg/s/s

Rotational acceleration, or angular acceleration describes how fast the rotational speed changes. This is expressed
as the change of the number of degrees per second, during one second (deg/s/s). This is also commonly written as
𝑑𝑒𝑔/𝑠2 .
For example, you can adjust the rotational acceleration setting of a Motor to change how smoothly or how quickly it
reaches the constant speed set point.

15.3 Distance and linear motion

15.3.1 distance: mm

Distances are expressed in millimeters (mm) whenever possible.


For example, the distance value of the UltrasonicSensor is measured in millimeters.
While we recommend working with millimeters in your programs, you can use the following table to convert between
commonly used units.

mm cm inch
1 mm = 1 0.1 0.0394
1 cm = 10 1 0.394
1 inch = 25.4 2.54 1

15.3.2 dimension: mm

Dimensions are expressed in millimeters (mm), just like distances.


For example, the diameter of a wheel is measured in millimeters.

15.3.3 speed: mm/s

Linear speeds are expressed as millimeters per second (mm/s).


For example, the speed of a robotic vehicle is expressed in mm/s.

15.3.4 linear acceleration: mm/s/s

Linear acceleration describes how fast the speed changes. This is expressed as the change of the millimeters per
second, during one second (deg/s/s). This is also commonly written as 𝑚𝑚/𝑠2 .
For example, you can adjust the acceleration setting of a DriveBase to change how smoothly or how quickly it
reaches the constant speed set point.

238
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

15.4 Approximate and relative units

15.4.1 percentage: %

Some signals do not have specific units. They range from a minimum (0%) to a maximum (100%). Specifics type of
percentages are relative distances or brightness.
Another example is the sound volume, which ranges from 0% (silent) to 100% (loudest).

15.4.2 relative distance: %

Some distance measurements do not provide an accurate value with a specific unit, but they range from very close
(0%) to very far (100%). These are referred to as relative distances.
For example, the distance value of the InfraredSensor is a relative distance.

15.4.3 brightness: %

The perceived brightness of a light is expressed as a percentage. It is 0% when the light is off and 100% when the light
is fully on. When you choose 50%, this means that the light is perceived as approximately half as bright to the human
eye.

15.5 Force

15.5.1 force: N

Force values are expressed in newtons (N).


While we recommend working with newtons in your programs, you can use the following table to convert to and from
other units.

mN N lbf
1 mN = 1 0.001 2.248 · 10−4
1N= 1000 1 0.2248
1 lbf = 4448 4.448 1

15.6 Electricity

15.6.1 voltage: mV

Voltages are expressed in millivolt (mV).


For example, you can check the voltage of the battery.

15.6.2 current: mA

Electrical currents are expressed in milliampere (mA).


For example, you can check the current supplied by the battery.

239
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

15.6.3 energy: J

Stored energy or energy consumption can be expressed in Joules (J).

15.6.4 power: mW

Power is the rate at which energy is stored or consumed. It is expressed in milliwatt (mW).

15.7 Ambient environment

15.7.1 frequency: Hz

Sound frequencies are expressed in Hertz (Hz).


For example, you can choose the frequency of a beep to change the pitch.

15.7.2 temperature: °C

Temperature is measured in degrees Celcius (°C). To convert to degrees Fahrenheit (°F) or Kelvin (K), you can use the
following conversion formulas:
9
𝐹 =𝐶 · 5 + 32.
𝐾 = 𝐶 + 273.15.

15.7.3 hue: deg

Hue of a color (0-359 degrees).


TODO: diagram

240
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
CHAPTER 16

More about Motors

16.1 The Control Class

The Motor class uses PID control to accurately track your commanded target angles. Similarly, the DriveBase
class uses two of such controllers: one to control the heading and one to control the traveled distance.
You can change the control settings through the following attributes, which are instances of the Control class given
below.:
• Motor.control
• DriveBase.heading_control
• DriveBase.distance_control
You can only change the settings while the controller is stopped. For example, you can set the settings at the beginning
of your program. Alternatively, first call stop() to make your Motor or DriveBase stop, and then change the
settings.
class Control
Class to interact with PID controller and settings.
scale
Scaling factor between the controlled integer variable and the physical output. For example, for a single
motor this is the number of encoder pulses per degree of rotation.

Status

done()
Checks if an ongoing command or maneuver is done.
Returns True if the command is done, False if not.
Return type bool

241
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

stalled()
Checks if the controller is currently stalled.
A controller is stalled when it cannot reach the target speed or position, even with the maximum actuation
signal.
Returns True if the controller is stalled, False if not.
Return type bool

Settings

limits(speed, acceleration, actuation)


Configures the maximum speed, acceleration, and actuation.
If no arguments are given, this will return the current values.
Parameters
• speed (rotational speed: deg/s or speed: mm/s) – Maximum speed. All speed commands
will be capped to this value.
• acceleration (rotational acceleration: deg/s/s or linear acceleration: mm/s/s) – Max-
imum acceleration.
• actuation (percentage: %) – Maximum actuation as percentage of absolute maximum.
pid(kp, ki, kd, integral_range, integral_rate, feed_forward)
Gets or sets the PID values for position and speed control.
If no arguments are given, this will return the current values.
Parameters
• kp (int) – Proportional position (or integral speed) control constant.
• ki (int) – Integral position control constant.
• kd (int) – Derivative position (or proportional speed) control constant.
• integral_range (angle: deg or distance: mm) – Region around the target angle or
distance, in which integral control errors are accumulated.
• integral_rate (rotational speed: deg/s or speed: mm/s) – Maximum rate at which
the error integral is allowed to grow.
• feed_forward (percentage: %) – This adds a feed forward signal to the PID feedback
signal, in the direction of the speed reference. This value is expressed as a percentage of
the absolute maximum duty cycle.
target_tolerances(speed, position)
Gets or sets the tolerances that say when a maneuver is done.
If no arguments are given, this will return the current values.
Parameters
• speed (rotational speed: deg/s or speed: mm/s) – Allowed deviation from zero speed
before motion is considered complete.
• position (angle: deg or distance: mm) – Allowed deviation from the target before
motion is considered complete.

242
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

stall_tolerances(speed, time)
Gets or sets stalling tolerances.
If no arguments are given, this will return the current values.
Parameters
• speed (rotational speed: deg/s or speed: mm/s) – If the controller cannot reach this speed
for some time even with maximum actuation, it is stalled.
• time (time: ms) – How long the controller has to be below this minimum speed before
we say it is stalled.

243
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Python Module Index

p
pybricks.ev3devices, 173
pybricks.geometry, 236
pybricks.hubs, 24
pybricks.iodevices, 186
pybricks.media, 208
pybricks.media.ev3dev, 208
pybricks.messaging, 230
pybricks.nxtdevices, 180
pybricks.parameters, 195
pybricks.pupdevices, 61
pybricks.robotics, 205
pybricks.tools, 201

244
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Index

A brake() (Motor method), 66, 174


active() (AnalogSensor method), 187 Button (class in pybricks.parameters), 198
ambient() (ColorDistanceSensor method), 81 Button.BEACON (in module pybricks.parameters), 198
ambient() (ColorSensor method), 114, 176, 181 Button.CENTER (in module pybricks.parameters), 198
ambient() (LightSensor method), 181 Button.DOWN (in module pybricks.parameters), 198
AnalogSensor (class in pybricks.iodevices), 187 Button.LEFT (in module pybricks.parameters), 198
angle() (DriveBase method), 206 Button.LEFT_DOWN (in module pybricks.parameters),
angle() (GyroSensor method), 179 198
angle() (Motor method), 65, 174 Button.LEFT_UP (in module pybricks.parameters), 198
animate() (pybricks.hubs.CityHub.light class method), 29 Button.RIGHT (in module pybricks.parameters), 198
animate() (pybricks.hubs.InventorHub.display class Button.RIGHT_DOWN (in module pybricks.parameters),
method), 47 198
animate() (pybricks.hubs.InventorHub.light class Button.RIGHT_UP (in module pybricks.parameters), 198
method), 43 Button.UP (in module pybricks.parameters), 198
animate() (pybricks.hubs.MoveHub.light class method), buttons() (InfraredSensor method), 177
26
animate() (pybricks.hubs.PrimeHub.display class
C
method), 39 char() (pybricks.hubs.InventorHub.display class method),
animate() (pybricks.hubs.PrimeHub.light class method), 48
35 char() (pybricks.hubs.PrimeHub.display class method),
animate() (pybricks.hubs.TechnicHub.light class 39
method), 32 CityHub (class in pybricks.hubs), 27
clear() (EV3Brick.screen method), 54
B clear() (Image method), 229
beacon() (InfraredSensor method), 177 clear() (UARTDevice method), 191
beep() (EV3Brick.speaker method), 51 close() (BluetoothMailboxClient method), 233
BLACK (Color attribute), 198 close() (BluetoothMailboxServer method), 233
blink() (pybricks.hubs.CityHub.light class method), 29 Color (class in pybricks.parameters), 197
blink() (pybricks.hubs.InventorHub.light class method), color() (ColorDistanceSensor method), 80
43 color() (ColorSensor method), 113, 176, 181
blink() (pybricks.hubs.MoveHub.light class method), 26 ColorDistanceSensor (class in pybricks.pupdevices), 80
blink() (pybricks.hubs.PrimeHub.light class method), 34 ColorSensor (class in pybricks.ev3devices), 176
blink() (pybricks.hubs.TechnicHub.light class method), ColorSensor (class in pybricks.nxtdevices), 181
31 ColorSensor (class in pybricks.pupdevices), 112
BLUE (Color attribute), 198 connect() (BluetoothMailboxClient method), 233
BluetoothMailboxClient (class in pybricks.messaging), Control (class in pybricks._common), 241
233 control (Motor attribute), 175
BluetoothMailboxServer (class in pybricks.messaging), Control.scale (in module pybricks._common), 241
233 conversion() (VernierAdapter method), 184
count() (InfraredSensor method), 163

245
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

current() (pybricks.hubs.CityHub.battery class method), F


29 family (Font attribute), 222
current() (pybricks.hubs.EV3Brick.battery class method), Font (class in pybricks.media.ev3dev), 221
58 force() (ForceSensor method), 155
current() (pybricks.hubs.InventorHub.battery class ForceSensor (class in pybricks.pupdevices), 155
method), 49
current() (pybricks.hubs.MoveHub.battery class method), G
26
GRAY (Color attribute), 198
current() (pybricks.hubs.PrimeHub.battery class method),
GREEN (Color attribute), 198
41
GyroSensor (class in pybricks.ev3devices), 178
current() (pybricks.hubs.TechnicHub.battery class
method), 32
CYAN (Color attribute), 198
H
heading_control (DriveBase attribute), 207
D height (EV3Brick.screen attribute), 58
height (Font attribute), 223
DataLog (class in pybricks.tools), 201
height (Image attribute), 229
dc() (Motor method), 70, 175
hold() (Motor method), 66, 174
DEFAULT (Font attribute), 222
hsv() (ColorDistanceSensor method), 91
detectable_colors() (ColorDistanceSensor method), 92
hsv() (ColorSensor method), 127
detectable_colors() (ColorSensor method), 129
Direction (class in pybricks.parameters), 195
Direction.CLOCKWISE (in module py-
I
bricks.parameters), 196 I2CDevice (class in pybricks.iodevices), 188
Direction.COUNTERCLOCKWISE (in module py- Image (class in pybricks.media.ev3dev), 226
bricks.parameters), 196 image() (pybricks.hubs.InventorHub.display class
distance() (ColorDistanceSensor method), 82 method), 47
distance() (DriveBase method), 206 image() (pybricks.hubs.PrimeHub.display class method),
distance() (ForceSensor method), 155 39
distance() (InfraredSensor method), 161, 177 ImageFile (class in pybricks.media.ev3dev), 208
distance() (UltrasonicSensor method), 142, 178, 182 ImageFile.ACCEPT (in module pybricks.media.ev3dev),
distance_control (DriveBase attribute), 207 208
done() (Control method), 241 ImageFile.ANGRY (in module pybricks.media.ev3dev),
draw_box() (EV3Brick.screen method), 57 210
draw_box() (Image method), 228 ImageFile.AWAKE (in module pybricks.media.ev3dev),
draw_circle() (EV3Brick.screen method), 58 210
draw_circle() (Image method), 228 ImageFile.BACKWARD (in module py-
draw_image() (EV3Brick.screen method), 56 bricks.media.ev3dev), 208
draw_image() (Image method), 227 ImageFile.BOTTOM_LEFT (in module py-
draw_line() (EV3Brick.screen method), 57 bricks.media.ev3dev), 210
draw_line() (Image method), 228 ImageFile.BOTTOM_RIGHT (in module py-
draw_pixel() (EV3Brick.screen method), 56 bricks.media.ev3dev), 210
draw_pixel() (Image method), 228 ImageFile.CRAZY_1 (in module py-
draw_text() (EV3Brick.screen method), 54 bricks.media.ev3dev), 210
draw_text() (Image method), 226 ImageFile.CRAZY_2 (in module py-
drive() (DriveBase method), 206 bricks.media.ev3dev), 211
DriveBase (class in pybricks.robotics), 205 ImageFile.DECLINE (in module py-
bricks.media.ev3dev), 208
E ImageFile.DIZZY (in module pybricks.media.ev3dev),
211
empty() (Image static method), 226
ImageFile.DOWN (in module pybricks.media.ev3dev),
EnergyMeter (class in pybricks.nxtdevices), 183
211
EV3Brick (class in pybricks.hubs), 49
ImageFile.EV3 (in module pybricks.media.ev3dev), 210
Ev3devSensor (class in pybricks.iodevices), 192
ImageFile.EV3_ICON (in module py-
bricks.media.ev3dev), 210

246
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

ImageFile.EVIL (in module pybricks.media.ev3dev), 211 K


ImageFile.FORWARD (in module py- keypad() (InfraredSensor method), 178
bricks.media.ev3dev), 209
ImageFile.KNOCKED_OUT (in module py- L
bricks.media.ev3dev), 211
Light (class in pybricks.pupdevices), 171
ImageFile.LEFT (in module pybricks.media.ev3dev), 209
LightSensor (class in pybricks.nxtdevices), 181
ImageFile.MIDDLE_LEFT (in module py-
limits() (Control method), 242
bricks.media.ev3dev), 211
load_image() (EV3Brick.screen method), 56
ImageFile.MIDDLE_RIGHT (in module py-
load_image() (Image method), 229
bricks.media.ev3dev), 211
log() (DataLog method), 202
ImageFile.NEUTRAL (in module py-
LogicMailbox (class in pybricks.messaging), 234
bricks.media.ev3dev), 211
LUMPDevice (class in pybricks.iodevices), 186
ImageFile.NO_GO (in module pybricks.media.ev3dev),
209 M
ImageFile.PINCHED_LEFT (in module py-
bricks.media.ev3dev), 211 MAGENTA (Color attribute), 198
ImageFile.PINCHED_MIDDLE (in module py- Mailbox (class in pybricks.messaging), 233
bricks.media.ev3dev), 212 Matrix (class in pybricks.geometry), 236
ImageFile.PINCHED_RIGHT (in module py- Motor (class in pybricks.ev3devices), 173
bricks.media.ev3dev), 212 MoveHub (class in pybricks.hubs), 24
ImageFile.QUESTION_MARK (in module py-
bricks.media.ev3dev), 209 N
ImageFile.RIGHT (in module pybricks.media.ev3dev), number() (pybricks.hubs.InventorHub.display class
209 method), 48
ImageFile.SLEEPING (in module py- number() (pybricks.hubs.PrimeHub.display class
bricks.media.ev3dev), 212 method), 39
ImageFile.STOP_1 (in module pybricks.media.ev3dev), NumericMailbox (class in pybricks.messaging), 234
209
ImageFile.STOP_2 (in module pybricks.media.ev3dev), O
209 off() (Light method), 172
ImageFile.TARGET (in module pybricks.media.ev3dev), off() (pybricks.hubs.CityHub.light class method), 29
210 off() (pybricks.hubs.EV3Brick.light class method), 50
ImageFile.THUMBS_DOWN (in module py- off() (pybricks.hubs.InventorHub.display class method),
bricks.media.ev3dev), 209 47
ImageFile.THUMBS_UP (in module py- off() (pybricks.hubs.InventorHub.light class method), 43
bricks.media.ev3dev), 209 off() (pybricks.hubs.MoveHub.light class method), 26
ImageFile.TIRED_LEFT (in module py- off() (pybricks.hubs.PrimeHub.display class method), 38
bricks.media.ev3dev), 212 off() (pybricks.hubs.PrimeHub.light class method), 34
ImageFile.TIRED_MIDDLE (in module py- off() (pybricks.hubs.TechnicHub.light class method), 31
bricks.media.ev3dev), 212 off() (pybricks.nxtdevices.ColorSensor.light class
ImageFile.TIRED_RIGHT (in module py- method), 182
bricks.media.ev3dev), 212 off() (pybricks.pupdevices.ColorDistanceSensor.light
ImageFile.UP (in module pybricks.media.ev3dev), 212 class method), 98
ImageFile.WARNING (in module py- off() (pybricks.pupdevices.ColorSensor.lights class
bricks.media.ev3dev), 210 method), 135
ImageFile.WINKING (in module py- off() (pybricks.pupdevices.UltrasonicSensor.lights class
bricks.media.ev3dev), 212 method), 145
InfraredSensor (class in pybricks.ev3devices), 177 on() (Light method), 172
InfraredSensor (class in pybricks.pupdevices), 161 on() (pybricks.hubs.CityHub.light class method), 28
input() (EnergyMeter method), 184 on() (pybricks.hubs.EV3Brick.light class method), 50
intensity() (SoundSensor method), 183 on() (pybricks.hubs.InventorHub.light class method), 43
InventorHub (class in pybricks.hubs), 41 on() (pybricks.hubs.MoveHub.light class method), 26
on() (pybricks.hubs.PrimeHub.light class method), 34
on() (pybricks.hubs.TechnicHub.light class method), 31

247
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

on() (pybricks.nxtdevices.ColorSensor.light class pybricks.media.ev3dev (module), 208


method), 182 pybricks.messaging (module), 230
on() (pybricks.pupdevices.ColorDistanceSensor.light pybricks.nxtdevices (module), 180
class method), 98 pybricks.parameters (module), 195
on() (pybricks.pupdevices.ColorSensor.lights class pybricks.pupdevices (module), 61
method), 134 pybricks.robotics (module), 205
on() (pybricks.pupdevices.UltrasonicSensor.lights class pybricks.tools (module), 201
method), 144
ORANGE (Color attribute), 197 R
orientation() (pybricks.hubs.InventorHub.display class read() (Ev3devSensor method), 192
method), 47 read() (I2CDevice method), 188
orientation() (pybricks.hubs.PrimeHub.display class read() (LUMPDevice method), 186
method), 38 read() (Mailbox method), 234
output() (EnergyMeter method), 184 read() (UARTDevice method), 190
read_all() (UARTDevice method), 190
P RED (Color attribute), 197
passive() (AnalogSensor method), 187 reflection() (ColorDistanceSensor method), 81
pause() (StopWatch method), 201 reflection() (ColorSensor method), 114, 177, 182
pid() (Control method), 242 reflection() (InfraredSensor method), 162
pixel() (pybricks.hubs.InventorHub.display class reflection() (LightSensor method), 181
method), 47 reset() (DriveBase method), 207
pixel() (pybricks.hubs.PrimeHub.display class method), reset() (StopWatch method), 201
38 reset_angle() (GyroSensor method), 179
play_file() (EV3Brick.speaker method), 51 reset_angle() (Motor method), 65, 174
play_notes() (EV3Brick.speaker method), 51 resistance() (AnalogSensor method), 187
Port (class in pybricks.parameters), 195 resume() (StopWatch method), 201
Port.A (in module pybricks.parameters), 195 rgb() (ColorSensor method), 177, 182
Port.B (in module pybricks.parameters), 195 run() (Motor method), 69, 174
Port.C (in module pybricks.parameters), 195 run_angle() (Motor method), 70, 174
Port.D (in module pybricks.parameters), 195 run_target() (Motor method), 70, 175
Port.E (in module pybricks.parameters), 195 run_time() (Motor method), 70, 174
Port.F (in module pybricks.parameters), 195 run_until_stalled() (Motor method), 70, 175
Port.S1 (in module pybricks.parameters), 195
Port.S2 (in module pybricks.parameters), 195 S
Port.S3 (in module pybricks.parameters), 195 save() (EV3Brick.screen method), 58
Port.S4 (in module pybricks.parameters), 195 save() (Image method), 229
port_index (Ev3devSensor attribute), 192 say() (EV3Brick.speaker method), 51
presence() (UltrasonicSensor method), 143, 178 send() (Mailbox method), 234
pressed() (ForceSensor method), 156 sensor_index (Ev3devSensor attribute), 192
pressed() (pybricks.hubs.EV3Brick.buttons class set_font() (EV3Brick.screen method), 56
method), 50 set_font() (Image method), 227
pressed() (pybricks.hubs.InventorHub.buttons class set_speech_options() (EV3Brick.speaker method), 51
method), 49 set_volume() (EV3Brick.speaker method), 54
pressed() (pybricks.hubs.PrimeHub.buttons class settings() (DriveBase method), 206
method), 40 shape (Matrix attribute), 236
pressed() (TouchSensor method), 176, 180 Side (class in pybricks.parameters), 198
PrimeHub (class in pybricks.hubs), 32 Side.BACK (in module pybricks.parameters), 198
print() (EV3Brick.screen method), 55 Side.BOTTOM (in module pybricks.parameters), 198
print() (Image method), 227 Side.FRONT (in module pybricks.parameters), 198
pybricks.ev3devices (module), 173 Side.LEFT (in module pybricks.parameters), 199
pybricks.geometry (module), 236 Side.RIGHT (in module pybricks.parameters), 199
pybricks.hubs (module), 24 Side.TOP (in module pybricks.parameters), 198
pybricks.iodevices (module), 186 SoundFile (class in pybricks.media.ev3dev), 213
pybricks.media (module), 208

248
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

SoundFile.ACTIVATE (in module py- bricks.media.ev3dev), 219


bricks.media.ev3dev), 214 SoundFile.ERROR (in module pybricks.media.ev3dev),
SoundFile.AIR_RELEASE (in module py- 214
bricks.media.ev3dev), 218 SoundFile.ERROR_ALARM (in module py-
SoundFile.AIRBRAKE (in module py- bricks.media.ev3dev), 214
bricks.media.ev3dev), 218 SoundFile.EV3 (in module pybricks.media.ev3dev), 215
SoundFile.ANALYZE (in module py- SoundFile.FANFARE (in module py-
bricks.media.ev3dev), 214 bricks.media.ev3dev), 213
SoundFile.BACKING_ALERT (in module py- SoundFile.FANTASTIC (in module py-
bricks.media.ev3dev), 218 bricks.media.ev3dev), 215
SoundFile.BACKWARDS (in module py- SoundFile.FIVE (in module pybricks.media.ev3dev), 220
bricks.media.ev3dev), 214 SoundFile.FLASHING (in module py-
SoundFile.BLACK (in module pybricks.media.ev3dev), bricks.media.ev3dev), 214
217 SoundFile.FORWARD (in module py-
SoundFile.BLUE (in module pybricks.media.ev3dev), bricks.media.ev3dev), 214
217 SoundFile.FOUR (in module pybricks.media.ev3dev),
SoundFile.BOING (in module pybricks.media.ev3dev), 220
213 SoundFile.GAME_OVER (in module py-
SoundFile.BOO (in module pybricks.media.ev3dev), 213 bricks.media.ev3dev), 215
SoundFile.BRAVO (in module pybricks.media.ev3dev), SoundFile.GENERAL_ALERT (in module py-
215 bricks.media.ev3dev), 220
SoundFile.BROWN (in module pybricks.media.ev3dev), SoundFile.GO (in module pybricks.media.ev3dev), 216
217 SoundFile.GOOD (in module pybricks.media.ev3dev),
SoundFile.CAT_PURR (in module py- 216
bricks.media.ev3dev), 218 SoundFile.GOOD_JOB (in module py-
SoundFile.CHEERING (in module py- bricks.media.ev3dev), 216
bricks.media.ev3dev), 213 SoundFile.GOODBYE (in module py-
SoundFile.CLICK (in module pybricks.media.ev3dev), bricks.media.ev3dev), 216
220 SoundFile.GREEN (in module pybricks.media.ev3dev),
SoundFile.COLOR (in module pybricks.media.ev3dev), 217
214 SoundFile.HELLO (in module pybricks.media.ev3dev),
SoundFile.CONFIRM (in module py- 216
bricks.media.ev3dev), 220 SoundFile.HI (in module pybricks.media.ev3dev), 216
SoundFile.CRUNCHING (in module py- SoundFile.HORN_1 (in module pybricks.media.ev3dev),
bricks.media.ev3dev), 213 218
SoundFile.CRYING (in module pybricks.media.ev3dev), SoundFile.HORN_2 (in module pybricks.media.ev3dev),
213 218
SoundFile.DETECTED (in module py- SoundFile.INSECT_BUZZ_1 (in module py-
bricks.media.ev3dev), 214 bricks.media.ev3dev), 219
SoundFile.DOG_BARK_1 (in module py- SoundFile.INSECT_BUZZ_2 (in module py-
bricks.media.ev3dev), 219 bricks.media.ev3dev), 219
SoundFile.DOG_BARK_2 (in module py- SoundFile.INSECT_CHIRP (in module py-
bricks.media.ev3dev), 219 bricks.media.ev3dev), 219
SoundFile.DOG_GROWL (in module py- SoundFile.KUNG_FU (in module py-
bricks.media.ev3dev), 219 bricks.media.ev3dev), 213
SoundFile.DOG_SNIFF (in module py- SoundFile.LASER (in module pybricks.media.ev3dev),
bricks.media.ev3dev), 219 218
SoundFile.DOG_WHINE (in module py- SoundFile.LAUGHING_1 (in module py-
bricks.media.ev3dev), 219 bricks.media.ev3dev), 213
SoundFile.DOWN (in module pybricks.media.ev3dev), SoundFile.LAUGHING_2 (in module py-
214 bricks.media.ev3dev), 213
SoundFile.EIGHT (in module pybricks.media.ev3dev), SoundFile.LEFT (in module pybricks.media.ev3dev), 215
220 SoundFile.LEGO (in module pybricks.media.ev3dev),
SoundFile.ELEPHANT_CALL (in module py- 216

249
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

SoundFile.MAGIC_WAND (in module py- bricks.media.ev3dev), 217


bricks.media.ev3dev), 213 SoundFile.SPEED_IDLE (in module py-
SoundFile.MINDSTORMS (in module py- bricks.media.ev3dev), 217
bricks.media.ev3dev), 216 SoundFile.SPEED_UP (in module py-
SoundFile.MORNING (in module py- bricks.media.ev3dev), 217
bricks.media.ev3dev), 216 SoundFile.START (in module pybricks.media.ev3dev),
SoundFile.MOTOR_IDLE (in module py- 215
bricks.media.ev3dev), 218 SoundFile.STOP (in module pybricks.media.ev3dev), 215
SoundFile.MOTOR_START (in module py- SoundFile.T_REX_ROAR (in module py-
bricks.media.ev3dev), 218 bricks.media.ev3dev), 219
SoundFile.MOTOR_STOP (in module py- SoundFile.TEN (in module pybricks.media.ev3dev), 220
bricks.media.ev3dev), 218 SoundFile.THANK_YOU (in module py-
SoundFile.NINE (in module pybricks.media.ev3dev), 220 bricks.media.ev3dev), 217
SoundFile.NO (in module pybricks.media.ev3dev), 216 SoundFile.THREE (in module pybricks.media.ev3dev),
SoundFile.OBJECT (in module pybricks.media.ev3dev), 220
215 SoundFile.TICK_TACK (in module py-
SoundFile.OKAY (in module pybricks.media.ev3dev), bricks.media.ev3dev), 218
216 SoundFile.TOUCH (in module pybricks.media.ev3dev),
SoundFile.OKEY_DOKEY (in module py- 215
bricks.media.ev3dev), 216 SoundFile.TURN (in module pybricks.media.ev3dev),
SoundFile.ONE (in module pybricks.media.ev3dev), 220 215
SoundFile.OUCH (in module pybricks.media.ev3dev), SoundFile.TWO (in module pybricks.media.ev3dev), 220
213 SoundFile.UH_OH (in module pybricks.media.ev3dev),
SoundFile.OVERPOWER (in module py- 214
bricks.media.ev3dev), 221 SoundFile.UP (in module pybricks.media.ev3dev), 215
SoundFile.RATCHET (in module py- SoundFile.WHITE (in module pybricks.media.ev3dev),
bricks.media.ev3dev), 218 217
SoundFile.READY (in module pybricks.media.ev3dev), SoundFile.YELLOW (in module py-
221 bricks.media.ev3dev), 217
SoundFile.RED (in module pybricks.media.ev3dev), 217 SoundFile.YES (in module pybricks.media.ev3dev), 217
SoundFile.RIGHT (in module pybricks.media.ev3dev), SoundFile.ZERO (in module pybricks.media.ev3dev),
215 219
SoundFile.SEARCHING (in module py- SoundSensor (class in pybricks.nxtdevices), 182
bricks.media.ev3dev), 215 speed() (GyroSensor method), 179
SoundFile.SEVEN (in module pybricks.media.ev3dev), speed() (Motor method), 65, 174
220 stall_tolerances() (Control method), 242
SoundFile.SHOUTING (in module py- stalled() (Control method), 241
bricks.media.ev3dev), 213 state() (DriveBase method), 206
SoundFile.SIX (in module pybricks.media.ev3dev), 220 Stop (class in pybricks.parameters), 196
SoundFile.SMACK (in module pybricks.media.ev3dev), stop() (DriveBase method), 206
213 stop() (Motor method), 66, 174
SoundFile.SNAKE_HISS (in module py- Stop.BRAKE (in module pybricks.parameters), 196
bricks.media.ev3dev), 219 Stop.COAST (in module pybricks.parameters), 196
SoundFile.SNAKE_RATTLE (in module py- Stop.HOLD (in module pybricks.parameters), 196
bricks.media.ev3dev), 219 StopWatch (class in pybricks.tools), 201
SoundFile.SNEEZING (in module py- storage() (EnergyMeter method), 183
bricks.media.ev3dev), 214 straight() (DriveBase method), 205
SoundFile.SNORING (in module py- style (Font attribute), 222
bricks.media.ev3dev), 214
SoundFile.SONAR (in module pybricks.media.ev3dev), T
218 T (Matrix attribute), 236
SoundFile.SORRY (in module pybricks.media.ev3dev), target_tolerances() (Control method), 242
216 TechnicHub (class in pybricks.hubs), 29
SoundFile.SPEED_DOWN (in module py- temperature() (TemperatureSensor method), 183

250
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors
Pybricks Modules and Examples Version v3.0.0a3

TemperatureSensor (class in pybricks.nxtdevices), 183 write() (LUMPDevice method), 187


text() (pybricks.hubs.InventorHub.display class method), write() (UARTDevice method), 190
48
text() (pybricks.hubs.PrimeHub.display class method), 39 Y
text_height() (Font method), 225 YELLOW (Color attribute), 197
text_width() (Font method), 224
TextMailbox (class in pybricks.messaging), 234
tilt() (TiltSensor method), 166
TiltSensor (class in pybricks.pupdevices), 166
time() (StopWatch method), 201
touched() (ForceSensor method), 157
TouchSensor (class in pybricks.ev3devices), 176
TouchSensor (class in pybricks.nxtdevices), 180
track_target() (Motor method), 71, 175
turn() (DriveBase method), 205

U
UARTDevice (class in pybricks.iodevices), 190
UltrasonicSensor (class in pybricks.ev3devices), 178
UltrasonicSensor (class in pybricks.nxtdevices), 182
UltrasonicSensor (class in pybricks.pupdevices), 142

V
value() (VernierAdapter method), 185
vector() (in module pybricks.geometry), 236
VernierAdapter (class in pybricks.nxtdevices), 184
VIOLET (Color attribute), 198
voltage() (AnalogSensor method), 187
voltage() (pybricks.hubs.CityHub.battery class method),
29
voltage() (pybricks.hubs.EV3Brick.battery class method),
58
voltage() (pybricks.hubs.InventorHub.battery class
method), 49
voltage() (pybricks.hubs.MoveHub.battery class method),
26
voltage() (pybricks.hubs.PrimeHub.battery class method),
40
voltage() (pybricks.hubs.TechnicHub.battery class
method), 32
voltage() (VernierAdapter method), 184

W
wait() (in module pybricks.tools), 201
wait() (Mailbox method), 234
wait_for_connection() (BluetoothMailboxServer
method), 233
wait_new() (Mailbox method), 234
waiting() (UARTDevice method), 190
WHITE (Color attribute), 198
width (EV3Brick.screen attribute), 58
width (Font attribute), 223
width (Image attribute), 229
write() (I2CDevice method), 188

251
LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are trademarks and/or copyrights of the LEGO Group of companies which does not sponsor, authorize or endorse this site. © 2018-2020 The Pybricks Authors

You might also like