Table Of Contents

Previous topic

sphero_ros Tutorials

This Page

sphero_ros Python & Node API

Node API

sphero.py

sphero.py provides a simple ROS wrapper for the sphero_driver.

Subscribed Topics

disable_stabilization (std_msgs/Bool)
Turns the auto stabilization of the Sphero on and off. True for off and False for on.
cmd_vel (geometry_msgs/Twist)
The commanded velocity of the Sphero.
set_angular_velocity (std_msgs/Float32)
The angular velocity of the sphero.
set_back_led (std_msgs/Float32)
Changes the brightness of the back white LED in the Sphero. Completely off is 0.0 and full brightness 1.0.
set_color (std_msgs/ColorRGBA)
Sets the RGB color of the Sphero.
set_heading (std_msgs/Float32)
Immediately changes the heading of the Sphero to the commanded angle. Will move in the shortest angular distance to the commanded heading.

Published Topics

collision (sphero_node/SpheroCollision)
Publishes collision data when the Sphero collides with the environment.
diagnostics (diagnostic_msgs/DiagnosticArray)
Publishes relevant information (i.e. battery status).
imu (snesor_msgs/Imu)
The Sphero imu data.
odom (nav_msgs/Odometry)
The odometric state of the Sphero.

Parameters

~cmd_vel_timeout (float, default: 0.6)
The time from when the last cmd_vel was published to set cmd_vel to zero.
~connect_blue (int, default: 0)
Set the blue value of the color the Sphero turns on connection.
~connect_green (int, default: 255)
Set the green value of the color the Sphero turns on connection.
~connect_red (int, default: 0)
Set the red value of the color the Sphero turns on connection.
~diag_update_rate (float, default: 1.0)
Sets the update rate for the diagnostics.

Python API

The Python API for the underlying Sphero driver.

sphero_driver

class sphero_driver.Sphero(target_name='Sphero')[source]
assign_counter_value(counter, response)[source]

Sphero contains a 32-bit counter that increments every millisecond when it’s not in the Idle state. It has no absolute meaning and is reset for various reasons. This command assigns the counter a specific value for subsequent sampling.

Parameters:
  • counter – value to set the counter to.
  • response – request response back from Sphero.
boost(time, heading, response)[source]

This commands Sphero to meet the provided heading, disable stabilization and ramp the motors up to full-speed for a period of time. The Time parameter is the duration in tenths of a second. Setting it to zero enables constant boost until a Set Stabilization command is received.

Parameters:
  • time – duration of boost in tenths of seconds.
  • heading – the heading to travel while boosting.
  • response – request response back from Sphero.
clear_counters(response)[source]

This is a developers-only command to clear the various system counters described in the level 2 diag.

Parameters:response – request response back from Sphero.
config_collision_detect(method, Xt, Xspd, Yt, Yspd, ignore_time, response)[source]

This command either enables or disables asynchronous message generation when a collision is detected.The Ignore Time parameter disables collision detection for a period of time after the async message is generated, preventing message overload to the client. The value is in 10 millisecond increments.

Parameters:
  • method – Detection method type to use. Currently the only method supported is 01h. Use 00h to completely disable this service.
  • Yt (Xt,) – An 8-bit settable threshold for the X (left/right) and Y (front/back) axes of Sphero. A value of 00h disables the contribution of that axis.
  • Xspd,Yspd – An 8-bit settable speed value for the X and Y axes. This setting is ranged by the speed, then added to Xt, Yt to generate the final threshold value.
  • ignore_time – An 8-bit post-collision dead time to prevent retriggering; specified in 10ms increments.
get_app_config_blk(response)[source]

This allows you to retrieve the application configuration block that is set aside for exclusive use by applications. :param response: request response back from Sphero.

get_auto_reconnect(response)[source]

This returns the Bluetooth auto reconnect values as defined in the Set Auto Reconnect command.

Parameters:response – request response back from Sphero.
get_bt_name(response)[source]

This returns the textual name (in ASCII) that the Bluetooth module advertises. It also returns the BTA Bluetooth Address or MAC ID for this device. Both values are returned in ASCII and have field widths of 16 characters, with unused trailing characters set to 00h.

Parameters:response – request response back from Sphero.
get_power_state(response)[source]

This returns the current power state and some additional parameters to the Client.

Parameters:response – request response back from Sphero.
get_rgb_led(response)[source]

