Controls (aka "Control Flow") change the flow of your program and enable conditional or branching logic. For example, "if speed > 20, then turn LED lights red." There are lots of different types of controls to make interesting programs that go beyond a procedural set of Movement commands.
Delays execution of the next set of code for a specified number of seconds. To delay code for 10 seconds, use await delay(10). The function is the same for both JavaScript and Python.
Use the examples below to set Speed to 100 for a duration of 4 seconds, then stop:
JavaScript:
setSpeed(100);
await delay(4);
setSpeed(0);
Python:
set_speed(100)
await delay(4)
set_speed(0)
Parameters:
duration {number} - The duration to pause execution (in seconds)
A loop (aka a "for" loop) repeats the designated code for a given number of times.
In JavaScript, you define for loops via this template:
for (initialize loop variable; check loop condition; update loop variable) {
// code to repeat goes here (contained between the '{' and '}' braces)
}
For Python you define for loops via this template:
for i in range(n):
# code to repeat goes here
i is the variable (iterator), and range is a Python function that generates a sequence of numbers (n).
When you define new loop variables, you can use any name you like as long as it is unique, but we often use _i1 to be consistent with the code generated from our blocks canvas. Here's a simple example that spins 90 degrees and says "Spin" 8 times.
JavaScript:
async function startProgram() {
setBackLed(255);
for (var _i1 = 0; _i1 < 8; _i1++) {
await speak('Spin', true);
setHeading((getHeading() + 90)); await delay(0.25);
}
}
Python:
async def start_program():
set_back_led(255)
for _i1 in range(8):
await speak('Spin', True)
set_heading((get_heading() + 90))
await delay(0.25)
A fun use of loops is to blink random colors. To set a random color on the main LED's every 0.2s for 20 loops, use:
JavaScript:
async function startProgram() {
for (var _i1 = 0; _i1 < 20; _i1++) {
setMainLed(getRandomColor());
await delay(0.2);
}
}
Python:
async def start_program():
for _i1 in range(20):
set_main_led(get_random_color())
await delay(0.2)
To add a second loop to the random color program you need a new, unique variable name. An easy way to do this is to increment the _i# value using _i2. For example, the code below runs the random color loop 20 times, then runs a second loop that replicates the colors of a traffic light 4 times:
JavaScript:
async function startProgram() {
// random colors
for (var _i1 = 0; _i1 < 20; _i1++) {
setMainLed(getRandomColor());
await delay(0.1);
}
//traffic light
for (var _i2 = 0; _i2 < 4; _i2++) {
setMainLed({ r: 0, g: 255, b: 0 });
await delay(0.8);
setMainLed({ r: 255, g: 243, b: 14 });
await delay(0.8);
setMainLed({ r: 255, g: 0, b: 0 });
await delay(0.8);
}
}
Python:
async def start_program():
# random colors
for _i1 in range(20):
set_main_led(get_random_color())
await delay(0.1)
# traffic light
for _i2 in range(4):
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(0.8)
set_main_led({'r': 255, 'g': 243, 'b': 14})
await delay(0.8)
set_main_led({'r': 255, 'g': 0, 'b': 0})
await delay(0.8)
Loop until (aka a "while" loop) repeats the code within until a condition is met. You will need to understand how to write conditions with Operators and Comparators before using Loop Until and the rest of the controls below.
JavaScript:
while ( !testCondition ) {
// code to loop until testCondition is true, then exit the loop
}
Python:
while not ( test_condition )
# code to loop until test_condition is true, then exit the loop
}
In this template, Test Condition is an expression that evaluates to true or false. In JavaScript, the ! operator, meaning "not", reverses the value of the test condition. In Python you use while not. The loop terminates when the test condition becomes true.
For example, you can repeat speed increases and use Loop Until to reach a "Speed Limit", such as is 80 in this example. Given 20 + (20*x) = 80, you should see the Loop repeat 3 times (hearing the Notification sound each time) before reaching Speed 80 and then stopping with the Skid sound. You will need about 12ft of clear floor space to run this program:
JavaScript:
async function startProgram() {
setMainLed({ r: 33, g: 255, b: 20 });
setSpeed(20);
while (!(getSpeed() === 80)) {
await Sound.Game.Notification.play(true);
setSpeed((getSpeed() + 20));
await delay(1.5);
}
setMainLed({ r: 255, g: 26, b: 62 });
setSpeed(0);
await Sound.Mechanical.Skid.play(true);
}
Python:
async def start_program():
set_main_led({'r': 33, 'g': 255, 'b': 20})
set_speed(20)
while not (get_speed() == 80):
await Sound.Game.Notification.play(True)
set_speed((get_speed() + 20))
await delay(1.5)
set_main_led({'r': 255, 'g': 26, 'b': 62})
set_speed(0)
await Sound.Mechanical.Skid.play(True)
Loop Forever (aka "while true" loop) repeats the code within forever, or until you stop the program.
JavaScript:
while (true)
{
// code to loop forever
}
Python:
while True:
# code to loop forever
For example, to create a game themed metronome that runs forever, use:
JavaScript:
async function startProgram() {
while (true) {
await Sound.Game.Coin.play(true);
setHeading((getHeading() + 180));
await delay(1.2);
await Sound.Game.Bubble.play(true);
setHeading((getHeading() - 180));
await delay(1.2);
}
}
Python:
async def start_program():
while True:
await Sound.Game.Coin.play(True)
set_heading((get_heading() + 180))
await delay(1.2)
await Sound.Game.Bubble.play(True)
set_heading((get_heading() - 180))
await delay(1.2)
You can nest a for loop inside the while true loop to make the metronome more interesting. For example, this version of the metronome replaces the delay code with a light sequence using a loop of light commands:
JavaScript:
async function startProgram() {
while (true) {
await Sound.Game.Coin.play(true);
setHeading((getHeading() + 180));
//green light blinks
for (var green_count = 0; green_count < 6; green_count++) {
setMainLed({ r: 9, g: 255, b: 5 });
await delay(0.1);
setMainLed({ r: 255, g: 247, b: 245 });
await delay(0.1);
}
await Sound.Game.Bubble.play(true);
setHeading((getHeading() - 180));
//red light blinks
for (var red_count = 0; red_count < 6; red_count++) {
setMainLed({ r: 255, g: 15, b: 0 });
await delay(0.1);
setMainLed({ r: 255, g: 233, b: 227 });
await delay(0.1);
}
}
}
Python:
async def start_program():
while True:
await Sound.Game.Coin.play(True)
set_heading((get_heading() + 180))
# green light blinks
for green_count in range(6):
set_main_led({'r': 9, 'g': 255, 'b': 5})
await delay(0.1)
set_main_led({'r': 255, 'g': 247, 'b': 245})
await delay(0.1)
await Sound.Game.Bubble.play(True)
set_heading((get_heading() - 180))
# red light blinks
for red_count in range(6):
set_main_led({'r': 255, 'g': 15, 'b': 0})
await delay(0.1)
set_main_led({'r': 255, 'g': 233, 'b': 227})
await delay(0.1)
If Then statements execute the code within only if the given condition is true.
JavaScript:
if (condition) {
// code executed if condition is true
}
Python:
if (condition):
# code executed if condition is true
For example, if you hold the robot and shake it, the lights will turn green and speak "Shake". You need to nest an if...then statement within a while true loop like the one below.
JavaScript:
async function startProgram() {
setStabilization(false);
while (true) {
if ((Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) > 1.4)) {
await speak("Shake", false);
setMainLed({ r: 0, g: 255, b: 0 });
await delay(1);
}
await delay(0.025);
}
}
Python:
async def start_program():
set_stabilization(False)
while True:
if (Math.sqrt((get_acceleration()['x'] ** 2) + (get_acceleration()['y'] ** 2) + (get_acceleration()['z'] ** 2)) > 1.4):
await speak("Shake", False)
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(1)
await delay(0.025)
The OR operator allows the code to execute if any of a set of conditions is true. In JavaScript, use || for the OR operator. In Python, use or.
Let's take the prior program and make it so that the forward pitch or the table tap will change the main LED's to green:
JavaScript:
async function startProgram() {
setStabilization(false);
while (true) {
if (((Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) > 1.4) || (getOrientation().pitch < -45))) {
await speak("Shake or Pitch", false);
setMainLed({ r: 0, g: 255, b: 0 });
await delay(1);
setMainLed({ r: 0, g: 0, b: 0 });
}
await delay(0.025);
}
}
Python:
async def start_program():
set_stabilization(False)
while True:
if ((Math.sqrt((get_acceleration()['x'] ** 2) + (get_acceleration()['y'] ** 2) + (get_acceleration()['z'] ** 2)) > 1.4) or (get_orientation()['pitch'] < -45)):
await speak("Shake or Pitch", False)
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(1)
set_main_led({'r': 0, 'g': 0, 'b': 0})
await delay(0.025)
The AND operator requires additional conditions to be true. In JavaScript, use && for the AND operator. In Python, use and. You can add as many required conditions as you want, but let's just add a second requirement to get the LED's to turn green. The second condition will be a forward pitch measured by the IMU. You will need to aim the robot ensuring the tail light faces you, pitch it forward 45°, then tap it on the table and the LED's will turn green if you have the pitch angle correct:
JavaScript:
async function startProgram() {
setStabilization(false);
setBackLed(255);
while (true) {
if (((Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) > 1.4) && (getOrientation().pitch < -45))) {
await speak("Shake and Pitch", false);
setMainLed({ r: 0, g: 255, b: 0 });
await delay(1);
setMainLed({ r: 0, g: 0, b: 0 });
}
await delay(0.025);
}
}
Python:
async def start_program():
set_stabilization(False)
set_back_led(255)
while True:
if ((Math.sqrt((get_acceleration()['x'] ** 2) + (get_acceleration()['y'] ** 2) + (get_acceleration()['z'] ** 2)) > 1.4) and (get_orientation()['pitch'] < -45)):
await speak("Shake and Pitch", False)
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(1)
set_main_led({'r': 0, 'g': 0, 'b': 0})
await delay(0.025)
If Then Else statements execute the code contained within the "if" code when the given condition is true; otherwise performs the "else" code.
JavaScript:
if (condition) {
// code executed if condition is true
} else {
// code executed if condition is false
{
}
Python:
if (condition):
# code executed if condition is true
else:
# code executed if condition is false
For example, let's build on the "if then" sample above by offering an "else" condition that sets the LED's to red when the condition is not true, but still turns green when you shake it:
JavaScript:
async function startProgram() {
setStabilization(false);
while (true) {
if ((Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) > 1.4)) {
await speak("Shake", false);
setMainLed({ r: 0, g: 255, b: 0 });
await delay(1);
} else {
setMainLed({ r: 255, g: 0, b: 0 });
}
await delay(0.025);
}
}
Python:
async def start_program():
set_stabilization(False)
while True:
if (Math.sqrt((get_acceleration()['x'] ** 2) + (get_acceleration()['y'] ** 2) + (get_acceleration()['z'] ** 2)) > 1.4):
await speak("Shake", False)
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(1)
else:
set_main_led({'r': 255, 'g': 0, 'b': 0})
await delay(0.025)
To create > 2 outcomes you can nest N "if then else" statements. For example, let's create a program with 3 conditions where the LED's are red at rest, blink green when you shake the robot and blink blue when you pitch the robot forward:
JavaScript:
async function startProgram() {
setStabilization(false);
setBackLed(255);
while (true) {
if ((Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) > 1.4)) {
await speak("Shake", false);
setMainLed({ r: 0, g: 255, b: 0 });
await delay(1);
} else {
if ((getOrientation().pitch < -45)) {
await speak("Pitch", false);
setMainLed({ r: 0, g: 0, b: 255 });
await delay(1);
} else {
setMainLed({ r: 255, g: 0, b: 0 });
}
}
await delay(0.025);
}
}
Python:
async def start_program():
set_stabilization(False)
set_back_led(255)
while True:
if (Math.sqrt((get_acceleration()['x'] ** 2) + (get_acceleration()['y'] ** 2) + (get_acceleration()['z'] ** 2)) > 1.4):
await speak("Shake", False)
set_main_led({'r': 0, 'g': 255, 'b': 0})
await delay(1)
else:
if (get_orientation()['pitch'] < -45):
await speak("Pitch", False)
set_main_led({'r': 0, 'g': 0, 'b': 255})
await delay(1)
else:
set_main_led({'r': 255, 'g': 0, 'b': 0})
await delay(0.025)
Immediately stops the program execution, equivalent to selecting the "Stop" button in Sphero Edu.
To roll for 5 seconds, then stop the program, use the following examples:
JavaScript:
async function startProgram() {
await roll(0, 100, 5);
exitProgram();
}
Python:
async def start_program():
await roll(0, 100, 5)
exit_program()
await() requires a time-based command to complete. This is automatically added to commands that require it in the block canvas like await roll and await delay that include a duration of time:
JavaScript:
async function startProgram() {
await roll(90, 100, 2);
}
Python:
async def start_program():
await roll(90, 100, 2)