A variable is a named memory location in which you can store a value like a number. There are four types of variables: number, string, boolean, and color. You must declare a variable type when you create one, and you can't change it later. For example, to use as a counter you can "increment a variable named loopCount inside a loop that repeats 4 times. When loopCount = 4, set the LED to red. You can retrieve this value anywhere in your program using the variable's name. Any code that takes a value can take your named variable instead.
Below are a few basic techniques to use variables, but you are not limited to these.
Use the var, let, or const keywords to declare a new variable. let and const are preferred in most use cases.
var is a function-scoped way to declare a variable (legacy approach)
let is a block-scoped way to declare a variable (modern approach)
const is a block-scoped way to declare a variable in which it cannot be reassigned (modern approach)
The variable name must begin with either a letter, underscore(_), or $, and can contain letters, numbers, and the _ or $ characters.
Upper and lowercase letters are distinct (case-sensitive).
Variables should not use reserved keywords.
Use the = operator to assign a value to your variable.
It is good practice to use a new line for each variable, since it makes it easier to see them when reviewing your code, and you can comment out a single variable quickly if needed:
let driveTime = 3.55;
let repeat = 6.1;
let predict = 2;
async function startProgram() {
// code
}
However, you can do comma-separated declaration on one line. Generally, this is not recommended as common practice:
let driveTime = 3.55, repeat = 6.1, predict = 2;
async function startProgram() {
// code
}
Keywords are not needed when declaring a variable.
The variable name must begin with either a letter or underscore(_) and can contain letters, numbers, and _.
Upper and lowercase letters are distinct (case-sensitive).
Variables should not used reserved keywords.
Use the = operator to assign a value to your variable.
It is good practice to use a new line for each variable, since it makes it easier to see them when reviewing your code, and you can comment out a single variable quickly if needed:
drive_time = 3.55
repeat = 6.1
predict = 2
async def start_program():
# code
pass
To use the value stored in your variable, you must 'reference' the variable in your code. To do this, just write the name of your variable anywhere you want to use its value.
Use the following examples to make your robot change colors after a collision:
JavaScript:
var color = { r: 0, g: 255, b: 0 };
async function changeColor() {
color = { r: 255, g: 0, b: 0 };
};
registerEvent(EventType.onCollision, changeColor);
async function startProgram() {
while (true) {
setMainLed(color);
await delay(0.1);
}
};
Python:
color = {'r': 0, 'g': 255, 'b': 0}
async def changeColor():
global color
color = {'r': 255, 'g': 0, 'b': 0}
register_event(EventType.on_collision, changeColor)
async def start_program():
while True:
set_main_led(color)
await delay(0.1)
It's useful to set a variable value in the main loop to use as a counter based on a condition. For example, let's extend the collision program to say the number of collisions, using a numCollisions variable:
JavaScript:
var color = { r: 0, g: 255, b: 0 };
var numCollisions = 0;
var report = false;
async function changeColor() {
color = { r: 255, g: 0, b: 0 };
// Increase the number of collisions by 1 and
// tell the main loop to report the result.
++numCollisions;
report = true;
};
registerEvent(EventType.onCollision, changeColor);
async function startProgram() {
while (true) {
setMainLed(color);
if (report) {
// A new collision occurred. Tell the user.
await speak("" + numCollisions, true);
await delay(1);
color = { r: 0, g: 255, b: 0 };
report = false;
}
await delay(0.1);
}
};
Python:
color = {'r': 0, 'g': 255, 'b': 0}
numCollisions = 0
report = False
async def changeColor():
global color, numCollisions, report
color = {'r': 255, 'g': 0, 'b': 0}
# Increase the number of collisions by 1 and
# tell the main loop to report the result.
numCollisions += 1
report = True
register_event(EventType.on_collision, changeColor)
async def start_program():
global color, report
while True:
set_main_led(color)
if report:
# A new collision occurred. Tell the user.
await speak("" + str(numCollisions), True)
await delay(1)
color = {'r': 0, 'g': 255, 'b': 0}
report = False
await delay(0.1)
You can also compare two variable values to create conditional logic. Let's extend the color change program one last time. We'll make it exit when the user has reached a certain number of collisions:
JavaScript:
var color = { r: 0, g: 255, b: 0 };
var numCollisions = 0;
var report = false;
const MAX_COLLISIONS = 3; // <-- new variable
async function changeColor() {
color = { r: 255, g: 0, b: 0 };
// Increase the number of collisions by 1 and
// tell the main loop to report the result.
++numCollisions;
report = true;
};
registerEvent(EventType.onCollision, changeColor);
async function startProgram() {
while (true) {
setMainLed(color);
if (report) {
// A new collision occurred. Tell the user.
await speak("" + numCollisions, true);
await delay(1);
color = { r: 0, g: 255, b: 0 };
report = false;
// Check to see if we have reached the max number of collisions.
if (numCollisions === MAX_COLLISIONS) {
await speak("All done!", true);
await delay(1.5);
exitProgram();
}
}
await delay(0.1);
}
}
Python:
color = {'r': 0, 'g': 255, 'b': 0}
numCollisions = 0
report = False
MAX_COLLISIONS = 3 # <-- new variable
async def changeColor():
global color, numCollisions, report
color = {'r': 255, 'g': 0, 'b': 0}
# Increase the number of collisions by 1 and
# tell the main loop to report the result.
numCollisions += 1
report = True
register_event(EventType.on_collision, changeColor)
async def start_program():
global color, report
while True:
set_main_led(color)
if report:
# A new collision occurred. Tell the user.
await speak("" + str(numCollisions), True)
await delay(1)
color = {'r': 0, 'g': 255, 'b': 0}
report = False
# Check to see if we have reached the max number of collisions.
if numCollisions == MAX_COLLISIONS:
await speak("All done!", True)
await delay(1.5)
exit_program()
await delay(0.1)
A string variable is a text string value. These are very useful for naming the players in a game, determining outcomes, or speaking any dynamic text. Often they are concatenated in a speak command. As an example, you could use this in a program to "speak" that its a player's turn:
JavaScript:
async function startProgram() {
var playerName = "Edward";
await speak(buildString("It's your turn", playerName), true);
}
Python:
async def start_program():
playerName = "Edward"
await speak(build_string(["It's your turn", playerName]), True)
A boolean variable is a stored boolean value that can be assigned and operated on. Values can be true or false.
A color variable is an RGB value that relates to a color which can be used to to dynamically read and set color values. You can also generate a human readable color string name from an RGB value for the below colors. The table will convert your RGB values to the closest one in the chart if it does not match exactly.
For example, you can use the color variable to create a program that changes the Main LED to a random value after a spin, then speaks the color aloud:
JavaScript:
async function startProgram() {
while (true) {
await rawMotor(255, -255, 0.5);
var randomColor = {
r: getRandomInt(0, 255),
g: getRandomInt(0, 255),
b: getRandomInt(0, 255)
};
setMainLed(randomColor);
await speak(buildString(randomColor), true);
await delay(0.25);
}
}
Python:
async def start_program():
while True:
await raw_motor(255, -255, 0.5)
randomColor = {
'r': get_random_int(0, 255),
'g': get_random_int(0, 255),
'b': get_random_int(0, 255)
}
set_main_led(randomColor)
await speak(build_string([randomColor]), True)
await delay(0.25)