This retrieves the “user LED color” which is stored in the config block (which may or may not be actively driven to the RGB LED).

Parameters:response – request response back from Sphero.
get_version(response)[source]

The Get Versioning command returns a whole slew of software and hardware information.

Parameters:response – request response back from Sphero.
go_to_sleep(time, macro, response)[source]

This puts Sphero to sleep immediately with two parameters: the first is the number of seconds after which it will automatically re-awaken. If set to zero, this feature is disabled. If non-zero then the MACRO parameter allows an optional system macro to be run upon wakeup. If this is set to zero, no macro is executed.

Parameters:
  • time – number of seconds wait before auto re-awake.
  • macro – macro number to run when re-awakened.
  • response – request response back from Sphero.
parse_collision_detect(data, data_length)[source]

The data payload of the async message is 10h bytes long and formatted as follows:

-----------------------------------------------------------------
|X | Y | Z | AXIS | xMagnitude | yMagnitude | Speed | Timestamp |
-----------------------------------------------------------------
  • X, Y, Z - Impact components normalized as a signed 16-bit value. Use these to determine the direction of collision event. If you don’t require this level of fidelity, the two Magnitude fields encapsulate the same data in pre-processed format.
  • Axis - This bitfield specifies which axes had their trigger thresholds exceeded to generate the event. Bit 0 (01h) signifies the X axis and bit 1 (02h) the Y axis.
  • xMagnitude - This is the power that crossed the programming threshold Xt + Xs.
  • yMagnitude - This is the power that crossed the programming threshold Yt + Ys.
  • Speed - The speed of Sphero when the impact was detected.
  • Timestamp - The millisecond timer value at the time of impact; refer to the documentation of CID 50h and 51h to make sense of this value.
parse_pwr_notify(data, data_length)[source]

The data payload of the async message is 1h bytes long and formatted as follows:

--------
|State |
--------
The power state byte:
  • 01h = Battery Charging,
  • 02h = Battery OK,
  • 03h = Battery Low,
  • 04h = Battery Critical
ping(response)[source]

The Ping command is used to verify both a solid data link with the Client and that Sphero is awake and dispatching commands.

Parameters:response – request response back from Sphero.
poll_packet_times(time, response)[source]

This command helps the Client application profile the transmission and processing latencies in Sphero so that a relative synchronization of timebases can be performed. It allows the Client to reconcile time stamped messages from Sphero to its own time stamped events.

The scheme is as follows: the Client sends the command with the Client Tx time (T_{1}) filled in. Upon receipt of the packet, the command processor in Sphero copies that time into the response packet and places the current value of the millisecond counter into the Sphero Rx time field (T_{2}). Just before the transmit engine streams it into the Bluetooth module, the Sphero Tx time value (T_{3}) is filled in. If the Client then records the time at which the response is received (T_{4}) the relevant time segments can be computed from the four time stamps (T_{1}, T_{2}, T_{3}, T_{4}):

  • The value offset represents the maximum-likelihood time offset of the Client clock to Sphero’s system clock.
    • offset = 1/2*[(T_{2} - T_{1}) + (T_{3}  - T_{4})]
  • The value delay represents the round-trip delay between the Client and Sphero:
    • delay = (T_{4} - T_{1}) - (T_{3} - T_{2})
Parameters:
  • time – client Tx time.
  • response – request response back from Sphero.
recv(num_bytes)[source]

Commands are acknowledged from the Sphero -> Client in the following format:

-------------------------------------------------
|SOP1 | SOP2 | MSRP | SEQ | DLEN | <data> | CHK |
-------------------------------------------------
  • SOP1 - Start Packet 1 - Always 0xff.
  • SOP2 - Start Packet 2 - Set to 0xff when this is an acknowledgement, 0xfe otherwise.
  • MSRP - Message Response - This is generated by the message decoder of the virtual device.
  • SEQ - Sequence Number - Echoed to the client when this is a direct message response (set to 00h when SOP2 = FEh)
  • DLEN - Data Length - The number of bytes following through the end of the packet
  • <data>
  • CHK - Checksum - - The modulo 256 sum of all the bytes from the DID through the end of the data payload, bit inverted (1’s complement)

Asynchronous Packets are sent from Sphero -> Client in the following byte format:

