Sphero Edu API

class spherov2.sphero_edu.SpheroEduAPI(toy: spherov2.toy.Toy)[source]

Implementation of Sphero Edu Javascript APIs: https://sphero.docsapp.io/docs/get-started

Get Started

Sphero robots aren’t just toys – they are programmable robots that are great for learning about computer science! This wiki is a guide to learn how to program Sphero robots with Python. You will need a Sphero robot, a Python 3 environment, and a hunger to learn.

Hello World!

Using your device with the Sphero Edu API, create a new python code file, and copy and paste these code samples into the file. Don’t forget to aim your robot, and then run the script to see what happens!

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)

Movement

Movements control the robot’s motors and control system. You can use sequential movement commands by separating them with line breaks, like the Hello World! program. Sphero robots move with three basic instructions: heading, speed, and duration. For example, if you set heading = 0°, speed = 60, duration = 3s, the robot would roll forward for 3s at a moderate speed.

class spherov2.sphero_edu.SpheroEduAPI[source]
roll(heading: int, speed: int, duration: float)[source]

Combines heading(0-360°), speed(-255-255), and duration to make the robot roll with one line of code. For example, to have the robot roll at 90°, at speed 200 for 2s, use roll(90, 200, 2)

set_speed(speed: int)[source]

Sets the speed of the robot from -255 to 255, where positive speed is forward, negative speed is backward, and 0 is stopped. Each robot type translates this value differently into a real world speed; Ollie is almost three times faster than Sphero. For example, use set_speed(188) to set the speed to 188 which persists until you set a different speed. You can also read the real-time velocity value in centimeters per second reported by the motor encoders.

stop_roll(heading: int = None)[source]

Sets the speed to zero to stop the robot, effectively the same as the set_speed(0) command.

set_heading(heading: int)[source]

Sets the direction the robot rolls. Assuming you aim the robot with the blue tail light facing you, then 0° is forward, 90° is right, 270° is left, and 180° is backward. For example, use set_heading(90) to face right.

spin(angle: int, duration: float)[source]

Spins the robot for a given number of degrees over time, with 360° being a single revolution. For example, to spin the robot 360° over 1s, use: spin(360, 1). Use set_speed() prior to spin() to have the robot move in circle or an arc or circle.

Note: Unlike official API, performance of spin is guaranteed, but may be longer than the specified duration.

set_stabilization(stabilize: bool)[source]

Turns the stabilization system on and set_stabilization(false) turns it off. Stabilization is normally on to keep the robot upright using the Inertial Measurement Unit (IMU), a combination of readings from the Accelerometer (directional acceleration), Gyroscope (rotation speed), and Encoders (location and distance). When set_stabilization(false) and you power the motors, the robot will not balance, resulting in possible unstable behaviors like wobbly driving, or even jumping if you set the power very high. Some use cases to turn it off are:

  1. Jumping: Set Motor Power to max values and the robot will jump off the ground!
  2. Gyro: Programs like the Spinning Top where you want to to isolate the Gyroscope readings rather than having the robot auto balance inside the shell.

When stabilization is off you can’t use set_speed() to set a speed because it requires the control system to be on to function. However, you can control the motors using Motor Power with raw_motor() when the control system is off.

raw_motor(left: int, right: int, duration: float)[source]

Controls the electrical power sent to the left and right motors independently, on a scale from -255 to 255 where positive is forward, negative is backward, and 0 is stopped. If you set both motors to full power the robot will jump because stabilization (use of the IMU to keep the robot upright) is disabled when using this command. This is different from set_speed() because Raw Motor sends an “Electromotive force” to the motors, whereas Set Speed is a target speed measured by the encoders. For example, to set the raw motor to full power for 4s, making the robot jump off the ground, use raw_motor(255, 255, 4).

reset_aim()[source]

Resets the heading calibration (aim) angle to use the current direction of the robot as 0°.

Sphero BOLT Movements

Sphero BOLT has a compass (magnetometer) sensor that has unique functionality. Nearby metallic and magnetic objects can affect the accuracy of the compass, so try to use this feature in an area without that interference, or hold it up in the air if you can’t get away from interference.

Star Wars Droid Movements

class spherov2.sphero_edu.SpheroEduAPI[source]
play_animation(animation: enum.IntEnum)[source]

Plays iconic Star Wars Droid animations unique to BB-8, BB-9E, R2-D2 and R2-Q5 that combine movement, lights and sound. All animation enums can be accessed under the droid class, such as R2D2.Animations.CHARGER_1.

