Events are predefined robot functions into which you can embed conditional logic. When an event occurs, the conditional logic is called and then the program returns to the main loop where it left off. 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," then return to the main loop.
To use event commands, an event callback must first be registered. There are two registration functions for event callbacks; one for registing events that do not have a condition, and one for registering events that do have a condition.
Registers an event callback:
JavaScript: registerEvent(EventType, functionName)
Python: register_event(EventType, function_name)
Parameters:
name {EventType} - The name of the event type
callback {any} - The event callback to execute
Registers an event callback for an event that needs to have a condition met:
JavaScript: registerEventCondition(EventType, functionName, condition)
Python: registerEventCondition(EventType, function_name, condition)
Parameters:
name {EventType} - The name of the event type
callback {any} - an async function that checks the condition and triggers the event if the condition has been met
condition {any} - either a numeric threshold (such as time elapsed) or a predicate function
Executes conditional logic when the robot collides with an object. The On Collision event needs to first be registered with a Register Event function before it can be called in code. See the examples below:
JavaScript:
async function onCollision() {
// code to execute on collision
}
registerEvent(EventType.onCollision, onCollision);
Python:
async def on_collision():
# code to execute on collision
pass
register_event(EventType.ON_COLLISION, on_collision)
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 speak "collision" and change the LED's to red, then continue in the opposite direction:
JavaScript:
async function onCollision() {
stopRoll();
setMainLed({ r: 255, g: 0, b: 0 });
await speak("Collision", false);
setHeading((getHeading() + 180));
await delay(0.5);
setMainLed({ r: 255, g: 22, b: 255 });
setSpeed(100);
}
registerEvent(EventType.onCollision, onCollision);
async function startProgram() {
setMainLed({
r: 255,
g: 255,
b: 255
});
setSpeed(100);
}
Python:
async def on_collision():
stop_roll()
set_main_led({'r': 255, 'g': 0, 'b': 0})
await speak("Collision", False)
set_heading((get_heading() + 180))
await delay(0.5)
set_main_led({'r': 255, 'g': 22, 'b': 255})
set_speed(100)
register_event(EventType.ON_COLLISION, on_collision)
async def start_program():
set_main_led({'r': 255, 'g': 255, 'b': 255})
set_speed(100)
Note:
On Collision is not supported with RVR/RVR+, since repeated collisions can damage the motors.
Executes conditional logic when a specific distance (in centimeters) has been traveled. The On Total Distance event needs to first be registered with a Register Event Condition function before it can be called in code. See the examples below:
JavaScript:
async function onTotalDistance(distance) {
// code to execute when distance condition is met
}
registerEventCondition(EventType.onTotalDistance, onTotalDistance, 10);
Python:
async def on_total_distance(distance):
# code to execute when distance condition is met
pass
register_event_condition(EventType.ON_TOTAL_DISTANCE, on_total_distance, 10)
Below is a basic program in which BOLT+ rolls at a set speed until 50cm has been traveled, at which point a celebratory confetti animation is displayed on the LCD screen:
JavaScript:
async function startProgram() {
setSpeed(100);
}
async function onTotalDistance(distance) {
stopRoll();
await setDisplayAnimation("confetti", true);
}
registerEventCondition(EventType.onTotalDistance, onTotalDistance, 50);
Python:
async def start_program():
set_speed(100)
async def on_total_distance(distance):
stop_roll()
await set_display_animation("confetti", True)
register_event_condition(EventType.ON_TOTAL_DISTANCE, on_total_distance, 50)
You can use multiple instances of On Total Distance events in your program. For example, you can write code to execute at 10cm, 50cm, and 100cm, and all three instances will execute provided you have registered each event condition. In the program below, the robot will roll at a speed of 50 until the 3 distance conditions are met. At 10 cm the LEDs will turn red, at 50cm the LEDs will turn blue , and at 100cm the robot will stop rolling:
JavaScript:
async function startProgram() {
setSpeed(50);
}
async function onTotalDistance(distance) {
setMainLed({ r: 255, g: 0, b: 0 });
}
registerEventCondition(EventType.onTotalDistance, onTotalDistance, 10);
async function onTotalDistance_2(distance) {
setMainLed({ r: 0, g: 255, b: 0 });
}
registerEventCondition(EventType.onTotalDistance, onTotalDistance_2, 50);
async function onTotalDistance_3(distance) {
stopRoll();
}
registerEventCondition(EventType.onTotalDistance, onTotalDistance_3, 100);
Python:
async def start_program():
set_speed(50)
async def on_total_distance(distance):
set_main_led({'r': 255, 'g': 0, 'b': 0})
register_event_condition(EventType.ON_TOTAL_DISTANCE, on_total_distance, 10)
async def onTotalDistance_2(distance2):
set_main_led({'r': 0, 'g': 255, 'b': 0})
register_event_condition(EventType.ON_TOTAL_DISTANCE, on_total_distance_2, 50)
async def onTotalDistance_3(distance3):
stop_roll()
register_event_condition(EventType.ON_TOTAL_DISTANCE, on_total_distance_3, 100)
Note:
On Total Distance is only supported with Sphero BOLT+.
Executes conditional logic when when a specific time (in seconds) has elapsed. The On Time Elapsed event needs to first be registered with a Register Event Condition function before it can be called in code. See the examples below:
JavaScript:
async function onTimeElapsed(program_run_time) {
// code to execute on specified elapsed time
}
registerEventCondition(EventType.onTimeElapsed, onTimeElapsed, 15);
Python:
async def on_time_elapsed(program_run_time):
# code to execute on specified elapsed time
pass
register_event_condition(EventType.ON_TIME_ELAPSED, on_time_elapsed, 15)
Below is a basic program in which BOLT+ rolls at a set speed until 10 seconds has elapsed, at which point a celebratory confetti animation is displayed on the BOLT+ LCD screen:
JavaScript:
async function startProgram() {
setSpeed(50);
}
async function onTimeElapsed(program_run_time) {
stopRoll();
await setDisplayAnimation("confetti", true);
}
registerEventCondition(EventType.onTimeElapsed, onTimeElapsed, 10);
Python:
async def start_program():
set_speed(50)
async def on_time_elapsed(program_run_time):
stop_roll()
await set_display_animation("confetti", True)
register_event_condition(EventType.ON_TIME_ELAPSED, on_time_elapsed, 10)
You can use multiple instances of On Time Elapsed events in your program. For example, you can write code to execute at 10 seconds, 15 seconds, and 100cm, and all three instances will execute provided you have registered each event condition and have set unique function names.
Note:
On Time Elapsed is only supported with Sphero BOLT+.
Executes conditional logic when when the ambient light in your environment is greater than or less than specified values.
JavaScript:
async function onAmbientLight(ambientLight) {
// code to execute on specified ambient light condition
}
registerEventCondition(EventType.onAmbientLight, onAmbientLight, function check(ambientLight) { return ambientLight >= 500 });
Python:
async def on_ambient_light(ambientLight):
# code to execute on specified ambient light condition
pass
def check(ambient_light):
return ambient_light >= 500
register_event_condition(EventType.ON_AMBIENT_LIGHT, on_ambient_light, check)
You can use multiple instances of On Ambient Light. For example, below is a basic program in which the BOLT+ LEDs will change to green if the ambient light is above 400lux and change to red if the ambient light is below 200lux:
JavaScript:
async function startProgram() {
setMainLed({ r: 255, g: 255, b: 255 });
}
async function onAmbientLight(ambientLight) {
setMainLed({ r: 0, g: 255, b: 0 });
}
registerEventCondition(EventType.onAmbientLight, onAmbientLight, function check(ambientLight) { return ambientLight >= 400 });
async function onAmbientLight_2(ambientLight) {
setMainLed({ r: 255, g: 0, b: 0 });
}
registerEventCondition(EventType.onAmbientLight, onAmbientLight_2, function check(ambientLight) { return ambientLight <= 200 });
Python:
async def start_program():
set_main_led({'r': 255, 'g': 255, 'b': 255})
async def on_ambient_light(ambient_light):
set_main_led({'r': 0, 'g': 255, 'b': 0})
def check(ambient_light):
return ambient_light >= 400
register_event_condition(EventType.ON_AMBIENT_LIGHT, on_ambient_light, check)
async def on_ambient_light_2(ambient_light):
set_main_led({'r': 255, 'g': 0, 'b': 0})
def check2(ambient_light):
return ambient_light <= 200
register_event_condition(EventType.ON_AMBIENT_LIGHT, on_ambient_light_2, check2)
Note:
On Ambient Light is only supported with Sphero BOLT+.
Executes conditional logic when the associated software button is selected.
JavaScript:
var _softwareButtonEvents = ['one'];
async function startProgram() {
registerSoftwareButton(_softwareButtonEvents);
}
async function onSoftwareButton(button) {
if (button !== 'one') return;
}
registerEvent(EventType.onSoftwareButton, onSoftwareButton);
Python:
_software_button_events = ['one']
async def start_program():
register_software_button(_software_button_events)
async def on_software_button(button):
if button != 'one':
return
register_event(EventType.ON_SOFTWARE_BUTTON, on_software_button)
You can define up to three software buttons. Each defined software button must have a unique name to ensure the program executes without errors. Unlike other on event commands, the On Software Button function allows the user to directly control when the associated code executes, which opens up many interesting opportunities.
The example below shows how these buttons can be combine in interesting ways with other BOLT+ commands.
JavaScript:
var _softwareButtonEvents = ['aim', 'honk horn', 'change LED color'];
async function startProgram() {
registerSoftwareButton(_softwareButtonEvents);
drive(true);
}
async function onSoftwareButton(button) {
if (button !== 'aim') return;
resetAim();
}
registerEvent(EventType.onSoftwareButton, onSoftwareButton);
async function onSoftwareButton_2(button) {
if (button !== 'honk horn') return;
await Sound.Mechanical.CarHorn.play(false);
}
registerEvent(EventType.onSoftwareButton, onSoftwareButton_2);
async function onSoftwareButton_3(button) {
if (button !== 'change LED color') return;
setMainLed(getRandomColor());
}
registerEvent(EventType.onSoftwareButton, onSoftwareButton_3);
Python:
_software_button_events = ['aim', 'honk horn', 'change LED color']
async def start_program():
register_software_button(_software_button_events)
drive(True)
async def on_software_button(button):
if button != 'aim':
return
reset_aim()
register_event(EventType.ON_SOFTWARE_BUTTON, on_software_button)
async def on_software_button_2(button2):
if button2 != 'honk horn':
return
await Sound.Mechanical.CarHorn.play(False)
register_event(EventType.ON_SOFTWARE_BUTTON, on_software_button_2)
async def on_software_button_3(button3):
if button3 != 'change LED color':
return
set_main_led(get_random_color())
register_event(EventType.ON_SOFTWARE_BUTTON, on_software_button_3)
In this example, we are turning BOLT+ into a horn honking car as we drive it around our environment. On program start, drive(true) allows the user to manually drive BOLT+ around their environment. The first button (titled "aim") is set to allow the user to reset their heading at will:
JavaScript:
async function onSoftwareButton(button) {
if (button !== 'aim') return;
resetAim();
Python:
async def on_software_button(button):
if button != 'aim':
return
reset_aim()
The second button (titled "honk horn") allows the user to play a car horn sound effect at will:
JavaScript:
async function onSoftwareButton_2(button) {
if (button !== 'honk horn') return;
await Sound.Mechanical.CarHorn.play(false);
Python:
async def on_software_button_2(button2):
if button2 != 'honk horn':
return
await Sound.Mechanical.CarHorn.play(False)
The third button (titled "change LED color") allows the user to randomize the LEDs at will:
JavaScript:
async function onSoftwareButton_3(button) {
if (button !== 'change LED color') return;
setMainLed(getRandomColor());
Python:
async def on_software_button_3(button3):
if button3 != 'change LED color':
return
set_main_led(get_random_color())
Note:
On Software Button is only supported with Sphero BOLT+.
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². 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.
JavaScript:
async function onFreefall() {
// code to execute on freefall
}
registerEvent(EventType.onFreefall, onFreefall);
Python:
async def on_freefall():
# code to execute on freefall
pass
register_event(EventType.ON_FREEFALL, on_freefall)
For example, to speak "freefall" and change the LED's to red on freefall use:
JavaScript:
async function onFreefall() {
setMainLed({ r: 255, g: 0, b: 0 });
await speak("freefall", false);
await delay(0.5);
}
registerEvent(EventType.onFreefall, onFreefall);
async function startProgram() {
while (true) {
setMainLed({ r: 255, g: 255, b: 255 });
await delay(0.1);
}
}
Python:
async def on_freefall():
set_main_led({'r': 255, 'g': 0, 'b': 0})
await speak("freefall", False)
await delay(0.5)
register_event(EventType.ON_FREEFALL, on_freefall)
async def start_program():
while True:
set_main_led({'r': 255, 'g': 255, 'b': 255})
await delay(0.1)
Note:
On Freefall is not supported with RVR/RVR+, since repeated falls can damage mechanical components.
Executes conditional logic when the robot lands after being in freefall. You don't need to define an On Freefall event for the robot to experience an On Landing event, but the robot must meet the conditions for freefall before landing.
JavaScript:
async function onLanding() {
// code to execute on landing
}
registerEvent(EventType.onLanding, onLanding);
Python:
async def on_landing():
# code to execute on landing
pass
register_event(EventType.ON_LANDING, on_landing)
For example, to speak "landing" and change the LED's to green after landing, use:
JavaScript:
async function onLanding() {
setMainLed({ r: 0, g: 255, b: 0 });
await speak("landing", false);
await delay(0.5);
}
registerEvent(EventType.onLanding, onLanding);
async function startProgram() {
while (true) {
setMainLed({ r: 255, g: 255, b: 255 });
await delay(0.1);
}
}
Python:
async def on_landing():
set_main_led({'r': 0, 'g': 255, 'b': 0})
await speak("landing", False)
await delay(0.5)
register_event(EventType.ON_LANDING, on_landing)
async def start_program():
while True:
set_main_led({'r': 255, 'g': 255, 'b': 255})
await delay(0.1)
Note:
On Landing is not supported with RVR/RVR+, since repeated falls can damage mechanical components.
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.
JavaScript:
async function onGyroMax() {
// code to execute on gyroscope max
}
registerEvent(EventType.onGyroMax, onGyroMax);
Python:
async def on_gyro_max():
# code to execute on gyroscope max
pass
register_event(EventType.ON_GYRO_MAX, on_gyro_max)
For example, to speak "gyro max" and change the LED's to red when you reach gyro max, use:
JavaScript:
async function onGyroMax() {
setMainLed({ r: 255, g: 0, b: 0 });
await speak("gyroscope max", true);
await delay(1.0);
}
registerEvent(EventType.onGyroMax, onGyroMax);
async function startProgram() {
setStabilization(false);
setBackLed(255);
while (true) {
setMainLed({ r: 255, g: 255, b: 255 });
await delay(0.5);
}
}
Python:
async def on_gyro_max():
set_main_led({'r': 255, 'g': 0, 'b': 0})
await speak("gyroscope max", True)
await delay(1.0)
register_event(EventType.ON_GYRO_MAX, on_gyro_max)
async def start_program():
set_stabilization(False)
set_back_led(255)
while True:
set_main_led({'r': 255, 'g': 255, 'b': 255})
await delay(0.5)
Note:
On Gyro Max is not supported with RVR/RVR+.
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.
JavaScript:
async function onCharging() {
// code to execute on charging
}
registerEvent(EventType.onCharging, onCharging);
Python:
async def on_charging():
# code to execute on charging
pass
register_event(EventType.ON_CHARGING, on_charging)
Note:
On Charging is not supported with RVR/RVR+ since the battery is physically removed when charging.
On Charging is not supported with Mini since the Mini resets when charging starts.
On Charging is not supported with BOLT+ since the BOLT+ resets when charging starts and connection is not supported while in the charging cradle.
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.
JavaScript:
async function onNotCharging() {
// code to execute on not charging
}
registerEvent(EventType.onNotCharging, onNotCharging);
Python:
async def on_not_charging():
# code to execute on not charging
pass
register_event(EventType.ON_NOT_CHARGING, on_not_charging)
For example, to have Sphero execute 3 different conditions for on start, on charging, and on not charging, use:
JavaScript:
async function onCharging() {
setMainLed({ r: 6, g: 0, b: 255 });
await speak("charging", true);
await delay(1.0);
await speak("remove me from my charger", true);
}
registerEvent(EventType.onCharging, onCharging);
async function onNotCharging() {
setMainLed({ r: 255, g: 0, b: 47 });
await speak("not charging", true);
await delay(2.0);
}
registerEvent(EventType.onNotCharging, onNotCharging);
async function startProgram() {
await speak("place me in my charger", true);
while (true) {
setMainLed({ r: 3, g: 255, b: 0 });
await delay(0.5);
}
}
Python:
async def on_charging():
set_main_led({'r': 6, 'g': 0, 'b': 255})
await speak("charging", True)
await delay(1.0)
await speak("remove me from my charger", True)
register_event(EventType.ON_CHARGING, on_charging)
async def on_not_charging():
set_main_led({'r': 255, 'g': 0, 'b': 47})
await speak("not charging", True)
await delay(2.0)
register_event(EventType.ON_NOT_CHARGING, on_not_charging)
async def start_program():
await speak("place me in my charger", True)
while True:
set_main_led({'r': 3, 'g': 255, 'b': 0})
await delay(0.5)
Note:
On Not Charging is not supported with RVR/RVR+ since the battery is physically removed when charging.
On Not Charging is not supported with Mini since the Mini resets when charging starts.
On Not Charging is not supported with BOLT+ since the BOLT+ resets when charging starts and connection is not supported while in the charging cradle.
Executes conditional logic called when an infrared message is received on the specified channel. This can be triggered by one robot receiving a message from another robot. For example, to have Sphero BOLT change the matrix to red when receiving a message on channel 4 use:
JavaScript:
var _messageChannels = [4];
async function startProgram() {
listenForIRMessage(_messageChannels);
}
async function onIRMessage4(channel) {
if (channel !== 4) return;
setMainLed({ r: 255, g: 0, b: 0 });
listenForIRMessage(_messageChannels);
}
registerEvent(EventType.onIRMessage, onIRMessage4);
Python:
_message_channels = [4]
async def start_program():
listen_for_ir_message(_message_channels)
async def on_ir_message_4(channel):
if channel != 4:
return
set_main_led({'r': 255, 'g': 0, 'b': 0})
listen_for_ir_message(_message_channels)
register_event(EventType.ON_IR_MESSAGE, on_ir_message_4)
Note:
On IR Message is supported with Sphero BOLT, BOLT+, and RVR/RVR+.
onColor(color) executes conditional logic called when Sphero RVR/RVR+'s color sensor returns a specified RGB color value.
JavaScript:
var _colors = [{ r: 255, g: 15, b: 60 }];
async function startProgram() {
listenForColorSensor(_colors);
}
async function onColor(color) {
if (color.r !== 255 || color.g !== 15 || color.b !== 60) return;
}
registerEvent(EventType.onColor, onColor);
Python:
_colors = [{'r': 255, 'g': 15, 'b': 60}]
async def start_program():
listen_for_color_sensor(_colors)
async def on_color(color):
if color['r'] != 255 or color['g'] != 15 or color['b'] != 60:
return
register_event(EventType.ON_COLOR, on_color)
The color that RVR/RVR+'s color sensor returns needs to be very close to the color set with the On Color function for the event to execute correctly. We recommend setting the desired color with the "on color" event block in the block canvas, then copying the RGB values into your JavaScript code. To accomplish this, do the following:
Connect to a Sphero RVR/RVR+
Select the "on color" event block and add it to the block canvas
Select the square on the "on color" event block to open the Color Sensor popup
Position the color sensor over the desired color
Copy the red, green, and blue values from the popup
Add them to the On Color async function in the Text canvas to ensure the color event executes correctly
"On color" block popup:
Note:
The physical color sensor must be enabled for On Color to execute correctly. If the Listen For Color Sensor function is not included, then the color sensor will return an RGB value of 0,0,0 (black). Always ensure the following code is included while setting up the On Color events:
JavaScript:
async function startProgram() {
listenForColorSensor(_colors);
}
Python:
async def start_program():
listen_for_color_sensor(_colors)