### Detecting Devices Example Source: https://docs.pybricks.com/en/latest/iodevices/pupdevice Example code demonstrating how to detect and identify Pybricks Powered Up devices connected to different ports. ```APIDOC ## Detecting Devices ### Description This example iterates through available ports, attempts to instantiate a `PUPDevice` on each, and prints the device name based on its ID. ### Method `Detect Devices` ### Endpoint N/A (Code Example) ### Parameters N/A ### Request Body N/A ### Request Example ```python from pybricks.iodevices import PUPDevice from pybricks.parameters import Port from uerrno import ENODEV # Dictionary of device identifiers along with their name. device_names = { # pybricks.pupdevices.DCMotor 1: "Wedo 2.0 Medium Motor", 2: "Powered Up Train Motor", # pybricks.pupdevices.Light 8: "Powered Up Light", # pybricks.pupdevices.Motor 38: "BOOST Interactive Motor", 46: "Technic Large Motor", 47: "Technic Extra Large Motor", 48: "SPIKE Medium Angular Motor", 49: "SPIKE Large Angular Motor", 65: "SPIKE Small Angular Motor", 75: "Technic Medium Angular Motor", 76: "Technic Large Angular Motor", # pybricks.pupdevices.TiltSensor 34: "Wedo 2.0 Tilt Sensor", # pybricks.pupdevices.InfraredSensor 35: "Wedo 2.0 Infrared Motion Sensor", # pybricks.pupdevices.ColorDistanceSensor 37: "BOOST Color Distance Sensor", # pybricks.pupdevices.ColorSensor 61: "SPIKE Color Sensor", # pybricks.pupdevices.UltrasonicSensor 62: "SPIKE Ultrasonic Sensor", # pybricks.pupdevices.ForceSensor 63: "SPIKE Force Sensor", # pybricks.pupdevices.ColorLightMatrix 64: "SPIKE 3x3 Color Light Matrix", } # Make a list of known ports. ports = [Port.A, Port.B] # On hubs that support it, add more ports. try: ports.append(Port.C) ports.append(Port.D) except AttributeError: pass # On hubs that support it, add more ports. try: ports.append(Port.E) ports.append(Port.F) except AttributeError: pass # Go through all available ports. for port in ports: # Try to get the device, if it is attached. try: device = PUPDevice(port) except OSError as ex: if ex.args[0] == ENODEV: # No device found on this port. print(port, ": ---") continue else: raise # Get the device id id = device.info()["id"] # Look up the name. try: print(port, ":", device_names[id]) except KeyError: print(port, ":", "Unknown device with ID", id) ``` ### Response #### Success Response (200) Output will be printed to the console, indicating the port and the detected device name or 'Unknown device' if the ID is not in `device_names`. #### Response Example ``` Port.A : BOOST Interactive Motor Port.B : SPIKE Force Sensor Port.C : --- ``` ``` -------------------------------- ### Pybricks DCMotor: Start and Stop Sequence Source: https://docs.pybricks.com/en/latest/pupdevices/dcmotor This example demonstrates a basic start and stop sequence for a DCMotor. The motor is repeatedly set to a positive duty cycle for one second, then stopped using the `stop()` method for another second, within a loop. It uses `DCMotor`, `Port`, and `wait` from the Pybricks library. ```python 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) ``` -------------------------------- ### Measuring Color Example Source: https://docs.pybricks.com/en/latest/pupdevices/colordistancesensor Example code demonstrating how to initialize the ColorDistanceSensor and continuously measure and print the detected color. ```APIDOC ## Measuring color ### Description This example shows how to initialize the ColorDistanceSensor and read its color in a loop. ### Method GET (Conceptual - reading sensor data) ### Endpoint N/A (Local sensor interaction) ### Parameters None ### Request Body None ### Request Example ```python from pybricks.pupdevices import ColorDistanceSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorDistanceSensor(Port.A) while True: # Read the color. color = sensor.color() # Print the measured color. print(color) # Move the sensor around and see how # well you can detect colors. # Wait so we can read the value. wait(100) ``` ### Response #### Success Response (200) * **color** (Color) - The currently detected color. #### Response Example ```json { "color": "Color.RED" } ``` ``` -------------------------------- ### Pybricks Multitasking Example with async/await Source: https://docs.pybricks.com/en/latest/tools/index Demonstrates cooperative multitasking in Pybricks using async and await. This example shows how to run multiple coroutines concurrently, such as driving and operating a gripper simultaneously. Requires pybricks modules for devices and tools. ```Python from pybricks.pupdevices import Motor from pybricks.parameters import Direction, Port from pybricks.robotics import DriveBase from pybricks.tools import multitask, run_task # Set up all devices. left = Motor(Port.A, Direction.COUNTERCLOCKWISE) right = Motor(Port.B) gripper = Motor(Port.C) drive_base = DriveBase(left, right, 56, 114) # Move the gripper up and down. async def move_gripper(): await gripper.run_angle(500, -90) await gripper.run_angle(500, 90) # Drive forward, turn move gripper at the same time, and drive backward. async def main(): await drive_base.straight(250) await multitask(drive_base.turn(90), move_gripper()) await drive_base.straight(-250) # Runs the main program from start to finish. run_task(main()) ``` -------------------------------- ### Measure Color and Reflection Example Source: https://docs.pybricks.com/en/latest/pupdevices/colorsensor Demonstrates how to use the Color Sensor to measure both the color of a surface and its reflectivity. This example utilizes `color()` and `reflection()` methods, along with `wait()` for timing. ```python from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the color sensor color_sensor = ColorSensor(Port.A) # Measure and print color and reflection print("Measuring color and reflection...") color = color_sensor.color() reflection = color_sensor.reflection() print(f"Detected Color: {color}") print(f"Surface Reflection: {reflection}%") # Wait for 2 seconds wait(2000) ``` -------------------------------- ### Get Hub Information with system.info() Source: https://docs.pybricks.com/en/latest/hubs/movehub Retrieves information about the hub as a dictionary. Keys include hub name, reset reason, Bluetooth connection status, and program start type. The 'name' and 'reset_reason' were previously separate methods but are now included in this dictionary for convenience. ```python hub_info = system.info() print(hub_info["name"]) print(hub_info["reset_reason"]) print(hub_info["host_connected_ble"]) print(hub_info["program_start_type"]) ``` -------------------------------- ### Get System Information (Pybricks) Source: https://docs.pybricks.com/en/latest/hubs/technichub Retrieves a dictionary containing information about the hub, including its name, reset reason, Bluetooth connection status, and program start type. ```python system.info() ``` -------------------------------- ### Waiting for a Color Example Source: https://docs.pybricks.com/en/latest/pupdevices/colordistancesensor Example code demonstrating a function to wait until a specific color is detected by the ColorDistanceSensor. ```APIDOC ## Waiting for a color ### Description This example defines a function `wait_for_color` that pauses execution until the sensor detects a specified color. ### Method GET (Conceptual - reading sensor data) ### Endpoint N/A (Local sensor interaction) ### Parameters None ### Request Body None ### Request Example ```python from pybricks.pupdevices import ColorDistanceSensor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize the sensor. sensor = ColorDistanceSensor(Port.A) # This is a function that waits for a desired color. def wait_for_color(desired_color): # While the color is not the desired color, we keep waiting. while sensor.color() != desired_color: wait(20) # Example usage: # wait_for_color(Color.BLUE) # print("Blue color detected!") ``` ### Response #### Success Response (200) No direct response, execution continues after the desired color is detected. #### Response Example N/A ``` -------------------------------- ### Control a Power Functions motor Source: https://docs.pybricks.com/en/latest/pupdevices/pfmotor Example demonstrating how to initialize and control a single Power Functions motor using the `PFMotor` class. ```APIDOC ## Control a Power Functions motor ### Description This example shows how to set up a `ColorDistanceSensor` and a `PFMotor`, then control the motor's speed and direction. ### Method ```python from pybricks.pupdevices import ColorDistanceSensor, PFMotor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize the sensor. sensor = ColorDistanceSensor(Port.B) # Initialize a motor on channel 1, on the red output. motor = PFMotor(sensor, 1, Color.RED) # Rotate and then stop. motor.dc(100) wait(1000) motor.stop() wait(1000) # Rotate the other way at half speed, and then stop. motor.dc(-50) wait(1000) motor.stop() ``` ### Request Example ```json { "description": "Initialize ColorDistanceSensor on Port.B, PFMotor on channel 1 (Color.RED), run motor at 100% for 1 second, stop, run motor at -50% for 1 second, stop." } ``` ### Response Example ```json { "description": "Motor performs the specified actions." } ``` ``` -------------------------------- ### Initialize and Run Motor - pybricks Source: https://docs.pybricks.com/en/latest/pupdevices/motor Initializes a motor on a specified port and runs it clockwise at a given speed for a set duration. This is a basic example for motor control. ```python 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) ``` -------------------------------- ### Get Help Information for Objects in MicroPython Source: https://docs.pybricks.com/en/latest/micropython/builtins The `help()` function provides information about objects or module documentation. When called without arguments, it offers instructions for using the REPL. With the argument 'modules', it lists available modules. This is a standard MicroPython runtime utility. ```python help() help(_object_) -> None ``` -------------------------------- ### Controlling multiple Power Functions motors Source: https://docs.pybricks.com/en/latest/pupdevices/pfmotor Example demonstrating how to control multiple Power Functions motors simultaneously using different channels. ```APIDOC ## Controlling multiple Power Functions motors ### Description This example demonstrates controlling two `PFMotor` instances concurrently, each assigned to a different channel and potentially a different direction. ### Method ```python from pybricks.pupdevices import ColorDistanceSensor, PFMotor from pybricks.parameters import Port, Color, Direction from pybricks.tools import wait # Initialize the sensor. sensor = ColorDistanceSensor(Port.B) # You can use multiple motors on different channels. arm = PFMotor(sensor, 1, Color.BLUE) wheel = PFMotor(sensor, 4, Color.RED, Direction.COUNTERCLOCKWISE) # Accelerate both motors. for duty in [15, 30, 45, 60, 75, 90, 100]: arm.dc(duty) wheel.dc(duty) wait(1000) # Brake both motors. arm.brake() wheel.brake() ``` ### Request Example ```json { "description": "Initialize ColorDistanceSensor on Port.B, PFMotor 'arm' on channel 1 (Color.BLUE), PFMotor 'wheel' on channel 4 (Color.RED, Counter-Clockwise). Accelerate both motors gradually over 7 seconds, then brake both." } ``` ### Response Example ```json { "description": "Both motors accelerate and then brake as specified." } ``` ``` -------------------------------- ### Pybricks Hub: Create Status Light Animations Source: https://docs.pybricks.com/en/latest/hubs/primehub This example illustrates creating animations with the status light, including sequences of colors and dynamic color changes based on mathematical functions like sine waves. It requires importing `sin` and `pi` from `umath`. ```python from pybricks.hubs import PrimeHub from pybricks.parameters import Color from pybricks.tools import wait from umath import sin, pi # Initialize the hub. hub = PrimeHub() # Make an animation with multiple colors. hub.light.animate([Color.RED, Color.GREEN, Color.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) ``` -------------------------------- ### Pybricks Ultrasonic Sensor: Measure Distance and Control Lights Source: https://docs.pybricks.com/en/latest/pupdevices/ultrasonicsensor This example demonstrates how to initialize the UltrasonicSensor, continuously measure the distance to an object, and control the sensor's built-in lights based on the measured distance. It uses pybricks modules for sensor interaction and timing. ```python from pybricks.pupdevices import UltrasonicSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. eyes = UltrasonicSensor(Port.A) while True: # Print the measured distance. print(eyes.distance()) # If an object is detected closer than 500mm: if eyes.distance() < 500: # Turn the lights on. eyes.lights.on(100) else: # Turn the lights off. eyes.lights.off() # Wait some time so we can read what is printed. wait(100) ``` -------------------------------- ### Configure Stall Tolerances (Pybricks) Source: https://docs.pybricks.com/en/latest/pupdevices/motor Gets or sets the stalling tolerances for motor control. If no arguments are given, it returns the current values. Tolerances are defined by speed and time. ```python control.stall_tolerances(speed=1, time=100) ``` ```python control.stall_tolerances() ``` -------------------------------- ### Button and System Control Source: https://docs.pybricks.com/en/latest/hubs/technichub APIs for checking button states, getting system information, setting the stop button behavior, and interacting with persistent storage. ```APIDOC ## GET /buttons/pressed ### Description Checks which buttons are currently pressed. ### Method GET ### Endpoint `/buttons/pressed` ### Response #### Success Response (200) - **pressed_buttons** (Set[Button]) - A set containing the currently pressed buttons (e.g., `Button.CENTER`, `Button.LEFT`). #### Response Example ```json { "pressed_buttons": ["CENTER", "LEFT"] } ``` ## GET /system/info ### Description Gets information about the hub, including its name, reset reason, connection status, and program start type. ### Method GET ### Endpoint `/system/info` ### Response #### Success Response (200) - **hub_info** (dict) - A dictionary containing system information with keys: `"name"`, `"reset_reason"`, `"host_connected_ble"`, `"program_start_type"`. #### Response Example ```json { "hub_info": { "name": "Pybricks Hub", "reset_reason": 0, "host_connected_ble": true, "program_start_type": 3 } } ``` ## POST /system/set_stop_button ### Description Sets the button or button combination that stops a running script. This can be used to disable the default stop button behavior. ### Method POST ### Endpoint `/system/set_stop_button` ### Parameters #### Request Body - **button** (Button | tuple | None) - Required - The button or tuple of buttons to set as the stop button. Use `None` to disable the stop button. ### Request Example ```json { "button": ["CENTER", "UP"] } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the operation. #### Response Example ```json { "status": "Stop button configured successfully." } ``` ## POST /system/storage ### Description Writes binary data to persistent storage. ### Method POST ### Endpoint `/system/storage` ### Parameters #### Request Body - **offset** (int) - Required - The starting byte offset for writing. - **data** (bytes) - Required - The binary data to write. ### Request Example ```json { "offset": 0, "data": "SGVsbG8sIFdvcmxkIQ==" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure of the write operation. #### Response Example ```json { "status": "Data written to storage successfully." } ``` ## GET /system/storage ### Description Reads binary data from persistent storage. ### Method GET ### Endpoint `/system/storage` ### Parameters #### Query Parameters - **offset** (int) - Required - The starting byte offset for reading. - **length** (int) - Required - The number of bytes to read. ### Request Example ``` GET /system/storage?offset=0&length=12 ``` ### Response #### Success Response (200) - **data** (bytes) - The binary data read from storage. #### Response Example ```json { "data": "SGVsbG8sIFdvcmxkIQ==" } ``` ``` -------------------------------- ### Configure Drive Settings Source: https://docs.pybricks.com/en/latest/robotics Sets the speed and acceleration for straight-line driving and turning. Can be used to get current settings if no arguments are provided. ```APIDOC ## `settings()` Method ### Description Configures the drive base speed and acceleration. If you give no arguments, this returns the current values as a tuple. The initial values are automatically configured based on your wheel diameter and axle track. ### Method `settings(straight_speed, straight_acceleration, turn_rate, turn_acceleration)` ### Parameters #### Path Parameters * **straight_speed** (Number, mm/s) - Optional - Straight-line speed of the robot. * **straight_acceleration** (Number, mm/s²) - Optional - Straight-line acceleration and deceleration of the robot. Provide a tuple with two values to set acceleration and deceleration separately. * **turn_rate** (Number, deg/s) - Optional - Turn rate of the robot. * **turn_acceleration** (Number, deg/s²) - Optional - Turn acceleration and deceleration rate. ``` -------------------------------- ### Pybricks Hub: Control Individual Pixels on Matrix Source: https://docs.pybricks.com/en/latest/hubs/primehub This example demonstrates controlling individual pixels on the hub's matrix display by setting their position and brightness. It shows how to turn pixels on, off, and set specific brightness levels. ```python from pybricks.hubs import PrimeHub from pybricks.tools import wait # Initialize the hub. hub = PrimeHub() # 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) ``` -------------------------------- ### Pybricks Hub: Control Status Light Brightness and Custom Colors Source: https://docs.pybricks.com/en/latest/hubs/primehub This example shows how to adjust the brightness of the status light and how to use custom colors defined by HSV values. It utilizes the Color class and allows for dynamic color changes in a loop. ```python 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) ``` -------------------------------- ### Python: EssentialHub Status Light Animations Source: https://docs.pybricks.com/en/latest/hubs/essentialhub Provides examples of creating light animations on the EssentialHub using predefined color sequences and custom patterns. It uses `pybricks.hubs.EssentialHub`, `pybricks.parameters.Color`, `pybricks.tools.wait`, and `umath.sin`, `umath.pi`. The `animate` method allows for complex visual effects. ```python from pybricks.hubs import EssentialHub from pybricks.parameters import Color from pybricks.tools import wait from umath import sin, pi # Initialize the hub. hub = EssentialHub() # Make an animation with multiple colors. hub.light.animate([Color.RED, Color.GREEN, Color.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) ``` -------------------------------- ### Configure PID Control (Pybricks) Source: https://docs.pybricks.com/en/latest/pupdevices/motor Gets or sets the PID (Proportional-Integral-Derivative) values for position and speed control. If no arguments are given, it returns the current PID values. Parameters include kp, ki, kd, integral_deadzone, and integral_rate. ```python control.pid(kp=100, ki=10, kd=50, integral_deadzone=10, integral_rate=100) ``` ```python control.pid() ``` -------------------------------- ### Get Robot Heading Source: https://docs.pybricks.com/en/latest/hubs/essentialhub Retrieves the current heading angle of the robot relative to its starting orientation. The heading is 0 at program start and increases with clockwise turns. Note that this method currently only tracks heading accurately on a flat surface. ```python imu.heading() # Returns: float: deg # Example: 45.0 ``` -------------------------------- ### Pybricks Motor Stopping Methods in Python Source: https://docs.pybricks.com/en/latest/pupdevices/motor This example demonstrates various ways to stop a Pybricks motor's ongoing movement: 'stop' (coasting), 'brake' (applying resistance), 'hold' (maintaining position), and 'run(0)' (stopping by running at zero speed). It requires pybricks.pupdevices.Motor and pybricks.tools.wait. ```python 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) ``` -------------------------------- ### help() - Object Information Source: https://docs.pybricks.com/en/latest/micropython/builtins Provides information about objects or instructions for using the REPL. ```APIDOC ## help() - Object Information ### Description Get information about an object. If no arguments are given, this function prints instructions to operate the REPL. If the argument is "modules", it prints the available modules. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python help() # Prints REPL instructions help("modules") # Prints available modules help(sum) # Prints help for the sum function ``` ### Response #### Success Response (200) None (help() prints information to the console) #### Response Example ```json { "example": "Information printed to console, no direct return value." } ``` ``` -------------------------------- ### Pybricks Light: Blink Example Source: https://docs.pybricks.com/en/latest/pupdevices/light This code snippet demonstrates how to make a Pybricks light blink continuously. It initializes the Light device on a specified port and then enters an infinite loop to toggle the light on and off with a 500ms delay between state changes. Dependencies include `pybricks.pupdevices.Light`, `pybricks.parameters.Port`, and `pybricks.tools.wait`. ```python from pybricks.pupdevices import Light from pybricks.parameters import Port from pybricks.tools import wait # Initialize the light. light = Light(Port.A) # Blink the light forever. while True: # Turn the light on at 100% brightness. light.on(100) wait(500) # Turn the light off. light.off() wait(500) ``` -------------------------------- ### Get Robot Heading Angle - Pybricks Source: https://docs.pybricks.com/en/latest/hubs/technichub Retrieves the current heading angle of the robot in degrees. The heading is relative to the starting orientation and does not wrap around. Note: This function currently only provides accurate readings when the robot is on a flat surface. ```python imu.heading() ``` -------------------------------- ### City Hub Initialization Source: https://docs.pybricks.com/en/latest/hubs/cityhub Initializes the City Hub with optional broadcast and observe channels. ```APIDOC ## _CityHub(_broadcast_channel =None_, _observe_channels =[])_ ### Description Initializes the LEGO® City Hub. ### Parameters * **broadcast_channel** (_int_) - Optional - Channel number (0 to 255) used to broadcast data. Set to `None` when not using broadcasting. * **observe_channels** (_list_) - Optional - A list of channels to listen to when `hub.ble.observe()` is called. Default is an empty list. ``` -------------------------------- ### Initialize and Control Color Light Matrix (Pybricks) Source: https://docs.pybricks.com/en/latest/pupdevices/colorlightmatrix This snippet shows how to initialize the Color Light Matrix connected to a specific port and how to control its lights. It supports turning all lights to a single color or individual lights to specific colors. It also includes a method to turn all lights off. ```python from pybricks.pupdevices import ColorLightMatrix from pybricks.tools import wait from pybricks.parameters import Color # Assuming the matrix is connected to port 'A' matrix = ColorLightMatrix('A') # Turn all lights red matrix.on(Color.RED) wait(1000) # Turn all lights off matrix.off() wait(1000) # Example of setting individual lights (requires a list of 9 colors) # For simplicity, let's create a pattern colors = [ Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.ORANGE, Color.PURPLE, Color.WHITE, Color.BLACK, Color.CYAN ] matrix.on(colors) wait(2000) matrix.off() ``` -------------------------------- ### Basic Pybricks Motor Run Methods in Python Source: https://docs.pybricks.com/en/latest/pupdevices/motor This example showcases the basic run methods for a Pybricks motor, including 'run' (degrees per second), 'dc' (duty cycle), 'run_time' (degrees per second for a duration), 'run_angle' (degrees per second for an angle), 'run_target' (degrees per second to a target angle), and 'run_until_stalled'. It requires pybricks.pupdevices.Motor and pybricks.tools.wait. ```python 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 50% 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, 90) 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) ``` -------------------------------- ### Get Bluetooth Signal Strength (Pybricks) Source: https://docs.pybricks.com/en/latest/hubs/technichub Gets the average signal strength in dBm for a given Bluetooth channel, indicating proximity to the broadcasting device. Returns -128 if no recent data is observed. ```python ble.signal_strength(channel) ``` -------------------------------- ### Get IMU Acceleration Data Source: https://docs.pybricks.com/en/latest/hubs/technichub Reads acceleration data from the IMU. You can get the acceleration along a specific axis or as a vector along all axes. The data can be either calibrated or raw, depending on the `calibrated` parameter. ```python from pybricks.hubs import TechnicHub from pybricks.tools import Axis hub = TechnicHub() # Get acceleration along the X-axis (calibrated) acc_x = hub.imu.acceleration(Axis.X) print(f"Acceleration X: {acc_x} mm/s^2") # Get acceleration vector along all axes (raw data) acc_vector_raw = hub.imu.acceleration(calibrated=False) print(f"Raw acceleration vector: {acc_vector_raw} mm/s^2") # Get acceleration vector along all axes (calibrated) acc_vector = hub.imu.acceleration() print(f"Calibrated acceleration vector: {acc_vector} mm/s^2") ``` -------------------------------- ### Using Direction, Port, and Stop Parameters Source: https://context7.com/context7/pybricks_en/llms.txt This snippet demonstrates the fundamental use of `Port`, `Direction`, and `Stop` parameters when initializing motor objects in Pybricks. It shows how to specify which port a motor is connected to and its operational direction. ```python from pybricks.parameters import Port, Direction, Stop, Color, Button from pybricks.pupdevices import Motor # Port specification motor_a = Motor(Port.A) motor_b = Motor(Port.B) ``` -------------------------------- ### Get Rotation Along Axis - Pybricks Source: https://docs.pybricks.com/en/latest/hubs/technichub Gets the rotation angle of the device along a specified axis in degrees. This is useful for robots that primarily rotate along a single axis. The `calibrated` parameter allows for compensated or unscaled values. ```python imu.rotation(_axis_ , _calibrated =True_) ``` -------------------------------- ### Sum Items in an Iterable with Optional Start Value in Python Source: https://docs.pybricks.com/en/latest/micropython/builtins The `sum()` function calculates the total of all items within an iterable (like a list or tuple). It can optionally take a 'start' value which is added to the sum of the iterable's elements. This function is part of Python's built-in capabilities. ```python sum(_iterable_) sum(_iterable_ , _start_) ``` -------------------------------- ### Read Color and Reflection using Pybricks Color Sensor Source: https://docs.pybricks.com/en/latest/pupdevices/colorsensor This snippet demonstrates how to initialize a ColorSensor on Port A, and then continuously read and print its detected color and reflection values. It uses a simple loop with a wait function for periodic readings. No external dependencies are required beyond the pybricks library. ```python from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) while True: # Read the color and reflection color = sensor.color() reflection = sensor.reflection() # Print the measured color and reflection. print(color, reflection) # Wait so we can read the value. wait(100) ``` -------------------------------- ### Speaker Volume API Source: https://docs.pybricks.com/en/latest/hubs/primehub Allows you to get or set the volume of the speaker. ```APIDOC ## GET/POST /speaker/volume ### Description Gets or sets the speaker volume. If no volume is given, this method returns the current volume. ### Method GET (to retrieve volume), POST (to set volume) ### Endpoint /speaker/volume ### Parameters #### Query Parameters (for GET) None #### Request Body (for POST) - **volume** (Number, %) - Required - Volume of the speaker in the 0-100 range. ### Request Example (POST) ```json { "volume": 75 } ``` ### Response #### Success Response (200) - **volume** (int, %) - The current volume of the speaker. #### Response Example (GET) ```json { "volume": 75 } ``` ``` -------------------------------- ### Get Battery Current (Pybricks) Source: https://docs.pybricks.com/en/latest/hubs/technichub Retrieves the current being supplied by the battery in milliamperes (mA). ```python battery.current() ``` -------------------------------- ### Initialize and Use DriveBase in Python Source: https://docs.pybricks.com/en/latest/robotics Demonstrates how to initialize the DriveBase with left and right motors, wheel diameter, and axle track. It also shows examples of driving straight, turning, and driving arcs. This requires the 'Motor' and 'Stop' classes from the 'pybricks.robotics' and 'pybricks.tools' modules respectively. ```python from pybricks.robotics import DriveBase from pybricks.ev3devices import Motor from pybricks.parameters import Stop # Initialize motors (assuming motors are connected to ports B and C) left_motor = Motor(port=Motor.B) right_motor = Motor(port=Motor.C) # Initialize DriveBase # wheel_diameter = 55.5 # mm # axle_track = 104 # mm drive_base = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104) # Example: Drive straight 100 mm forward drive_base.straight(100) # Example: Turn 90 degrees clockwise drive_base.turn(90) # Example: Drive an arc with radius 50 mm for 180 degrees drive_base.arc(radius=50, angle=180) # Example: Drive an arc with radius 50 mm for a distance of 100 mm drive_base.arc(radius=50, distance=100) # Example: Drive straight 200 mm and then stop with coasting drive_base.straight(200, then=Stop.COAST) # Example: Turn 45 degrees left and wait for completion drive_base.turn(-45, wait=True) ``` -------------------------------- ### id() - Object Identity Source: https://docs.pybricks.com/en/latest/micropython/builtins Gets the unique identity (memory address) of an object. ```APIDOC ## id() - Object Identity ### Description Gets the _identity_ of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python obj = [1, 2, 3] id_val = id(obj) print(id_val) ``` ### Response #### Success Response (200) - **int** - The identifier (memory address) of the object. #### Response Example ```json { "example": "A unique integer representing the object's memory address, e.g., 140733380888448" } ``` ``` -------------------------------- ### Get Battery Voltage (Pybricks) Source: https://docs.pybricks.com/en/latest/hubs/technichub Retrieves the current voltage of the battery in millivolts (mV). ```python battery.voltage() ``` -------------------------------- ### Python: Initialize EssentialHub and Control Status Light On/Off Source: https://docs.pybricks.com/en/latest/hubs/essentialhub Initializes the EssentialHub and demonstrates how to turn the status light on and off repeatedly. It utilizes the `pybricks.hubs.EssentialHub` for hub initialization, `pybricks.parameters.Color` for color selection, and `pybricks.tools.wait` for timing control. ```python from pybricks.hubs import EssentialHub from pybricks.parameters import Color from pybricks.tools import wait # Initialize the hub. hub = EssentialHub() # 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) ``` -------------------------------- ### Initialize Prime Hub with Custom Orientation and Status Light Source: https://context7.com/context7/pybricks_en/llms.txt Demonstrates initializing a LEGO Prime Hub with a specified orientation using Axis parameters and setting the status light color. It also shows how to check for button presses. ```python from pybricks.hubs import PrimeHub from pybricks.parameters import Axis, Color, Button # Initialize hub with custom orientation # Specify which axis points through the top and front of the hub hub = PrimeHub(top_side=Axis.Z, front_side=Axis.X) # Turn on the status light hub.light.on(Color.GREEN) # Read button state pressed = hub.buttons.pressed() if Button.CENTER in pressed: print("Center button pressed") ``` -------------------------------- ### Get Bluetooth Firmware Version (Pybricks) Source: https://docs.pybricks.com/en/latest/hubs/technichub Retrieves the firmware version from the Bluetooth chip. ```python ble.version() ``` -------------------------------- ### hash() - Object Hash Value Source: https://docs.pybricks.com/en/latest/micropython/builtins Gets the hash value of an object if it supports hashing. ```APIDOC ## hash() - Object Hash Value ### Description Gets the hash value of an object, if the object supports it. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python value = hash(123) print(value) string_val = hash("hello") print(string_val) ``` ### Response #### Success Response (200) - **int** - The hash value. #### Response Example ```json { "example": "123 or a specific hash integer" } ``` ``` -------------------------------- ### LWP3Device Class Source: https://docs.pybricks.com/en/latest/iodevices/lwp3device Establishes a connection to a hub using the LEGO Wireless Protocol v3. ```APIDOC ## LWP3Device Class ### Description Connects to a hub running official LEGO firmware using the LEGO Wireless Protocol v3. ### Class _LWP3Device(_hub_kind_, _name=None_, _timeout=10000_, _pair=False_, _num_notifications=8_) ### Parameters #### Path Parameters - **hub_kind** (int) - Required - The hub type identifier of the hub to connect to. - **name** (str) - Optional - The name of the hub to connect to or `None` to connect to any hub. - **timeout** (int) - Optional - The time, in milliseconds, to wait for a connection before raising an exception. - **pair** (bool) - Optional - Whether to attempt pairing for a secure connection. This is required for some newer hubs. (Added in version 3.6) - **num_notifications** (int) - Optional - Number of incoming messages from the remote hub to store before discarding older messages. (Added in version 3.7) ### Methods #### name(_name_) - **Description**: Sets or gets the Bluetooth name of the device. - **Method**: GET/POST - **Endpoint**: N/A (Method of LWP3Device instance) - **Parameters**: - **name** (str) - Optional - New Bluetooth name of the device. If no name is given, this method returns the current name. #### write(_buf_) - **Description**: Sends a message to the remote hub. - **Method**: POST - **Endpoint**: N/A (Method of LWP3Device instance) - **Parameters**: - **buf** (bytes) - Required - The raw binary message to send. - **Asynchronous**: True #### read() - **Description**: Retrieves the oldest buffered message received from the remote hub. If all buffered messages have already been read, this returns `None`. - **Method**: GET - **Endpoint**: N/A (Method of LWP3Device instance) - **Returns**: bytes | None - The oldest raw binary message or `None` if there are no more messages. - **Changed in version 3.7**: Now supports reading multiple buffered messages instead of blocking until one new message was received. #### disconnect() - **Description**: Disconnects the remote LWP3Device from the hub. - **Method**: POST - **Endpoint**: N/A (Method of LWP3Device instance) - **Asynchronous**: True ``` -------------------------------- ### sum() - Summation Function Source: https://docs.pybricks.com/en/latest/micropython/builtins Calculates the sum of items in an iterable, optionally with a starting value. ```APIDOC ## sum() - Summation Function ### Description Sums the items from the iterable and the start value. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example with start value result = sum([1, 2, 3], 10) # result will be 16 # Example without start value result = sum([1, 2, 3]) # result will be 6 ``` ### Response #### Success Response (200) - **Number** - The total sum. #### Response Example ```json { "example": "6 or 16 depending on usage" } ``` ``` -------------------------------- ### Shutting Down CityHub Source: https://docs.pybricks.com/en/latest/hubs/cityhub Provides a simple example of how to shut down a Pybricks CityHub. It prints a 'Goodbye!' message, waits briefly, and then executes the shutdown command. ```python from pybricks.hubs import CityHub from pybricks.tools import wait # Initialize the hub. hub = CityHub() # Say goodbye and give some time to send it. print("Goodbye!") wait(100) # Shut the hub down. hub.system.shutdown() ``` -------------------------------- ### Pybricks Hub Menu: Select Program Source: https://docs.pybricks.com/en/latest/tools/index Demonstrates how to use the `hub_menu` function from `pybricks.tools` to display a menu on the hub and execute different programs based on user selection. This function simplifies creating interactive menus for program selection. ```python from pybricks.tools import hub_menu # This example assumes that you have three other programs in Pybricks Code, # called "fly_mission", "drive_mission", and "zigzag". This example creates a # menu that lets you pick which one to run. # Choose a letter. selected = hub_menu("F", "D", "Z") # Based on the selection, run a program. if selected == "F": import fly_mission elif selected == "D": import drive_mission elif selected == "Z": import zigzag ``` -------------------------------- ### Charger API Source: https://docs.pybricks.com/en/latest/hubs/primehub Provides functions to check charger connection, get charging current, and retrieve the charger status. ```APIDOC ## Charger API ### `charger.connected()` #### Description Checks whether a charger is connected via USB. #### Method #### Endpoint `charger.connected` #### Returns - `True` if a charger is connected, `False` otherwise (bool). ### `charger.current()` #### Description Gets the charging current. #### Method #### Endpoint `charger.current` #### Returns - Charging current in mA (int). ### `charger.status()` #### Description Gets the status of the battery charger, indicated by the battery light. #### Method #### Endpoint `charger.status` #### Returns - Status value (int): 0 (Not charging), 1 (Charging), 2 (Charging complete), 3 (Charger problem). ```