Block Programming - Variables
- njrohanjay
- Apr 2, 2022
- 2 min read
Updated: May 23, 2023
Variables in block programming work similarly to those in text-based programming languages. They allow you to store and manipulate data in your program. Let's dive into their usage with an example:
Example: Distance Tracker
Imagine we have a robot that's capable of tracking the distance it has traveled. To do this, we'll need to create and use variables.
Creating a Variable: We start by creating a variable block named 'distance'. This variable will hold the total distance the robot has traveled.
Initializing the Variable: We'll set the initial value of 'distance' to 0 since the robot hasn't moved yet.
Updating the Variable: As our robot moves forward, we'll need to increment the value of 'distance' to reflect the new total distance traveled. For example, if our robot moves forward by 5 units, we'll add 5 to our 'distance' variable.
Displaying the Variable: We can use the 'distance' variable to display the total distance traveled on an LCD display connected to our robot.
The pseudocode for the blocks could look something like this:
# Create a variable 'distance'
distance = 0
# Inside a loop that controls the robot's movement:
repeat until program ends:
move_forward(5) # Move the robot forward 5 units
distance = distance + 5 # Add the distance moved to the total
display_on_LCD("Total Distance: ", distance) # Display the total distance
This program will continuously move the robot forward in increments of 5 units and update the 'distance' variable accordingly. It will then display the total distance traveled on an LCD screen.
Firstly, in your block programming interface, you'd look for a block that says Create variable... or something similar. This is where you'd enter the variable name, for our example it's 'distance'.
Next, you'll want to find a block that allows you to set or initialize the variable. For 'distance', we'd set it to 0 to start with.
Now, every time your robot moves, you'll want to update the value of 'distance'. In the block programming interface, this would look like finding a block that allows you to change the variable by a certain value. If your robot moves forward by 5 units each time, you'd use this block to add 5 to 'distance' every time the robot moves.
Lastly, you'll want to display the 'distance' variable. This will depend on your specific robot kit and block programming interface, but you'd generally look for a block that allows you to print or display a variable.
In a simplified sequence of blocks, it could look like this:
Create variable... > (input 'distance')
Set variable... > ('distance' to 0)
(In a loop) Move robot forward... > (by 5 units)
(In the same loop) Change variable... > ('distance' by 5)
(In the same loop) Display on LCD... > ('distance')
Comments