Lesson 08 The Night Shift · Python

Python Examples

Pybricks · programs to copy, run and change

Copy-paste Pybricks code that runs on both the SPIKE Prime hub and the MINDSTORMS Robot Inventor hub. Test, modify, and learn!

Before you start

  • On the hub

    Pybricks Firmware

    Runs every example below on SPIKE Prime and Robot Inventor hubs. You can restore the LEGO firmware any time.

  • In the browser

    Pybricks Code

    The browser editor at code.pybricks.com that installs the firmware and runs your programs.

  • Not the apps

    LEGO Apps

    The SPIKE and MINDSTORMS apps each use their own Python API, so these examples need Pybricks.

Code Examples

#01

Hello World - LED Matrix Display

Beginner

Display text and images on the hub's LED matrix. Perfect for your first program!

Python
from pybricks.hubs import PrimeHub
from pybricks.parameters import Icon
from pybricks.tools import wait

# PrimeHub also works on the MINDSTORMS Robot Inventor hub
hub = PrimeHub()

# Show one character
hub.display.char("A")
wait(1000)

# Show a built-in image
hub.display.icon(Icon.HAPPY)
wait(2000)

# Draw your own image: one brightness value (0 to 100) per pixel
smile = [
    [0, 100, 0, 100, 0],
    [0, 100, 0, 100, 0],
    [0, 0, 0, 0, 0],
    [100, 0, 0, 0, 100],
    [0, 100, 100, 100, 0],
]
hub.display.icon(smile)
wait(2000)

# Show text one character at a time (the lights turn off after the last one)
hub.display.text("HELLO")
  • MINDSTORMS
  • SPIKE Prime
#02

Motor Control Basics

Beginner

Control individual motors with speed, degrees, and timing.

Python
from pybricks.pupdevices import Motor
from pybricks.parameters import Port
from pybricks.tools import wait

motor = Motor(Port.A)

# Count degrees from where the motor is now
motor.reset_angle(0)

# Turn one full rotation at 500 degrees per second
motor.run_angle(500, 360)
wait(500)

# Run at 500 degrees per second for 2 seconds (time is in milliseconds)
motor.run_time(500, 2000)
wait(500)

# Run until told to stop
motor.run(300)
wait(2000)
motor.stop()

# Go back to the starting position
motor.run_target(500, 0)

# Read the rotation angle in degrees
print("Motor angle:", motor.angle())
  • MINDSTORMS
  • SPIKE Prime
#03

Driving Robot with DriveBase

Beginner

Drive a two-wheeled robot straight, turn in place, and steer with DriveBase, which keeps both motors in step.

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

# Left motor on port A, right motor on port B. The left motor is
# mirrored, so it turns counterclockwise to drive forward.
left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
right_motor = Motor(Port.B)

# Measure your own robot: wheel diameter and axle track in millimeters
robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112)

# Drive forward 200 mm, then back
robot.straight(200)
robot.straight(-200)

# Turn in place (positive = right, negative = left)
robot.turn(90)
robot.turn(-90)

# Curve: 100 mm/s forward while turning right at 45 degrees per second
robot.drive(100, 45)
wait(2000)
robot.stop()

# Spin in place: no forward speed, 90 degrees per second
robot.drive(0, 90)
wait(1000)
robot.stop()
Line 28 · Step 6 of 6 · Heading 180° 1 square = 50 mm
  • MINDSTORMS
  • SPIKE Prime
#04

Color Sensor Reading

Intermediate

Read colors, reflected light intensity, and ambient light for detection and sorting tasks.

Python
from pybricks.pupdevices import ColorSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait

sensor = ColorSensor(Port.C)

# Detected color: by default Color.RED, YELLOW, GREEN, BLUE, WHITE or NONE
print("Color:", sensor.color())

# Reflected light, 0 to 100 percent (higher = lighter surface)
print("Reflection:", sensor.reflection())

# Ambient light, 0 to 100 percent
print("Ambient:", sensor.ambient())

# Hue (0 to 359), saturation and brightness (0 to 100)
hsv = sensor.hsv()
print("Hue:", hsv.h, "Saturation:", hsv.s, "Brightness:", hsv.v)

# Wait until the sensor sees red
while sensor.color() != Color.RED:
    wait(10)
print("Red detected!")