R2-D2 & R2-Q5 Movements

The R2-D2 and R2-Q5 Droids are physically different from other Sphero robots, so there are some unique commands that only they can use.

class spherov2.sphero_edu.SpheroEduAPI[source]
set_dome_position(angle: float)[source]

Rotates the dome on its axis, from -160° to 180°. For example, set to 45° using set_dome_position(45).

set_stance(stance: spherov2.sphero_edu.Stance)[source]

Changes the stance between bipod and tripod. Set to bipod using set_stance(Stance.Bipod) and to tripod using set_stance(Stance.Tripod). Tripod is required for rolling.

set_waddle(waddle: bool)[source]

Turns the waddle walk on using set_waddle(True)` and off using set_waddle(False).

Lights

Lights control the color and brightness of LEDs on a robot.

class spherov2.sphero_edu.SpheroEduAPI[source]
set_main_led(color: spherov2.types.Color)[source]

Changes the color of the main LED light, or the full matrix on Sphero BOLT. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, set_main_led(Color(r=90, g=255, b=90)).

set_back_led(color: int)[source]

Sets the brightness of the back aiming LED, aka the “Tail Light.” This LED is limited to blue only, with a brightness scale from 0 to 255. For example, use set_back_led(255) to set the back LED to full brightness. Use time.sleep() to set it on for a duration. For example, to create a dim and a bright blink sequence use:

set_back_led(0)  # Dim
delay(0.33)
set_back_led(255)  # Bright
delay(0.33)
fade(from_color: spherov2.types.Color, to_color: spherov2.types.Color, duration: float)[source]

Changes the main LED lights from one color to another over a period of seconds. For example, to fade from green to blue over 3s, use: fade(Color(0, 255, 0), Color(0, 0, 255), 3.0).

strobe(color: spherov2.types.Color, period: float, count: int)[source]

Repeatedly blinks the main LED lights. The period is the time, in seconds, the light stays on during a single blink; cycles is the total number of blinks. The time for a single cycle is twice the period (time for a blink plus the same amount of time for the light to be off). Another way to say this is the period is 1/2 the time it takes for a single cycle. So, to strobe red 15 times in 3 seconds, use: strobe(Color(255, 57, 66), (3 / 15) * .5, 15).

Sphero BOLT Lights

Sphero BOLT has unique lighting capabilities with a front led, back led, and 8x8 led matrix. The matrix has 3 methods to program in increasing abstraction and sophistication that are very fun to play with! The 3 methods are setting pixels, text, and animations.

class spherov2.sphero_edu.SpheroEduAPI[source]
set_front_led(color: spherov2.types.Color)[source]

Changes the color of the front LED light. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the magenta color is expressed as set_front_color(Color(239, 0, 255))

set_back_led(color: spherov2.types.Color)[source]

Changes the color of the back LED light, aka the “Tail Light” or “Aim Light.” Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the green color is expressed as set_back_led(Color(0, 255, 0)). Sphero BOLT has this as an RGB LED on the back, whereas previous Spheros are limited to blue only.

Sphero RVR Lights

class spherov2.sphero_edu.SpheroEduAPI[source]
set_left_headlight_led(color: spherov2.types.Color)[source]

Changes the color of the front left headlight LED on RVR. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the pink color is expressed as set_left_headlight_led(Color(253, 159, 255)).

set_right_headlight_led(color: spherov2.types.Color)[source]

Changes the color of the front right headlight LED on RVR. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the blue color is expressed as set_right_headlight_led(0, 28, 255).

set_left_led(color: spherov2.types.Color)[source]

Changes the color of the LED on RVR’s left side (which is the side with RVR’s battery bay door). Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the green color is expressed as set_left_led(Color(0, 255, 34)).

set_right_led(color: spherov2.types.Color)[source]

Changes the color of the LED on RVR’s right side (which is the side with RVR’s power button). Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the red color is expressed as set_right_led(Color(255, 18, 0)).

set_front_led(color: spherov2.types.Color)[source]

Changes the color of RVR’s front two LED headlights together. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the magenta color is expressed as set_front_color(Color(239, 0, 255)).

set_back_led(color: spherov2.types.Color)[source]

Changes the color of the back LED light, aka the “Tail Light” or “Aim Light.” Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the above green color is expressed as set_back_led(Color(0, 255, 0)).

BB-9E Lights

class spherov2.sphero_edu.SpheroEduAPI[source]
set_dome_leds(brightness: int)[source]

Controls the brightness of the two single color LEDs (red and blue) in the dome, from 0 to 15. We don’t use 0-255 for this light because it has less granular control. For example, set them to full brightness using set_dome_leds(15).

R2-D2 & R2-Q5 Lights

class spherov2.sphero_edu.SpheroEduAPI[source]
set_front_led(color: spherov2.types.Color)[source]

Changes the color of the front LED light. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the fuchsia color is expressed as set_front_color(Color(232, 0, 255))

set_back_led(color: spherov2.types.Color)[source]

Changes the color of the back LED light. Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the above green color is expressed as set_back_led(Color(0, 255, 0)).

set_holo_projector_led(brightness: int)[source]

Changes the brightness of the Holographic Projector white LED, from 0 to 255. For example, set it to full brightness using set_holo_projector_led(255).

set_logic_display_leds(brightness: int)[source]

Changes the brightness of the Logic Display LEDs, from 0 to 255. For example, set it to full brightness using set_logic_display_leds(255).

Sounds

Control sounds and words which can play from your programming device’s speaker or the robot (R2-D2 & R2-Q5 only).

class spherov2.sphero_edu.SpheroEduAPI[source]
play_sound(sound: enum.IntEnum)[source]

Unique Star Wars Droid Sounds are available for BB-8, BB-9E and R2-D2. For example, to play the R2-D2 Burnout sound use play_sound(R2D2.Audio.R2_BURNOUT).

Sensors

Querying sensor data allows you to react to real-time values coming from the robots’ physical sensors. For example, “if accelerometer z-axis > 3G’s, then set LED’s to green.”

class spherov2.sphero_edu.SpheroEduAPI[source]
get_acceleration()[source]

Provides motion acceleration data along a given axis measured by the Accelerometer, in g’s, where g = 9.80665 m/s^2.

get_acceleration()['x'] is the left-to-right acceleration, from -8 to 8 g’s.

get_acceleration()['y'] is the forward-to-back acceleration, from of -8 to 8 g’s.

get_acceleration()['z'] is the upward-to-downward acceleration, from -8 to 8 g’s.

get_vertical_acceleration()[source]

This is the upward or downward acceleration regardless of the robot’s orientation, from -8 to 8 g’s.

get_orientation()[source]

Provides the tilt angle along a given axis measured by the Gyroscope, in degrees.

get_orientation()['pitch'] is the forward or backward tilt angle, from -180° to 180°.

get_orientation()['roll'] is left or right tilt angle, from -90° to 90°.

get_orientation()['yaw'] is the spin (twist) angle, from -180° to 180°.

get_gyroscope()[source]

Provides the rate of rotation around a given axis measured by the gyroscope, from -2,000° to 2,000° per second.

get_gyroscope().['pitch'] is the rate of forward or backward spin, from -2,000° to 2,000° per second.

get_gyroscope().['roll'] is the rate of left or right spin, from -2,000° to 2,000° per second.

get_gyroscope().['yaw'] is the rate of sideways spin, from -2,000° to 2,000° per second.

get_velocity()[source]

Provides the velocity along a given axis measured by the motor encoders, in centimeters per second.

get_velocity()['x'] is the right (+) or left (-) velocity, in centimeters per second.

get_velocity()['y'] is the forward (+) or back (-) velocity, in centimeters per second.

get_location()[source]

Provides the location where the robot is in space (x,y) relative to the origin, in centimeters. This is not the distance traveled during the program, it is the offset from the origin (program start).

get_location()['x'] is the right (+) or left (-) distance from the origin of the program start, in centimeters.

get_location()['y'] is the forward (+) or backward (-) distance from the origin of the program start, in centimeters.

get_distance()[source]

Provides the total distance traveled in the program, in centimeters.

get_speed()[source]

Provides the current target speed of the robot, from -255 to 255, where positive is forward, negative is backward, and 0 is stopped.

get_heading()[source]

Provides the target directional angle, in degrees. Assuming you aim the robot with the tail facing you, then 0° heading is forward, 90° is right, 180° is backward, and 270° is left.

get_main_led()[source]

Provides the RGB color of the main LEDs, from 0 to 255 for each color channel.

get_main_led().r is the red channel, from 0 - 255.

get_main_led().g is the green channel, from 0 - 255.

get_main_led().b is the blue channel, from 0 - 255.

get_back_led()[source]

get_back_led().b is the brightness of the back LED, from 0 to 255. For Sphero BOLT, use get_back_led() to get the RGB value.

Sphero BOLT Sensors

class spherov2.sphero_edu.SpheroEduAPI[source]
get_last_ir_message()[source]

Returns which channel the last infrared message was received on. You need to declare the on_ir_message event for each IR message you plan to see returned.

get_back_led()[source]

Provides the RGB color of the back LED, from 0 to 255 for each color channel.

get_front_led()[source]

Provides the RGB color of the front LED, from 0 to 255 for each color channel.

Sphero RVR Sensors

class spherov2.sphero_edu.SpheroEduAPI[source]
get_color()[source]

Provides the RGB color, from 0 to 255 for each color channel, that is returned from RVR’s color sensor.

get_color().r is the red channel, from 0 - 255, that is returned from RVR’s color sensor.

get_color().g is the green channel, from 0 - 255, that is returned from RVR’s color sensor.

get_color().b is the blue channel, from 0 - 255, that is returned from RVR’s color sensor.

R2-D2 & R2-Q5 Sensors

class spherov2.sphero_edu.SpheroEduAPI[source]
get_back_led()[source]

Provides the RGB color of the back LED, from 0 to 255 for each color channel.

get_front_led()[source]

Provides the RGB color of the front LED, from 0 to 255 for each color channel.

get_dome_leds()[source]

Provides the brightness of the Dome LEDs, from 0 to 15.

get_holo_projector_led()[source]

Provides the brightness of the Holographic Projector LED, from 0 to 255.

get_logic_display_leds()[source]

Provides the brightness of the white Logic Display LEDs, from 0 to 255.

Communications

Infrared (IR) is invisible light with longer wavelengths than visible light, and it is commonly used in TV remote controls to transmit small amounts of data. IR is used in Sphero BOLT to transmit data such as relative distance and heading between robots to enable following and evading behavior among multiple robots, as well as to send custom messages. There are four IR emitters and receivers (pairs) for 360° awareness assuming there is a clear line of sight between two or more robots. The effective range is up to about 3 meters.

class spherov2.sphero_edu.SpheroEduAPI[source]
start_ir_broadcast(near: int, far: int)[source]

Sets the IR emitters to broadcast on two specified channels, from 0 to 7, so other BOLTs can follow or evade. The broadcaster uses two channels because the first channel emits near IR pulses (< 1 meter), and the second channel emits far IR pulses (1 to 3 meters) so the following and evading BOLTs can detect these messages on their IR receivers with a sense of relative proximity to the broadcaster. You can’t use a channel for more than one purpose at time, such as sending messages along with broadcasting, following, or evading. For example, use start_ir_broadcast(0, 1) to broadcast on channels 0 and 1, so that other BOLTs following or evading on 0 and 1 will recognize this robot.

stop_ir_broadcast()[source]

Stops the broadcasting behavior.

start_ir_follow(near: int, far: int)[source]

Sets the IR receivers to look for broadcasting BOLTs on the same channel pair, from 0 to 7. Upon receiving messages from a broadcasting BOLT, the follower will adjust its heading and speed to follow the broadcaster. When a follower loses sight of a broadcaster, the follower will spin in place to search for the broadcaster. You can’t use a channel for more than one purpose at time, such as sending messages along with broadcasting, following, or evading. For example, use start_ir_follow(0, 1) to follow another BOLT that is broadcasting on channels 0 and 1.

stop_ir_follow()[source]

Stops the following behavior.

start_ir_evade(near: int, far: int)[source]

Sets the IR receivers to look for broadcasting BOLTs on the same channel pair, from 0 to 7. Upon receiving messages from a broadcasting BOLT, the evader will adjust its heading to roll away from the broadcaster. When an evader loses sight of a broadcaster, the evader will spin in place to search for the broadcaster. The evader may stop if it is in the far range for a period of time so it does not roll too far away from the broadcaster. You can’t use a channel for more than one purpose at time, such as sending messages along with broadcasting, following, or evading. For example, use start_ir_evade(0, 1) to evade another BOLT that is broadcasting on channels 0 and 1.

stop_ir_evade()[source]

Stops the evading behavior.

send_ir_message(channel: int, intensity: int)[source]

Sends a message on a given IR channel, at a set intensity, from 1 to 64. Intensity is proportional to proximity, where a 1 is the closest, and 64 is the farthest. For example, use send_ir_message(4, 5) to send message 4 at intensity 5. You will need to use onIRMessage4(channel) event for on a corresponding robot to receive the message. Also see the getLastIRMessage() sensor to keep track of the last message your robot received. You can’t use a channel for more than one purpose at time, such as sending messages along with broadcasting, following, or evading.

listen_for_ir_message()[source]

Refer to IR Message Received Event for usage.

listen_for_color_sensor()[source]

Refer to Color Event for usage.

Events

Events are predefined robot functions into which you can embed conditional logic. When an event occurs, the conditional logic is called in a newly spawned thread. The event will be called every time it occurs by default, unless you customize it. For example, “on collision, change LED lights to red and play the Collision sound,” while the main loop is still running.

class spherov2.sphero_edu.SpheroEduAPI[source]
register_event(event_type: spherov2.sphero_edu.EventType, listener: Callable[[...], None])[source]

Registers the event type with listener. If listener is None then it removes all listeners of the specified event type.

Note: listeners will be called in a newly spawned thread, meaning the caller have to deal with concurrency if needed. This library is thread-safe.

On Collision

Executes conditional logic when the robot collides with an object.

def on_collision(api):
    # code to execute on collision

api.register_event(EventType.on_collision, on_collision)

For example, below is a basic pong program where Sphero bounces off walls, or your hands/feet in perpetuity. Place the robot on the floor between two parallel walls/objects and run the program with the robot pointed perpendicularly at one wall. On collision, the program will print “collision” and change the LED’s to red, then continue in the opposite direction:

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)

On Freefall

Executes conditional logic when gravity is the only force acting on the robot, such as when dropping or throwing it. Freefall is measured by an accelerometer reading of < 0.1g for => 0.1s, where 1g is resting. On earth, objects in freefall accelerate downwards at 9.81 m/s^2. If you are in orbit, objects appear to be at rest with a reading of 0g because they (and you) are always in freefall, but they never hit the Earth.

def on_freefall(api):
    # code to execute on freefall

api.register_event(EventType.on_freefall, on_freefall)

For example, to print “freefall” and change the LED’s to red on freefall use:

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))

On Landing

Executes conditional logic when the robot lands after an being in freefall. You don’t need to define an on_freefall event for the robot to experience an on_landing, but the robot must meet the conditions for freefall before land.

def on_landing(api):
    # code to execute on landing

api.register_event(EventType.on_landing, on_landing)

For example, to print “landing” and change the LED’s to green after landing use:

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))

On Gyro Max

Executes conditional logic when the robot exceeds the bounds of measurable rotational velocity of -2,000° - 2,000° per second. This can be triggered by spinning the robot around like a top on a table really fast. You need to spin it around > 5.5 revolutions per second.

def on_gyro_max(api):
    # code to execute on gyromax

api.register_event(EventType.on_gyro_max, on_gyro_max)

For example, to print “gyromax” and change the LED’s to red when you reach gyromax, use:

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))

On Charging

Executes conditional logic called when the robot starts charging its battery. This can be triggered by placing your robot in it’s charging cradle, or by plugging it in.

def on_charging(api):
    # code to execute on charging

api.register_event(EventType.on_charging, on_charging)

On Not Charging

Executes conditional logic called when the robot stops charging its battery. This can be triggered by removing your robot from it’s charging cradle, or unplugging it.

def on_not_charging(api):
    # code to execute on not charging

api.register_event(EventType.on_not_charging, on_not_charging)

For example, to have Sphero execute 2 different conditions for on charging, and on not charging, use the below.

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)

On IR Message Received

Executes conditional logic called when an infrared message is received on the specified channel. This can be triggered by one Sphero BOLT robot receiving a message from another Sphero BOLT. For example, to have Sphero BOLT change the matrix to red when receiving a message on channel 4:

message_channels = (4, )

def on_ir_message_4(api, channel):
    if channel != 4:
        return
    api.set_main_led(Color(255, 0, 0))
    api.listen_for_ir_message(message_channels)

api.register_event(EventType.on_ir_message, on_ir_message_4)
api.listen_for_ir_message(message_channels)

On Color

Executes conditional logic called when Sphero RVR’s color sensor returns a specified RGB color value.

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)

The color that RVR’s color sensor returns needs to be very close to the color set with listen_for_color_sensor() for the event to execute correctly.