Code Examples
Display text and images on the hub's LED matrix. Perfect for your first program!
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")
Control individual motors with speed, degrees, and timing.
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())
Drive a two-wheeled robot straight, turn in place, and steer with DriveBase, which keeps both motors in step.
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()
Read colors, reflected light intensity, and ambient light for detection and sorting tasks.
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)
Measure distance and avoid obstacles. Pybricks calls the SPIKE distance sensor UltrasonicSensor.
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)
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.
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)
Official Documentation
More Guides
- Ask BlockTalk AI Get instant Python coding help
- MINDSTORMS Programming Guide
- SPIKE Prime Programming Guide