### Hello World! Example Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md A basic example to get started with the Sphero Edu API, setting the robot's main LED and moving it. ```APIDOC ## Hello World! Example ### Description This example demonstrates a basic script to connect to a Sphero robot, set its main LED color to blue, and make it move forward for 2 seconds before stopping. ### Method N/A (Python Script) ### Endpoint N/A (Local Script Execution) ### Parameters N/A ### Request Example ```python import time from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as droid: droid.set_main_led(Color(r=0, g=0, b=255)) droid.set_speed(60) time.sleep(2) droid.set_speed(0) ``` ### Response N/A (Script execution) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Install Spherov2 and Bleak Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Install the spherov2 library and the bleak library for Bluetooth communication. ```bash pip install spherov2 pip install bleak # Required for Bluetooth communication ``` -------------------------------- ### Installation Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Install the Spherov2 library and its dependency, bleak, using pip. ```APIDOC ## Installation ```bash pip install spherov2 pip install bleak # Required for Bluetooth communication ``` ``` -------------------------------- ### Start TCP Server Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/adapter.md This command starts the TCP server, which acts as a relay for Bluetooth packets. The host and port are optional and default to '0.0.0.0' and 50004 respectively. ```bash python -m spherov2.adapter.tcp_server [host] [port] ``` -------------------------------- ### Start TCP Server for Remote Control Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Starts the TCP server for remote Bluetooth relay. Can be run on default host/port or custom ones. ```bash # Start server on default host (0.0.0.0) and port (50004) python -m spherov2.adapter.tcp_server # Start server on custom host and port python -m spherov2.adapter.tcp_server 192.168.1.100 50005 ``` -------------------------------- ### Example Gyro Max Event Handler Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Example of an event handler for on_gyro_max that changes the main LED to red and prints 'gyromax'. Requires `Color` and `EventType` to be defined. ```python def on_gyro_max(api): api.set_main_led(Color(255, 0, 0)) print('gyromax') api.register_event(EventType.on_gyro_max, on_gyro_max) api.set_stabilization(False) api.set_back_led(255) api.set_main_led(Color(255, 255, 255)) ``` -------------------------------- ### IR Broadcast and Follow Example Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Demonstrates IR communication for Sphero BOLT. One robot broadcasts its presence on specified channels, while another follows. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI import time # Robot 1 - Broadcaster bolt1 = scanner.find_BOLT(toy_name="SB-1234") with SpheroEduAPI(bolt1) as broadcaster: # Broadcast on channels 0 (near) and 1 (far) broadcaster.start_ir_broadcast(near=0, far=1) # Move around - followers will track this robot broadcaster.roll(0, 100, 5) broadcaster.roll(90, 100, 5) broadcaster.stop_ir_broadcast() # Robot 2 - Follower (run in separate script) bolt2 = scanner.find_BOLT(toy_name="SB-5678") with SpheroEduAPI(bolt2) as follower: # Follow robot broadcasting on channels 0 and 1 follower.start_ir_follow(near=0, far=1) time.sleep(30) follower.stop_ir_follow() ``` -------------------------------- ### Find Toy using TCPAdapter Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/README.md Connect to a Sphero toy via a TCP connection, useful for relaying Bluetooth packets to another host. The TCP server can be started with `python -m spherov2.adapter.tcp_server [host] [port]`. Requires `pip install bleak`. ```python from spherov2 import scanner from spherov2.adapter.tcp_adapter import get_tcp_adapter with scanner.find_toy(adapter=get_tcp_adapter('localhost')) as toy: ... ``` -------------------------------- ### Handle Robot Landing Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Example of handling a robot landing by changing the main LED to green and printing 'land'. Ensure the EventType enum and Color class are imported. ```python def on_landing(api): api.set_main_led(Color(0, 255, 0)) print('land') api.register_event(EventType.on_landing, on_landing) api.set_main_led(Color(255, 255, 255)) ``` -------------------------------- ### Example Charging and Not Charging Events Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Demonstrates separate event handlers for charging and not charging states, including LED changes and print statements. Requires `Color`, `EventType`, and `time` module. ```python def on_charging(api): api.set_main_led(Color(6, 0, 255)) print('charging') time.sleep(1) print('remove me from my charger') api.register_event(EventType.on_charging, on_charging) def on_not_charging(api): api.set_main_led(Color(255, 0, 47)) print('not charging') api.register_event(EventType.on_not_charging, on_not_charging) print('place me in my charger') while True: api.set_main_led(Color(3, 255, 0)) time.sleep(0.5) ``` -------------------------------- ### Handle Robot Freefall Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Example of handling freefall by changing the main LED to red and printing 'freefall'. Ensure the EventType enum and Color class are imported. ```python def on_freefall(api): api.set_main_led(Color(255, 0, 0)) print('freefall') api.register_event(EventType.on_freefall, on_freefall) api.set_main_led(Color(255, 255, 255)) ``` -------------------------------- ### Basic SpheroEduAPI Usage Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Basic example of connecting to a Sphero toy and controlling its main LED and speed. Requires importing time, scanner, SpheroEduAPI, and Color. ```python import time from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as droid: # Set LED color droid.set_main_led(Color(r=0, g=0, b=255)) # Move forward droid.set_speed(60) time.sleep(2) # Stop droid.set_speed(0) ``` -------------------------------- ### Find Toy with BleakAdapter Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/adapter.md This snippet shows the default usage of BleakAdapter, which is automatically used by the scanner to find a toy. Ensure you have a Bluetooth 4.0+ adapter and have installed the bleak library. ```python from spherov2 import scanner with scanner.find_toy() as toy: ... ``` -------------------------------- ### Autonomous Navigation with Collision Detection Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt This example demonstrates autonomous robot navigation using collision detection and sensor feedback. It requires importing necessary modules and defining a class to handle robot behavior. ```python import time from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI, EventType from spherov2.types import Color class AutonomousRobot: def __init__(self, api): self.api = api self.collision_count = 0 def on_collision(self, api): self.collision_count += 1 api.stop_roll() api.set_main_led(Color(255, 0, 0)) print(f"Collision #{self.collision_count}") # Back up and turn api.roll(api.get_heading() + 180, 100, 0.5) api.set_heading(api.get_heading() + 90) api.set_main_led(Color(0, 255, 0)) def main(): toy = scanner.find_toy() with SpheroEduAPI(toy) as api: robot = AutonomousRobot(api) api.register_event(EventType.on_collision, robot.on_collision) # Initial setup api.reset_aim() api.set_main_led(Color(0, 255, 0)) # Autonomous exploration print("Starting autonomous exploration...") api.set_speed(80) start_time = time.time() while time.time() - start_time < 60: # Run for 60 seconds # Read sensors location = api.get_location() distance = api.get_distance() if location: print(f"Position: ({location['x']:.1f}, {location['y']:.1f}) cm, " f"Total distance: {distance:.1f} cm") time.sleep(1) api.stop_roll() api.set_main_led(Color(0, 0, 255)) print(f"Exploration complete! Collisions: {robot.collision_count}") if __name__ == "__main__": main() ``` -------------------------------- ### Read Location and Velocity Data Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Reads location and velocity data after initiating movement. Location is relative to the start point in cm, and velocity is in cm/s. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI import time toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Roll forward api.roll(0, 100, 2) # Get location relative to start (x, y) in cm location = api.get_location() print(f"Location: x={location['x']}cm, y={location['y']}cm") # Get velocity (x, y) in cm/s velocity = api.get_velocity() print(f"Velocity: x={velocity['x']}cm/s, y={velocity['y']}cm/s") # Get total distance traveled in cm distance = api.get_distance() print(f"Total distance: {distance}cm") # Get current target speed and heading speed = api.get_speed() heading = api.get_heading() print(f"Speed: {speed}, Heading: {heading}") ``` -------------------------------- ### Interact with Sphero Toy using SpheroEduAPI Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/README.md Utilize the high-level SpheroEduAPI for interacting with Sphero toys, implementing official Sphero Edu APIs. This example demonstrates spinning the toy. Ensure the toy is found using `scanner.find_toy()`. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: api.spin(360, 1) ``` -------------------------------- ### IR Messaging Example Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Enables sending and receiving IR messages between Sphero BOLT robots on a specific channel. The receiver changes LED color upon message detection. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI, EventType from spherov2.types import Color import time # Receiver robot def on_ir_message(api, channel): if channel == 4: api.set_main_led(Color(255, 0, 0)) print(f"Received message on channel {channel}") api.listen_for_ir_message((4,)) # Re-listen bolt = scanner.find_BOLT() with SpheroEduAPI(bolt) as api: api.register_event(EventType.on_ir_message, on_ir_message) api.listen_for_ir_message((4,)) # Listen on channel 4 time.sleep(30) # Sender robot (run in separate script) bolt_sender = scanner.find_BOLT(toy_name="SB-SENDER") with SpheroEduAPI(bolt_sender) as sender: # Send message on channel 4, intensity 5 sender.send_ir_message(channel=4, intensity=5) ``` -------------------------------- ### Handle Robot Collisions Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Example of handling robot collisions by stopping movement, changing LED color, printing a message, and reversing direction. Ensure the EventType enum is imported. ```python def on_collision(api): api.stop_roll() api.set_main_led(Color(255, 0, 0)) print('Collision') api.set_heading(api.get_heading() + 180) time.sleep(0.5) api.set_main_led(Color(255, 22, 255)) api.set_speed(100) api.register_event(EventType.on_collision, on_collision) api.set_main_led(Color(255, 255, 255)) api.set_speed(100) ``` -------------------------------- ### Register Charging Events Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Executes functions when the robot starts or stops charging. The robot's main LED changes color based on charging status. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI, EventType from spherov2.types import Color import time def on_charging(api): api.set_main_led(Color(0, 0, 255)) print("Charging started") def on_not_charging(api): api.set_main_led(Color(255, 0, 0)) print("Charging stopped") toy = scanner.find_toy() with SpheroEduAPI(toy) as api: api.register_event(EventType.on_charging, on_charging) api.register_event(EventType.on_not_charging, on_not_charging) print("Place robot in charger to trigger events...") while True: api.set_main_led(Color(0, 255, 0)) time.sleep(0.5) ``` -------------------------------- ### Set Front LED Color (R2-D2/R2-Q5) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Changes the color of the front LED light using RGB values on a scale of 0-255. For example, fuchsia is `Color(232, 0, 255)`. ```python set_front_led(Color(232, 0, 255)) ``` -------------------------------- ### Use TCP Adapter for Remote Toy Control Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Connects to a Sphero toy via a remote TCP relay server. Requires getting the TCP adapter and then finding the toy using it. ```python from spherov2 import scanner from spherov2.adapter.tcp_adapter import get_tcp_adapter from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color # Get TCP adapter for remote host TCPAdapter = get_tcp_adapter('192.168.1.100', 50004) # Find and connect to toy via TCP relay toy = scanner.find_toy(adapter=TCPAdapter) with SpheroEduAPI(toy) as api: api.set_main_led(Color(r=0, g=255, b=0)) api.roll(90, 100, 2) # Roll right at speed 100 for 2 seconds ``` -------------------------------- ### Draw Line on BOLT Matrix Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Use `set_matrix_line` to draw a line between two points on BOLT's LED matrix. Specify start and end coordinates and the desired `Color`. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_BOLT() with SpheroEduAPI(toy) as api: # Draw vertical line from (1,0) to (1,7) api.set_matrix_line(1, 0, 1, 7, Color(r=255, g=0, b=255)) # Draw horizontal line api.set_matrix_line(0, 4, 7, 4, Color(r=0, g=255, b=0)) ``` -------------------------------- ### Set Front LED Color (BOLT/RVR) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Changes the color of the front LED light using RGB values on a scale of 0-255. For example, magenta is `Color(239, 0, 255)`. ```python set_front_led(Color(239, 0, 255)) ``` -------------------------------- ### Set Back LED Color (BOLT/RVR) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Changes the color of the back LED light using RGB values on a scale of 0-255. For example, green is `Color(0, 255, 0)`. ```python set_back_led(Color(0, 255, 0)) ``` -------------------------------- ### Hello World with Sphero Edu API Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Connect to a Sphero robot, set its main LED to blue, and make it move for 2 seconds. Ensure your robot is aimed correctly before running. ```python import time from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as droid: droid.set_main_led(Color(r=0, g=0, b=255)) droid.set_speed(60) time.sleep(2) droid.set_speed(0) ``` -------------------------------- ### Set Front LED Color Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Set the front LED color on supported robots (BOLT, R2-D2, R2-Q5, RVR). Requires importing scanner, SpheroEduAPI, and Color. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_BOLT() # or find_R2D2(), find_RVR() with SpheroEduAPI(toy) as api: # Set front LED to magenta api.set_front_led(Color(r=239, g=0, b=255)) ``` -------------------------------- ### Handle Freefall and Landing Events Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Registers callback functions for freefall and landing events. The freefall callback sets the LED to red, and the landing callback sets it to green. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI, EventType from spherov2.types import Color import time def on_freefall(api): api.set_main_led(Color(255, 0, 0)) print("Freefall detected!") def on_landing(api): api.set_main_led(Color(0, 255, 0)) print("Landed!") toy = scanner.find_toy() with SpheroEduAPI(toy) as api: api.register_event(EventType.on_freefall, on_freefall) api.register_event(EventType.on_landing, on_landing) api.set_main_led(Color(255, 255, 255)) print("Drop the robot to trigger freefall event...") time.sleep(30) ``` -------------------------------- ### Control Back LED Brightness (Legacy) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Sets the brightness of the back aiming LED. This LED is limited to blue only, with a brightness scale from 0 to 255. Use `time.sleep()` to control the duration it stays on. ```python set_back_led(0) # Dim delay(0.33) set_back_led(255) # Bright delay(0.33) ``` -------------------------------- ### Register Charging Event Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Register a callback function to execute when the robot begins charging. ```python def on_charging(api): # code to execute on charging api.register_event(EventType.on_charging, on_charging) ``` -------------------------------- ### Set Main LED Color Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Set the main LED color using RGB values (0-255 for each channel). On BOLT, this sets the entire 8x8 matrix. Requires importing scanner, SpheroEduAPI, and Color. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Red api.set_main_led(Color(r=255, g=0, b=0)) # Green api.set_main_led(Color(r=0, g=255, b=0)) # Blue api.set_main_led(Color(r=0, g=0, b=255)) # Custom color (purple) api.set_main_led(Color(r=128, g=0, b=255)) ``` -------------------------------- ### Sounds and Animations Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt API calls for playing sounds on Star Wars droids. ```APIDOC ## Sounds and Animations ### play_sound ### Description Play built-in sounds on BB-8, BB-9E, R2-D2, and R2-Q5. ### Method `api.play_sound(sound_enum)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sound_enum** (Enum) - An enum value representing the sound to play (e.g., `R2D2.Audio.R2_BURNOUT`). Available sounds depend on the toy type. ### Request Example ```python api.play_sound(R2D2.Audio.R2_BURNOUT) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Register On Landing Event Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Register a callback function to execute when the robot lands after being in freefall. This event can be triggered without explicitly defining an on_freefall event. ```python def on_landing(api): # code to execute on landing api.register_event(EventType.on_landing, on_landing) ``` -------------------------------- ### Set Persistent Speed and Heading Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Set persistent speed and heading values that remain until changed. Requires importing scanner, SpheroEduAPI, and time. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI import time toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Set heading to 45 degrees api.set_heading(45) # Set speed (persists until changed) api.set_speed(100) time.sleep(2) # Change direction while moving api.set_heading(135) time.sleep(2) # Stop the robot api.stop_roll() ``` -------------------------------- ### Fade Main LED Color Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Gradually transition the main LED from one color to another over a specified duration. Requires importing scanner, SpheroEduAPI, and Color. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Fade from green to blue over 3 seconds api.fade(Color(0, 255, 0), Color(0, 0, 255), 3.0) # Fade from red to yellow over 2 seconds api.fade(Color(255, 0, 0), Color(255, 255, 0), 2.0) ``` -------------------------------- ### LED Control API Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Control the robot's LED lights, including the main LED, back LED, and front LED. ```APIDOC ## POST /api/led/set_main_led ### Description Sets the main LED color using RGB values. ### Method POST ### Endpoint /api/led/set_main_led ### Parameters #### Request Body - **color** (object) - Required - An object containing RGB values. - **r** (integer) - Required - Red component (0-255). - **g** (integer) - Required - Green component (0-255). - **b** (integer) - Required - Blue component (0-255). ### Request Example ```json { "color": { "r": 255, "g": 0, "b": 0 } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Main LED set successfully" } ``` ## POST /api/led/set_back_led ### Description Sets the back aiming LED color or brightness. ### Method POST ### Endpoint /api/led/set_back_led ### Parameters #### Request Body - **color_or_brightness** (object or integer) - Required - For BOLT/R2/RVR, an object with RGB values. For older Spheros, an integer brightness (0-255). - If object: **r**, **g**, **b** (integers 0-255). - If integer: Brightness value (0-255). ### Request Example (RGB) ```json { "color_or_brightness": { "r": 255, "g": 0, "b": 0 } } ``` ### Request Example (Brightness) ```json { "color_or_brightness": 255 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Back LED set successfully" } ``` ## POST /api/led/set_front_led ### Description Sets the front LED color on supported robots. ### Method POST ### Endpoint /api/led/set_front_led ### Parameters #### Request Body - **color** (object) - Required - An object containing RGB values. - **r** (integer) - Required - Red component (0-255). - **g** (integer) - Required - Green component (0-255). - **b** (integer) - Required - Blue component (0-255). ### Request Example ```json { "color": { "r": 239, "g": 0, "b": 255 } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Front LED set successfully" } ``` ## POST /api/led/fade ### Description Gradually transitions the main LED from one color to another over a specified duration. ### Method POST ### Endpoint /api/led/fade ### Parameters #### Request Body - **start_color** (object) - Required - The starting RGB color. - **r**, **g**, **b** (integers 0-255). - **end_color** (object) - Required - The ending RGB color. - **r**, **g**, **b** (integers 0-255). - **duration** (float) - Required - The duration in seconds for the fade. ### Request Example ```json { "start_color": {"r": 0, "g": 255, "b": 0}, "end_color": {"r": 0, "g": 0, "b": 255}, "duration": 3.0 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "LED fade initiated" } ``` ## POST /api/led/strobe ### Description Repeatedly blinks the main LED at a specified rate. ### Method POST ### Endpoint /api/led/strobe ### Parameters #### Request Body - **color** (object) - Required - The RGB color to strobe. - **r**, **g**, **b** (integers 0-255). - **period** (float) - Required - The time in seconds for one half-cycle of the strobe. - **count** (integer) - Required - The number of times to blink. ### Request Example ```json { "color": {"r": 255, "g": 0, "b": 0}, "period": 0.1, "count": 15 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "LED strobe initiated" } ``` ``` -------------------------------- ### Movement Commands Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Control robot motors, heading, and stabilization. ```APIDOC ## Movement Commands ### roll Combines heading, speed, and duration to make the robot roll in a single command. Heading is 0-360 degrees, speed is -255 to 255. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Roll forward at speed 200 for 2 seconds api.roll(0, 200, 2) # Roll right at speed 150 for 1.5 seconds api.roll(90, 150, 1.5) # Roll backward at speed 100 for 1 second api.roll(180, 100, 1) # Roll left at speed 50 for 3 seconds api.roll(270, 50, 3) ``` ``` -------------------------------- ### Spin Robot In Place Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Spin the robot in place for a specified angle over a duration. Requires importing scanner and SpheroEduAPI. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Spin 360 degrees (one full revolution) over 1 second api.spin(360, 1) # Spin counterclockwise 180 degrees over 2 seconds api.spin(-180, 2) # Spin while moving (creates arc/circle) api.set_speed(50) api.spin(720, 4) # Two full spins while moving ``` -------------------------------- ### Handle Robot Collisions Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Registers a callback function to execute when the robot collides with an object. The callback stops the robot, changes the LED to red, and turns it around. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI, EventType from spherov2.types import Color import time def on_collision(api): api.stop_roll() api.set_main_led(Color(255, 0, 0)) # Red on collision print("Collision detected!") api.set_heading(api.get_heading() + 180) # Turn around time.sleep(0.5) api.set_main_led(Color(255, 255, 255)) api.set_speed(100) toy = scanner.find_toy() with SpheroEduAPI(toy) as api: api.register_event(EventType.on_collision, on_collision) api.set_main_led(Color(255, 255, 255)) api.set_speed(100) # Keep program running time.sleep(30) ``` -------------------------------- ### Set Back LED Color/Brightness Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Set the back aiming LED (tail light). On older Spheros, this is brightness only (0-255). On BOLT/R2/RVR, this accepts RGB colors. Requires importing scanner, SpheroEduAPI, Color, and time. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color import time toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # For classic Sphero - brightness only (0-255) api.set_back_led(255) # Full brightness time.sleep(1) api.set_back_led(0) # Off # For BOLT/R2D2/R2Q5/RVR - full RGB api.set_back_led(Color(r=255, g=0, b=0)) ``` -------------------------------- ### Read Acceleration and Orientation Data Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Reads acceleration and orientation data from the robot. Ensure sensors are initialized with a short delay before reading. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI import time toy = scanner.find_toy() with SpheroEduAPI(toy) as api: time.sleep(0.5) # Allow sensors to initialize # Get acceleration (x, y, z) in g's (-8 to 8) accel = api.get_acceleration() print(f"Acceleration: x={accel['x']}, y={accel['y']}, z={accel['z']}") # Get vertical acceleration regardless of orientation vert_accel = api.get_vertical_acceleration() print(f"Vertical acceleration: {vert_accel}") # Get orientation (pitch, roll, yaw) in degrees orientation = api.get_orientation() print(f"Orientation: pitch={orientation['pitch']}, roll={orientation['roll']}, yaw={orientation['yaw']}") # Get gyroscope data (rotation rate in degrees/second) gyro = api.get_gyroscope() print(f"Gyroscope: pitch={gyro['pitch']}, roll={gyro['roll']}, yaw={gyro['yaw']}") ``` -------------------------------- ### Control BB-9E Dome LEDs Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Adjust the brightness of BB-9E's dome LEDs using `set_dome_leds`. The brightness value ranges from 0 to 15. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_BB9E() with SpheroEduAPI(toy) as api: # Set dome LEDs brightness (0-15) api.set_dome_leds(15) # Full brightness # Dim dome LEDs api.set_dome_leds(5) ``` -------------------------------- ### Register On Freefall Event Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Register a callback function to execute when the robot is in freefall. Freefall is detected by accelerometer readings below 0.1g for at least 0.1 seconds. ```python def on_freefall(api): # code to execute on freefall api.register_event(EventType.on_freefall, on_freefall) ``` -------------------------------- ### Reset Heading Calibration Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Resets the heading calibration to use the current direction as 0 degrees. Requires importing scanner and SpheroEduAPI. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Reset aim so current direction becomes 0 degrees api.reset_aim() # Now 0 degrees is forward from current position api.roll(0, 100, 2) ``` -------------------------------- ### Enable or Disable Stabilization Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Enable or disable the robot's stabilization system (IMU-based balance control). Requires importing scanner and SpheroEduAPI. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Disable stabilization for manual control api.set_stabilization(False) # Now raw_motor commands won't be auto-balanced api.raw_motor(100, 100, 1) # Re-enable stabilization api.set_stabilization(True) ``` -------------------------------- ### Scanner - Finding Toys Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Functions for discovering and connecting to Sphero robots via Bluetooth. ```APIDOC ## Scanner - Finding Toys ### find_toy Finds a single Sphero toy matching the specified criteria. Returns the first toy found or raises `ToyNotFoundError` if none are available. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI # Find any available Sphero toy toy = scanner.find_toy() # Find a specific toy by name toy = scanner.find_toy(toy_name="SB-1234") # Find with custom timeout (seconds) toy = scanner.find_toy(timeout=10.0) # Connect and use the toy with SpheroEduAPI(toy) as api: api.set_main_led(Color(r=255, g=0, b=0)) ``` ### find_toys Finds all Sphero toys matching the specified criteria. Returns a list of discovered toys. ```python from spherov2 import scanner from spherov2.toy.bolt import BOLT from spherov2.toy.mini import Mini # Find all available toys toys = scanner.find_toys(timeout=5.0) print(f"Found {len(toys)} toys") # Find only specific toy types bolts = scanner.find_toys(toy_types=[BOLT]) minis = scanner.find_toys(toy_types=[Mini]) # Find specific toys by name specific_toys = scanner.find_toys(toy_names=["SB-1234", "SB-5678"]) ``` ### Type-Specific Finders Convenience functions to find specific Sphero models. ```python from spherov2 import scanner # Find specific toy types bolt = scanner.find_BOLT() mini = scanner.find_Mini() bb8 = scanner.find_BB8() bb9e = scanner.find_BB9E() r2d2 = scanner.find_R2D2() r2q5 = scanner.find_R2Q5() rvr = scanner.find_RVR() sphero = scanner.find_Sphero() ollie = scanner.find_Ollie() sprk2 = scanner.find_Sprk2() ``` ``` -------------------------------- ### Set Back LED (Legacy) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Controls the brightness of the back aiming LED (Tail Light), which is limited to blue only. ```APIDOC ## Set Back LED (Legacy) ### Description Sets the brightness of the back aiming LED, also known as the "Tail Light." This LED is limited to blue only, with a brightness scale from 0 to 255. ### Method N/A (Python Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Example for setting back LED brightness # set_back_led(0) # Dim # delay(0.33) # set_back_led(255) # Bright # delay(0.33) ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### TCP Adapter - Remote Bluetooth Relay Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Control Sphero toys connected to a remote host via a relay server. ```APIDOC ## TCP Adapter - Remote Bluetooth Relay ### Starting the TCP Server ```bash # Start server on default host (0.0.0.0) and port (50004) python -m spherov2.adapter.tcp_server # Start server on custom host and port python -m spherov2.adapter.tcp_server 192.168.1.100 50005 ``` ### Using TCP Adapter ```python from spherov2 import scanner from spherov2.adapter.tcp_adapter import get_tcp_adapter from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color # Get TCP adapter for remote host TCPAdapter = get_tcp_adapter('192.168.1.100', 50004) # Find and connect to toy via TCP relay toy = scanner.find_toy(adapter=TCPAdapter) with SpheroEduAPI(toy) as api: api.set_main_led(Color(r=0, g=255, b=0)) api.roll(90, 100, 2) # Roll right at speed 100 for 2 seconds ``` ``` -------------------------------- ### Register Not Charging Event Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Register a callback function to execute when the robot stops charging. ```python def on_not_charging(api): # code to execute on not charging api.register_event(EventType.on_not_charging, on_not_charging) ``` -------------------------------- ### Direct Motor Control with Raw Motor Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Direct motor control for advanced movements like jumping. Disables stabilization automatically. Requires importing scanner and SpheroEduAPI. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Full power to both motors for 0.5s (robot will jump!) api.raw_motor(255, 255, 0.5) # Spin in place by setting opposite motor directions api.raw_motor(100, -100, 1) # Curve by setting different speeds api.raw_motor(200, 100, 2) ``` -------------------------------- ### Play Built-in Animations on R2-D2 Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Use this to play pre-defined animations on R2-D2 droids. Animations are specific to droid types and accessed via the toy_class.Animations enum. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.toy.r2d2 import R2D2 toy = scanner.find_R2D2() with SpheroEduAPI(toy) as api: # Play charger animation api.play_animation(R2D2.Animations.CHARGER_1) # Animations are unique to each droid type # Access via toy_class.Animations enum ``` -------------------------------- ### Set Front LED (Sphero BOLT, RVR, BB-9E, R2-D2 & R2-Q5) Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Changes the color of the front LED light(s) using RGB values. ```APIDOC ## Set Front LED ### Description Changes the color of the front LED light(s). This is applicable to Sphero BOLT, RVR, BB-9E, and R2-D2 & R2-Q5 models. Set the color using RGB (red, green, blue) values on a scale of 0 - 255. ### Method N/A (Python Function Call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Example for Sphero BOLT, RVR, BB-9E, R2-D2 & R2-Q5 # For magenta color on Sphero BOLT/RVR/BB-9E: # set_front_led(Color(r=239, g=0, b=255)) # For fuchsia color on R2-D2 & R2-Q5: # set_front_led(Color(r=232, g=0, b=255)) ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Strobe Main LED Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Repeatedly blink the main LED at a specified rate. Requires importing scanner, SpheroEduAPI, and Color. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI from spherov2.types import Color toy = scanner.find_toy() with SpheroEduAPI(toy) as api: # Strobe red 15 times over 3 seconds period = (3 / 15) * 0.5 api.strobe(Color(255, 0, 0), period, 15) # Fast blue strobe api.strobe(Color(0, 0, 255), 0.05, 20) ``` -------------------------------- ### Read BOLT Sensor Data Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Reads luminosity and compass data from a BOLT robot. Calibrate the compass before reading its direction. Luminosity is in lux. ```python from spherov2 import scanner from spherov2.sphero_edu import SpheroEduAPI import time toy = scanner.find_BOLT() with SpheroEduAPI(toy) as api: time.sleep(0.5) # Get ambient light level (0-100,000 lux) luminosity = api.get_luminosity() print(f"Light level: {luminosity}") # Direct luminosity reading direct_lum = api.get_luminosity_direct() print(f"Direct light reading: {direct_lum}") # Calibrate compass before use api.calibrate_compass() # Get compass direction compass = api.get_compass_direction() print(f"Compass zero: {compass}") ``` -------------------------------- ### Find All Sphero Toys Source: https://context7.com/artificial-intelligence-class/spherov2.py/llms.txt Finds all available Sphero toys within a specified timeout. Can filter by toy types or specific names. Returns a list of discovered toys. ```python from spherov2 import scanner from spherov2.toy.bolt import BOLT from spherov2.toy.mini import Mini # Find all available toys toys = scanner.find_toys(timeout=5.0) print(f"Found {len(toys)} toys") # Find only specific toy types bolts = scanner.find_toys(toy_types=[BOLT]) minis = scanner.find_toys(toy_types=[Mini]) # Find specific toys by name specific_toys = scanner.find_toys(toy_names=["SB-1234", "SB-5678"]) ``` -------------------------------- ### Register Color Sensor Event Source: https://github.com/artificial-intelligence-class/spherov2.py/blob/main/docs/sphero_edu.md Register a callback function to execute when the robot's color sensor detects a specific RGB color. The detected color must be very close to the specified color for the event to trigger. Requires `Color` and `EventType` to be defined. ```python color = (Color(255, 15, 60), ) def on_color(api, color): if color != Color(255, 15, 60): return api.register_event(EventType.on_color, on_color) api.listen_for_color_sensor(colors) ```