# React to colors as they appear
while True:
    color = sensor.color()
    if color == Color.RED:
        print("STOP!")
        break
    elif color == Color.GREEN:
        print("GO!")
    wait(100)
  • MINDSTORMS
  • SPIKE Prime
#05

Distance Sensor & Obstacle Avoidance

Intermediate

Measure distance and avoid obstacles. Pybricks calls the SPIKE distance sensor UltrasonicSensor.

Python
from pybricks.pupdevices import Motor, UltrasonicSensor
from pybricks.parameters import Port, Direction
from pybricks.robotics import DriveBase
from pybricks.tools import wait

eyes = UltrasonicSensor(Port.D)
left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
right_motor = Motor(Port.B)
robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112)

# Distance in millimeters (2000 when nothing is in range)
print("Distance:", eyes.distance(), "mm")

# Light all four segments around the eyes, then two of them
eyes.lights.on(100)
wait(1000)
eyes.lights.on([100, 100, 0, 0])
wait(1000)
eyes.lights.off()

# Wait until something is closer than 100 mm
while eyes.distance() > 100:
    wait(10)
print("Object within 10 cm!")

# Simple obstacle avoidance
SAFE_DISTANCE = 200  # mm

while True:
    if eyes.distance() > SAFE_DISTANCE:
        robot.drive(150, 0)
    else:
        robot.stop()
        robot.turn(90)
    wait(10)

From line 22 the program steers by the distance sensor, so the drawing stops there. The plotter draws only what the code decides on its own.

  • MINDSTORMS
  • SPIKE Prime
#06

PID Line Following Robot

Advanced

Follow the edge of a line with PID steering: start with KP alone, then add KI and KD. The line-following robot tutorial walks through calibration and tuning.

Python
from pybricks.pupdevices import Motor, ColorSensor
from pybricks.parameters import Port, Direction
from pybricks.robotics import DriveBase
from pybricks.tools import wait

left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
right_motor = Motor(Port.B)
sensor = ColorSensor(Port.C)
robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112)

# Calibrate: print sensor.reflection() over the line and over the mat
BLACK = 10
WHITE = 90
TARGET = (BLACK + WHITE) / 2  # the edge of the line

# PID gains: starting points to tune
KP = 1.2  # degrees per second of turn per point of error
KI = 0.0  # add a little if the robot drifts on long curves
KD = 0.0  # add some to damp side-to-side wobble

DRIVE_SPEED = 100  # mm/s

integral = 0
last_error = 0

while True:
    error = sensor.reflection() - TARGET
    integral += error
    derivative = error - last_error

    turn_rate = KP * error + KI * integral + KD * derivative
    robot.drive(DRIVE_SPEED, turn_rate)

    last_error = error
    wait(10)

From line 26 the program steers by the colour sensor, so the drawing stops there. The plotter draws only what the code decides on its own.

  • MINDSTORMS
  • SPIKE Prime
  • Competition
#07

Gyro Sensor Navigation

Advanced

Use the built-in gyroscope for precise turns and straight-line driving. Essential for competition robots!

Python
from pybricks.hubs import PrimeHub
from pybricks.pupdevices import Motor
from pybricks.parameters import Port, Direction
from pybricks.robotics import DriveBase
from pybricks.tools import wait

hub = PrimeHub()
left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
right_motor = Motor(Port.B)
robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112)

# Heading in degrees: 0 at program start, positive = clockwise.
# It keeps counting past 180 instead of wrapping around.
print("Heading:", hub.imu.heading())

# Tilt in degrees
pitch, roll = hub.imu.tilt()
print("Pitch:", pitch, "Roll:", roll)

# Let the drive base use the gyro for straight lines and turns
robot.use_gyro(True)

robot.straight(300)
robot.turn(90)    # right 90 degrees
wait(500)
robot.turn(-180)  # left 180 degrees
wait(500)
robot.turn(90)    # back to the starting heading


# Or steer to a heading yourself with proportional control
def turn_to_heading(target, kp=3):
    while True:
        error = target - hub.imu.heading()
        if abs(error) < 2:  # close enough
            robot.stop()
            break
        robot.drive(0, kp * error)
        wait(10)


turn_to_heading(90)
turn_to_heading(0)
Line 28 · Step 4 of 4 · Heading 0° 1 square = 50 mm

From line 42 the program steers by the gyro, so the drawing stops there. The plotter draws only what the code decides on its own.

  • MINDSTORMS
  • SPIKE Prime
  • Competition

Further reading