-------------------------------------------------------------
|SOP1 | SOP2 | ID CODE | DLEN-MSB | DLEN-LSB | <data> | CHK |
-------------------------------------------------------------
  • SOP1 - Start Packet 1 - Always 0xff.
  • SOP2 - Start Packet 2 - Set to 0xff when this is an acknowledgement, 0xfe otherwise.
  • ID CODE - ID Code - See the IDCODE dict
  • DLEN-MSB - Data Length MSB - The MSB number of bytes following through the end of the packet
  • DLEN-LSB - Data Length LSB - The LSB number of bytes following through the end of the packet
  • <data>
  • CHK - Checksum - - The modulo 256 sum of all the bytes from the DID through the end of the data payload, bit inverted (1’s complement)
roll(speed, heading, state, response)[source]

This commands Sphero to roll along the provided vector. Both a speed and a heading are required; the latter is considered relative to the last calibrated direction. A state Boolean is also provided (on or off). The client convention for heading follows the 360 degrees on a circle, relative to the ball: 0 is straight ahead, 90 is to the right, 180 is back and 270 is to the left. The valid range is 0..359.

Parameters:
  • speed – 0-255 value representing 0-max speed of the sphero.
  • heading – heading in degrees from 0 to 359.
  • state – 00h for off (braking) and 01h for on (driving).
  • response – request response back from Sphero.
run_l1_diags(response)[source]

This is a developer-level command to help diagnose aberrant behavior. Most system counters, process flags, and system states are decoded into human readable ASCII. There are two responses to this command: a Simple Response followed by a large async message containing the results of the diagnostic tests.

Parameters:response – request response back from Sphero.
run_l2_diags(response)[source]

This is a developers-only command to help diagnose aberrant behavior. It is much less impactful than the Level 1 command as it doesn’t interfere with the current operation it simply returns a current set of statistics to the client.

Parameters:response – request response back from Sphero.
send(data, response)[source]

Packets are sent from Client -> Sphero in the following byte format:

-------------------------------------------------------
| SOP1 | SOP2 | DID | CID | SEQ | DLEN | <data> | CHK |
-------------------------------------------------------
  • SOP1 - start packet 1 - Always 0xff.
  • SOP2 - start packet 2 - Set to 0xff when an acknowledgement is expected, 0xfe otherwise.
  • DID - Device ID
  • CID - Command ID
  • SEQ - Sequence Number - This client field is echoed in the response for all synchronous commands (and ignored by Sphero when SOP2 = 0xfe)
  • DLEN - Data
  • Length - Number of bytes through the end of the packet.
  • <data>
  • CHK - Checksum - The modulo 256 sum of all the bytes from the DID through the end of the data payload, bit inverted (1’s complement).
set_all_data_strm(sample_div, sample_frames, pcnt, response)[source]

Helper function to add all the data to the data strm mask, so that the user doesn’t have to set the data strm manually.

Parameters:
  • sample_div – divisor of the maximum sensor sampling rate.
  • sample_frames – number of sample frames emitted per packet.
  • pcnt – packet count (set to 0 for unlimited streaming).
  • response – request response back from Sphero.
set_app_config_blk(app_data, response)[source]

This allows you to write a 32 byte block of data from the configuration block that is set aside for exclusive use by applications.

Parameters:
  • app_data – block set aside for application.
  • response – request response back from Sphero.
set_auto_reconnect(enable, time, response)[source]

This configures the control of the Bluetooth module in its attempt to automatically reconnect with the last iPhone device. This is a courtesy behavior since the iPhone Bluetooth stack doesn’t initiate automatic reconnection on its own. The two parameters are simple: flag = 00h to disable or 01h to enable, and time = the number of seconds after power-up in which to enable auto reconnect mode. For example, if time = 30 then the module will be attempt reconnecting 30 seconds after waking up.

Parameters:
  • enable – 00h to disable or 01h to enable auto reconnecting.
  • time – the number of seconds after power-up in which to enable auto reconnect mode
  • response – request response back from Sphero.
set_back_led(brightness, response)[source]

This allows you to control the brightness of the back LED. The value does not persist across power cycles.

Parameters:
  • brightness – 0-255, off-on (the blue LED on hemisphere of the Sphero).
  • response – request response back from Sphero.
set_data_strm(sample_div, sample_frames, sample_mask1, pcnt, sample_mask2, response)[source]

