### Initialization examples Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/motor.md Examples demonstrating how to initialize and use motors in Pybricks. ```APIDOC ## Initialization Examples ### Making the motor move back and forth ```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) ``` ### Initializing multiple motors ```python 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) ``` ### Setting the positive direction as counterclockwise ```python from pybricks.pupdevices import Motor from pybricks.parameters import Port, Direction from pybricks.tools import wait # Example usage for setting positive direction # (Code snippet incomplete in source) ``` ``` -------------------------------- ### Turn EV3 light on and change color Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/ev3brick.rst This example shows how to turn on the EV3 brick's status light and set its color. Ensure the `ev3dev` library is installed. ```python from pybricks.hubs import EV3Brick from pybricks.tools import wait from pybricks.parameters import Color # Initialize the EV3 Brick b = EV3Brick() # Turn the light on and set color to red b.light.on(Color.RED) wait(1000) # Turn the light on and set color to green b.light.on(Color.GREEN) wait(1000) # Turn the light off b.light.off() wait(1000) # Turn the light on and set color to blue b.light.on(Color.BLUE) wait(1000) # Turn the light off b.light.off() ``` -------------------------------- ### Status light examples Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/movehub.md Examples demonstrating how to turn the status light on and off. ```APIDOC ## Status light examples ### Turning the light on and off ```python from pybricks.hubs import MoveHub from pybricks.parameters import Color from pybricks.tools import wait # Initialize the hub. hub = MoveHub() # 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) ``` ``` -------------------------------- ### UARTDevice Usage Example Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/iodevices/uartdevice.rst This example demonstrates how to read from and write to a UART device using the pybricks.iodevices.UARTDevice class on an EV3 brick. ```APIDOC ## UARTDevice Class ### Description The `UARTDevice` class provides a way to communicate with devices that use the Universal Asynchronous Receiver/Transmitter (UART) protocol. This class is currently only supported on the EV3 hardware. ### Note This class is **only supported on the EV3** at this time. It could be added to Powered Up hubs in a future release. ### Example: Read and write to a UART device ```python from pybricks.iodevices import UARTDevice from pybricks.parameters import Port # Initialize the UART device on Port 1 uart = UARTDevice(Port.S1) # Write data to the device uart.write(b"Hello\n") # Read data from the device (up to 10 bytes) data = uart.read(10) # Print the received data print(data) ``` ### Request Body This class does not directly involve HTTP requests. The `write` method takes bytes as input. ### Response This class does not directly involve HTTP responses. The `read` method returns bytes. ``` -------------------------------- ### Debugging in the REPL Terminal Example Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/exceptions.md This example demonstrates how to use `KeyboardInterrupt` to exit a script and continue debugging in the REPL terminal. It shows how to initialize a motor, run it, and then raise `KeyboardInterrupt` to enter the interactive terminal. ```APIDOC ## Example: Debugging in the REPL terminal ```python from pybricks.pupdevices import Motor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the motor. test_motor = Motor(Port.A) # Start moving at 500 deg/s. test_motor.run(500) # If you click on the terminal window and press CTRL+C, # you can continue debugging in this terminal. wait(5000) # You can also do this to exit the script and enter the # terminal. Variables in the global scope are still available. raise KeyboardInterrupt # For example, you can copy the following line to the terminal # to get the angle, because test_motor is still available. test_motor.angle() ``` ``` -------------------------------- ### Initialize the development environment Source: https://github.com/pybricks/pybricks-api/blob/master/CONTRIBUTING.md Commands to clone the repository and install dependencies using Poetry. ```bash git clone --recursive https://github.com/pybricks/pybricks-api cd pybricks-api poetry install ``` -------------------------------- ### GET imu.ready() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/essentialhub.md Checks if the IMU device is calibrated and ready for use. ```APIDOC ## GET imu.ready() ### Description Checks if the device is calibrated and ready for use. This returns True when the robot has been stationary for a few seconds, allowing for re-calibration. It returns False if the hub has just started or has not calibrated for more than 10 minutes. ### Method GET ### Endpoint imu.ready() ### Response #### Success Response (200) - **result** (bool) - True if the device is ready for use, False otherwise. ``` -------------------------------- ### Read Acceleration Data Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/movehub.md Read acceleration data from the IMU. This example shows how to get the full acceleration tuple and individual X, Y, Z values. ```python from pybricks.hubs import MoveHub from pybricks.tools import wait # Initialize the hub. hub = MoveHub() # Get the acceleration tuple. print(hub.imu.acceleration()) while True: # Get individual acceleration values. x, y, z = hub.imu.acceleration() print(x, y, z) # Wait so we can see what we printed. wait(100) ``` -------------------------------- ### Build documentation on macOS Source: https://github.com/pybricks/pybricks-api/blob/master/CONTRIBUTING.md Commands to build and open the documentation on macOS. ```bash # macOS poetry run make -C doc html open doc/main/build/html/index.html ``` -------------------------------- ### Get Random Element from Range (randrange) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/urandom.md Use `randrange` to select a random element from a range defined by start, stop, and step. The 'stop' value is excluded from the possible results. ```python randrange(stop: [int](builtins.md#ubuiltins.int)) → [int](builtins.md#ubuiltins.int) randrange(start: [int](builtins.md#ubuiltins.int), stop: [int](builtins.md#ubuiltins.int)) → [int](builtins.md#ubuiltins.int) andrange(start: [int](builtins.md#ubuiltins.int), stop: [int](builtins.md#ubuiltins.int), step: [int](builtins.md#ubuiltins.int)) → [int](builtins.md#ubuiltins.int) randrange(stop) -> int andrange(start, stop) -> int andrange(start, stop, step) -> int Returns a randomly selected element from `range(start, stop, step)`. For example, `randrange(1, 7, 2)` returns random numbers from `1` up to (but excluding) `7`, in increments of `2`. In other words, it returns `1`, `3`, or `5`. * **Parameters:** * **start** ([*int*](builtins.md#ubuiltins.int)) – Lowest value. Defaults to `0` if only one argument is given. * **stop** ([*int*](builtins.md#ubuiltins.int)) – Highest value. This value is *not* included in the range. * **step** ([*int*](builtins.md#ubuiltins.int)) – Increment between values. Defaults to `1` if only one or two arguments are given. * **Returns:** The random number. ``` -------------------------------- ### Get Basic Heading Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/primehub.md This method returns the heading angle relative to the starting orientation. Note that this method only keeps track of the heading while the robot is on a flat surface and may not be accurate if the robot is lifted or on a ramp. ```python hub.imu.heading() ``` -------------------------------- ### range(stop) / range(start, stop) / range(start, stop, step) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/builtins.md Creates a generator that yields values from `start` up to `stop`, with increments of `step`. Defaults are provided for `start` and `step` if not explicitly given. ```APIDOC ## range(stop) ## range(start, stop) ## range(start, stop, step) ### Description Creates a generator that yields values from `start` up to `stop`, with increments of `step`. ### Parameters #### Path Parameters - **start** (int) - Optional - Starting value. Defaults to `0` if only one argument is given. - **stop** (int) - Required - Endpoint. This value is *not* included. - **step** (int) - Optional - Increment between values. Defaults to `1` if only one or two arguments are given. ``` -------------------------------- ### Build documentation on Linux Source: https://github.com/pybricks/pybricks-api/blob/master/CONTRIBUTING.md Commands to build and open the documentation on Linux systems. ```bash poetry run make -C doc html xdg-open doc/main/build/html/index.html ``` -------------------------------- ### Define and use colors Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/parameters/color.md Demonstrates how to access predefined colors, read their properties, and create custom color instances. ```python from pybricks.parameters import Color # You can print colors. Colors may be obtained from the Color class, or # from sensors that return color measurements. print(Color.RED) # You can read hue, saturation, and value properties. print(Color.RED.h, Color.RED.s, Color.RED.v) # You can make your own colors. Saturation and value are 100 by default. my_green = Color(h=125) my_dark_green = Color(h=125, s=80, v=30) # When you print custom colors, you see exactly how they were defined. print(my_dark_green) # You can also add colors to the builtin colors. Color.MY_DARK_BLUE = Color(h=235, s=80, v=30) # When you add them like this, printing them only shows its name. But you can ``` -------------------------------- ### DriveBase Movement Examples Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/robotics.md Example usage of the DriveBase class to perform straight movements and turns. ```APIDOC ## DriveBase Movement ### Description Example program demonstrating how to initialize a DriveBase and perform basic movements like driving straight and turning. ### Request Example ```python from pybricks.pupdevices import Motor from pybricks.parameters import Port, Direction from pybricks.robotics import DriveBase left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.B) drive_base = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112) # Drive forward by 500mm drive_base.straight(500) # Turn around clockwise by 180 degrees drive_base.turn(180) ``` ``` -------------------------------- ### Turn Light On and Off Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/light.md This snippet demonstrates how to initialize a light device and toggle it on and off with a delay, creating a blinking effect. Ensure the Light is connected to the specified port. ```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) ``` -------------------------------- ### Build documentation on Windows Source: https://github.com/pybricks/pybricks-api/blob/master/CONTRIBUTING.md Commands to build and open the documentation using PowerShell on Windows. ```powershell # Windows (PowerShell) poetry run doc\make.bat html Invoke-Item doc\main\build\html\index.html ``` -------------------------------- ### Show an image on the EV3 screen Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/ev3brick.rst This example demonstrates how to display an image file on the EV3 brick's screen. The image file must be present on the brick. ```python from pybricks.hubs import EV3Brick from pybricks.tools import wait # Initialize the EV3 Brick b = EV3Brick() # Load and show an image b.screen.load_image("my_image.bmp") wait(5000) # Clear the screen b.screen.clear() ``` -------------------------------- ### Get Random Integer within Range (randint) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/urandom.md Use `randint(a, b)` to get a random integer N such that a <= N <= b. Both endpoints are inclusive. ```python randint(a, b) → [int](builtins.md#ubuiltins.int) Gets a random integer $N$ satisfying $a \leq N \leq b$. * **Parameters:** * **a** ([*int*](builtins.md#ubuiltins.int)) – Lowest value. This value *is* included in the range. * **b** ([*int*](builtins.md#ubuiltins.int)) – Highest value. This value *is* included in the range. * **Returns:** The random integer. ``` -------------------------------- ### help() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/builtins.md Provides information about objects or the REPL environment. ```APIDOC ## help() ### 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. ### Parameters - **object** (Any) - Optional - Object for which to print help information. ### Returns - **None** ``` -------------------------------- ### Get Random Float within Range (uniform) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/urandom.md Use `uniform(a, b)` to get a random floating-point value x such that a <= x <= b. Both endpoints are inclusive. ```python uniform(a, b) → [float](builtins.md#ubuiltins.float) Gets a random floating point value $x$ satisfying $a \leq x \leq b$. * **Parameters:** * **a** ([*float*](builtins.md#ubuiltins.float)) – Lowest value. * **b** ([*float*](builtins.md#ubuiltins.float)) – Highest value. * **Returns:** The random value. ``` -------------------------------- ### Get Random Float between 0 and 1 (random) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/urandom.md Use `random()` to get a random floating-point value x such that 0 <= x < 1. The lower bound is inclusive, and the upper bound is exclusive. ```python random() → [float](builtins.md#ubuiltins.float) Gets a random value $x$ satisfying $0 \leq x < 1$. * **Returns:** The random value. ``` -------------------------------- ### Use Surface Temperature Sensor Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/nxtdevices.rst Example demonstrating the usage of the Vernier surface temperature sensor with the NXT adapter. ```python .. literalinclude:: ../../examples/ev3/vernier_surface_temperature/main.py ``` -------------------------------- ### Method: on(brightness) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/light.md Turns on the light at a specified brightness level. ```APIDOC ## on(brightness=100) ### Description Turns on the light at the specified brightness. ### Parameters #### Request Body - **brightness** (Number) - Optional - Brightness of the light (percentage). ``` -------------------------------- ### Motor DC Control Loop Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/dcmotor.md This snippet demonstrates how to repeatedly start and stop a motor using DC power. It includes a loop that runs 10 times, with a 1-second delay between starting and stopping the motor. ```python for count in range(10): print("Counter:", count) example_motor.dc(70) wait(1000) example_motor.stop() wait(1000) ``` -------------------------------- ### ColorLightMatrix Class Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/colorlightmatrix.md Initializes the ColorLightMatrix. ```APIDOC ## ColorLightMatrix(port) ### Description Initializes the LEGO® SPIKE 3x3 Color Light Matrix. ### Parameters #### Path Parameters - **port** (Port) - Required - Port to which the device is connected. ``` -------------------------------- ### Build IDE documentation variant Source: https://github.com/pybricks/pybricks-api/blob/master/CONTRIBUTING.md Commands to build the IDE-specific documentation variant. ```bash # Linux/macOS poetry run make -C doc html TAG=ide ``` ```powershell # Windows (PowerShell) $env:TAG="ide" poetry run doc\make.bat html ``` -------------------------------- ### Running Code When Stop Button is Pressed Example Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/exceptions.md This example shows how to use a `try...except SystemExit` block to execute code when the stop button on the hub or in the Pybricks Code app is pressed. This is useful for cleanup operations. ```APIDOC ## Example: Running code when the stop button is pressed ```python from pybricks.tools import wait print("Started!") try: # Run your script here as you normally would. In this # example we just wait forever and do nothing. while True: wait(1000) except SystemExit: # This code will run when you press the stop button. # This can be useful to "clean up", such as to move # the motors back to their starting positions. print("You pressed the stop button!") ``` ``` -------------------------------- ### repr(object) Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/builtins.md Gets the string representation of an object. ```APIDOC ## repr(object) ### Description Gets the string that represents an object. ### Parameters #### Parameters - **x** (object) - Required - Object to be converted. ### Response - **Returns** (str) - String representation implemented by the object’s __repr__ method. ``` -------------------------------- ### ble.version() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/cityhub.md Gets the firmware version from the Bluetooth chip. ```APIDOC ## ble.version() ### Description Gets the firmware version from the Bluetooth chip. ### Method GET (conceptual) ### Endpoint /ble/version ### Response #### Success Response (200) - **firmware_version** (str) - The firmware version string. ### Response Example ```json { "firmware_version": "3.3.0" } ``` ``` -------------------------------- ### Displaying animated icons Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/primehub.md Demonstrates how to create a brightness-based animation on the hub display using a list of icon intensities. ```python 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) ``` -------------------------------- ### Battery Information Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/primehub.md Provides methods to get information about the battery. ```APIDOC ## battery.current() ### Description Gets the current supplied by the battery. ### Method GET ### Endpoint /battery/current ### Returns - **int** - Battery current in mA. ``` -------------------------------- ### Creating Custom Colors Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/parameters/color.md Demonstrates how to create new color instances with specific hue, saturation, and value, and how to add them to the Color class. ```APIDOC ## Making Your Own Colors ### Description This section explains how to define custom colors and add them as new constants to the `Color` class. ### Creating Instances - **Default Saturation and Value**: `my_green = Color(h=125)` (saturation and value default to 100) - **Custom Saturation and Value**: `my_dark_green = Color(h=125, s=80, v=30)` ### Adding Custom Colors Custom colors can be added as attributes to the `Color` class: ```python Color.MY_DARK_BLUE = Color(h=235, s=80, v=30) ``` ### Usage Example ```python from pybricks.parameters import Color # Print a predefined color print(Color.RED) # Access color properties print(Color.RED.h, Color.RED.s, Color.RED.v) # Create and print custom colors my_green = Color(h=125) my_dark_green = Color(h=125, s=80, v=30) print(my_dark_green) # Add and use a custom color Color.MY_DARK_BLUE = Color(h=235, s=80, v=30) print(Color.MY_DARK_BLUE) ``` ``` -------------------------------- ### GET/POST speaker.volume Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/primehub.md Gets or sets the speaker volume level. ```APIDOC ## GET/POST speaker.volume ### Description Gets or sets the speaker volume. If no volume is provided, returns the current volume. ### Parameters #### Request Body - **volume** (Number) - Optional - Volume level in the 0-100 range. ### Response #### Success Response (200) - **volume** (int) - Current volume percentage. ``` -------------------------------- ### control.stall_tolerances Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/motor.md Gets or sets the stalling tolerances for the motor controller. ```APIDOC ## control.stall_tolerances() ### Description Gets or sets stalling tolerances. If the controller cannot reach the specified speed for the given time even with maximum actuation, it is considered stalled. If no arguments are provided, it returns the current values. ### Parameters #### Request Body - **speed** (Number) - Optional - Minimum speed threshold (deg/s or mm/s). - **time** (Number) - Optional - Duration the controller must be below the speed threshold to trigger a stall (ms). ### Response #### Success Response (200) - **Tuple[int, int]** - Returns the current stall speed and time tolerances. ``` -------------------------------- ### Observe Data From Other Hubs Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/cityhub.md Demonstrates how to observe broadcasted data from another hub and use it to control motors and lights. The hub needs to be initialized with observe channels. ```default from pybricks.hubs import CityHub from pybricks.pupdevices import Motor from pybricks.parameters import Color, Port from pybricks.tools import wait # Initialize the hub. hub = CityHub(observe_channels=[1]) # Initialize the motors. left_motor = Motor(Port.A) right_motor = Motor(Port.B) while True: # Receive broadcast from the other hub. data = hub.ble.observe(1) if data is None: # No data has been received in the last 1 second. hub.light.on(Color.RED) else: # Data was received and is less that one second old. hub.light.on(Color.GREEN) # *data* contains the same values in the same order # that were passed to hub.ble.broadcast() on the # other hub. left_angle, right_angle = data # Make the motors on this hub mirror the position of the # motors on the other hub. left_motor.track_target(left_angle) right_motor.track_target(right_angle) # Broadcasts are only sent every 100 milliseconds, so there is # no reason to call the observe() method more often than that. wait(100) ``` -------------------------------- ### GET dpad() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/iodevices/xboxcontroller.md Retrieves the current direction-pad value as an integer. ```APIDOC ## GET dpad() ### Description Gets the direction-pad value. This method returns a number indicating the direction currently pressed. ### Response #### Success Response (200) - **value** (int) - Direction-pad position: 1 (up), 2 (up-right), 3 (right), 4 (down-right), 5 (down), 6 (down-left), 7 (left), 8 (up-left), 0 (not pressed). ``` -------------------------------- ### system.info() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/cityhub.md Retrieves information about the Pybricks hub. ```APIDOC ## system.info() ### Description Gets information about the hub as a dictionary. ### Method GET ### Endpoint /system/info ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (dict) - A dictionary containing system information with the following keys: - "name" (str): The hub name. - "reset_reason" (int): The reason for the hub's last reset (0: normal, 1: automatic reboot, 2: crash). - "host_connected_ble" (bool): True if connected via Bluetooth, False otherwise. - "program_start_type" (int): The type of program start (1: auto on power, 2: hub buttons, 3: connected computer). #### Response Example { "info": { "name": "Hub Name", "reset_reason": 0, "host_connected_ble": true, "program_start_type": 1 } } ``` -------------------------------- ### GET battery.current() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/cityhub.md Retrieves the current supplied by the battery in milliamperes. ```APIDOC ## GET battery.current() ### Description Gets the current supplied by the battery. ### Method GET ### Endpoint battery.current() ### Response #### Success Response (200) - **current** (int) - Battery current in mA. ``` -------------------------------- ### Implement an EV3 Bluetooth server Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/messaging.rst Use the BluetoothMailboxServer class to initiate a server that waits for incoming client connections. ```python from pybricks.messaging import BluetoothMailboxServer, TextMailbox # Initialize the server server = BluetoothMailboxServer() # Wait for a client to connect server.wait_for_connection() # Create a mailbox for communication mailbox = TextMailbox('greeting', server) # Wait for a message mailbox.wait() print(mailbox.read()) ``` -------------------------------- ### System Information Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/primehub.md Provides methods to get information about the system and hub. ```APIDOC ## system.info() ### Description Gets information about the hub as a dictionary. ### Method GET ### Endpoint /system/info ### Returns - **dict** - A dictionary with system info. Keys include: - `"name"` (string): The hub name. - `"reset_reason"` (int): Why the hub (re)booted (0: normal, 1: auto-reset, 2: crash). - `"host_connected_ble"` (bool): `True` if connected via Bluetooth. - `"program_start_type"` (int): How the program started (1: auto on power, 2: hub buttons, 3: computer). ``` -------------------------------- ### EssentialHub Initialization Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/essentialhub.md Initializes the LEGO SPIKE Essential Hub with orientation and communication settings. ```APIDOC ## EssentialHub Initialization ### Description Initializes the hub. Optionally, specify how the hub is placed in your design by saying in which direction the top side (with the button) and the front side (with the USB port, and I/O ports A and B) are pointing. ### Parameters - **top_side** (Axis) - Optional - The axis that passes through the top side of the hub. - **front_side** (Axis) - Optional - The axis that passes through the front side of the hub. - **broadcast_channel** (int) - Optional - Channel number (0 to 255) used to broadcast data. Choose 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. ``` -------------------------------- ### Driving straight and turning with a DriveBase Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/robotics.md Demonstrates initializing motors and a DriveBase to perform straight movements and rotations. The example includes optional gyro configuration for improved accuracy. ```default from pybricks.pupdevices import Motor from pybricks.parameters import Port, Direction from pybricks.robotics import DriveBase # Initialize both motors. In this example, the motor on the # left must turn counterclockwise to make the robot go forward. left_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.B) # Initialize the drive base. In this example, the wheel diameter is 56mm. # The distance between the two wheel-ground contact points is 112mm. drive_base = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=112) # Optionally, uncomment the line below to use the gyro for improved accuracy. # drive_base.use_gyro(True) # Drive forward by 500mm (half a meter). drive_base.straight(500) # Turn around clockwise by 180 degrees. drive_base.turn(180) # Drive forward again to get back to the start. drive_base.straight(500) # Turn around counterclockwise. drive_base.turn(-180) ``` -------------------------------- ### control.target_tolerances Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/motor.md Gets or sets the tolerances that determine when a maneuver is considered complete. ```APIDOC ## control.target_tolerances() ### Description Gets or sets the tolerances that define when a maneuver is done. If no arguments are provided, it returns the current values. ### Parameters #### Request Body - **speed** (Number) - Optional - Allowed deviation from zero speed before motion is considered complete (deg/s or mm/s). - **position** (Number) - Optional - Allowed deviation from the target before motion is considered complete (deg or mm). ### Response #### Success Response (200) - **Tuple[int, int]** - Returns the current speed and position tolerances. ``` -------------------------------- ### GET angle() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/motor.md Retrieves the current rotation angle of the motor in degrees. ```APIDOC ## GET angle() ### Description Gets the rotation angle of the motor. ### Response #### Success Response (200) - **angle** (int) - The rotation angle of the motor in degrees. ``` -------------------------------- ### system.info() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/movehub.md Retrieves information about the hub as a dictionary. ```APIDOC ## system.info() ### Description Gets information about the hub as a dictionary. ### Returns - **dict** - A dictionary containing the following keys: - "name" (str): The hub name. - "reset_reason" (int): Why the hub (re)booted (0: normal, 1: auto-reboot, 2: watchdog timeout). - "host_connected_ble" (bool): True if connected via Bluetooth, False otherwise. - "program_start_type" (int): How the program started (1: power on, 2: hub buttons, 3: connected computer). ``` -------------------------------- ### PUPDevice Class Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/iodevices/pupdevice.md Initializes a connection to a Powered Up device on a specific port. ```APIDOC ## class PUPDevice(port) ### Description Represents a Powered Up motor or sensor connected to a specific port. ### Parameters #### Path Parameters - **port** (Port) - Required - The port to which the device is connected. ``` -------------------------------- ### GET imu.heading() Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/technichub.md Retrieves the current heading angle of the robot in degrees. ```APIDOC ## GET imu.heading() ### Description Gets the heading angle of your robot. A positive value indicates a clockwise turn. The heading is initialized to 0 when the program starts and continues to grow beyond 180 degrees without wrapping. ### Returns - **float** - The heading angle in degrees. ``` -------------------------------- ### LWP3Device Class Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/iodevices/lwp3device.md Initializes a connection to a LEGO hub using the LEGO Wireless Protocol v3. ```APIDOC ## class LWP3Device ### Description Connects to a hub running official LEGO firmware using the LEGO Wireless Protocol v3. ### 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. - **pair** (bool) - Optional - Whether to attempt pairing for a secure connection. - **num_notifications** (int) - Optional - Number of incoming messages to store. ``` -------------------------------- ### ble.signal_strength Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/hubs/movehub.md Gets the average signal strength in dBm for the given channel. ```APIDOC ## GET ble.signal_strength ### Description Gets the average signal strength in dBm for the given channel. This indicates how near the broadcasting device is. ### Method GET ### Endpoint ble.signal_strength(channel) ### Parameters #### Path Parameters - **channel** (int) - Required - The channel number (0 to 255). ### Response #### Success Response (200) - **strength** (int) - The signal strength in dBm or -128 if there is no recent observed data. ``` -------------------------------- ### Accessing System and MicroPython Version Details Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/micropython/usys.md Retrieves detailed system implementation, version, and version_info tuples. ```python import usys # ('micropython', (1, 19, 1), 'SPIKE Essential Hub with STM32F413RG', 6) print(usys.implementation) # '3.4.0; Pybricks MicroPython v3.2.0b5 on 2022-11-11' print(usys.version) # (3, 4, 0) print(usys.version_info) ``` -------------------------------- ### Measuring color with ColorDistanceSensor Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/colordistancesensor.md Demonstrates how to initialize the sensor and continuously read and print the detected color. ```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) ``` -------------------------------- ### GET /sensors/infrared/count Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/infraredsensor.md Counts the number of objects that have passed by the infrared sensor. ```APIDOC ## GET /sensors/infrared/count ### Description Counts the number of objects that have passed by the sensor. ### Method GET ### Response #### Success Response (200) - **count** (int) - Number of objects counted. ``` -------------------------------- ### Initialize and Use PrimeHub Source: https://context7.com/pybricks/pybricks-api/llms.txt Initializes the PrimeHub with custom orientation and accesses its features like battery, buttons, and status light. Requires importing necessary modules. ```python from pybricks.hubs import PrimeHub from pybricks.parameters import Axis, Button from pybricks.tools import wait # Initialize the hub with custom orientation settings hub = PrimeHub(top_side=Axis.Z, front_side=Axis.X) # Access hub features print("Battery voltage:", hub.battery.voltage(), "mV") print("Battery current:", hub.battery.current(), "mA") # Check button presses pressed = hub.buttons.pressed() if Button.CENTER in pressed: print("Center button is pressed!") # Control the status light hub.light.on(Color.GREEN) wait(1000) hub.light.off() ``` -------------------------------- ### GET /sensors/infrared/reflection Source: https://github.com/pybricks/pybricks-api/blob/master/doc/main/pupdevices/infraredsensor.md Measures the reflection of a surface using the infrared sensor. ```APIDOC ## GET /sensors/infrared/reflection ### Description Measures the reflection of a surface using an infrared light. ### Method GET ### Response #### Success Response (200) - **reflection** (int) - Measured reflection, ranging from 0% (no reflection) to 100% (high reflection). ```