Currently the control system runs at 400Hz and because it’s pretty unlikely you will want to see data at that rate, N allows you to divide that down. sample_div = 2 yields data samples at 200Hz, sample_div = 10, 40Hz, etc. Every data sample consists of a “frame” made up of the individual sensor values as defined by the sample_mask. The sample_frames value defines how many frames to collect in memory before the packet is emitted. In this sense, it controls the latency of the data you receive. Increasing sample_div and the number of bits set in sample_mask drive the required throughput. You should experiment with different values of sample_div, sample_frames and sample_mask to see what works best for you.

Parameters:
  • sample_div – divisor of the maximum sensor sampling rate.
  • sample_frames – number of sample frames emitted per packet.
  • sample_mask1 – bitwise selector of data sources to stream.
  • pcnt – packet count (set to 0 for unlimited streaming).
  • response – request response back from Sphero.
set_device_name(name, response)[source]

This assigned name is held internally and produced as part of the Get Bluetooth Info service below. Names are clipped at 48 characters in length to support UTF-8 sequences; you can send something longer but the extra will be discarded. This field defaults to the Bluetooth advertising name.

Parameters:
  • name – 48 character name.
  • response – request response back from Sphero.
set_filtered_data_strm(sample_div, sample_frames, pcnt, response)[source]

Helper function to add all the filtered data to the data strm mask, so that the user doesn’t have to set the data strm manually.

Parameters:
  • sample_div – divisor of the maximum sensor sampling rate.
  • sample_frames – number of sample frames emitted per packet.
  • pcnt – packet count (set to 0 for unlimited streaming).
  • response – request response back from Sphero.
set_heading(heading, response)[source]

This allows the client to adjust the orientation of Sphero by commanding a new reference heading in degrees, which ranges from 0 to 359. You will see the ball respond immediately to this command if stabilization is enabled.

Parameters:
  • heading – heading in degrees from 0 to 359 (motion will be shortest angular distance to heading command)
  • response – request response back from Sphero.
set_power_notify(enable, response)[source]

This enables Sphero to asynchronously notify the Client periodically with the power state or immediately when the power manager detects a state change. Timed notifications arrive every 10 seconds until they’re explicitly disabled or Sphero is unpaired. The flag is as you would expect, 00h to disable and 01h to enable.

Parameters:
  • enable – 00h to disable and 01h to enable power notifications.
  • response – request response back from Sphero.
set_raw_data_strm(sample_div, sample_frames, pcnt, response)[source]

Helper function to add all the raw data to the data strm mask, so that the user doesn’t have to set the data strm manually.

Parameters:
  • sample_div – divisor of the maximum sensor sampling rate.
  • sample_frames – number of sample frames emitted per packet.
  • pcnt – packet count (set to 0 for unlimited streaming).
  • response – request response back from Sphero.
set_raw_motor_values(l_mode, l_power, r_mode, r_power, response)[source]

This allows you to take over one or both of the motor output values, instead of having the stabilization system control them. Each motor (left and right) requires a mode (see below) and a power value from 0- 255. This command will disable stabilization if both modes aren’t “ignore” so you’ll need to re-enable it via CID 02h once you’re done.

Parameters:
  • mode – 0x00 - off, 0x01 - forward, 0x02 - reverse, 0x03 - brake, 0x04 - ignored.
  • power – 0-255 scalar value (units?).
set_rgb_led(red, green, blue, save, response)[source]

This allows you to set the RGB LED color. The composite value is stored as the “application LED color” and immediately driven to the LED (if not overridden by a macro or orbBasic operation). If FLAG is true, the value is also saved as the “user LED color” which persists across power cycles and is rendered in the gap between an application connecting and sending this command.

Parameters:
  • red – red color value.
  • green – green color value.
  • blue – blue color value.
  • save – 01h for save (color is saved as “user LED color”).
set_rotation_rate(rate, response)[source]

This allows you to control the rotation rate that Sphero will use to meet new heading commands. The commanded value is in units of 0.784 degrees/sec. So, setting a value of c8h will set the rotation rate to 157 degrees/sec. A value of 255 jumps to the maximum and a value of 1 is the minimum.

Parameters:
  • rate – rotation rate in units of 0.784degrees/sec (setting this value will not cause the device to move only set the rate it will move in other funcation calls).
  • response – request response back from Sphero.
set_stablization(enable, response)[source]

This turns on or off the internal stabilization of Sphero, in which the IMU is used to match the ball’s orientation to its various set points. The flag value is as you would expect, 00h for off and 01h for on.

Parameters:
  • enable – 00h for off and 01h for on (on by default).
  • response – request response back from Sphero.