What is a variable and what is it for?

A variable is like a box for saving data, a value that we can view and come back to later on in the program. We can also change this saved value at any time.

box_var_2 box_a_5 box_var_cambio

Declaring variables:

On declaring, we create a ” box” and save the data in it for the first time. In bitbloq, that data can be a number type or text type. On declaring the variable, you define which type it is. For example, if the first thing you save is a number, that variable will always be for numbers so you can´t mix different types!

You can rename variables however you want. This feature will help you to identify your “box” at any time. Here are a few examples of variable declaration:

We can also save the value that a sensor returns directly. This case is usually seen in the following lessons:

Using variables:

With bitbloq, you have blocks for “looking in the box” (look at the value saved in the variable in that moment) and the blocks for saving a new value in it (deleting the previous one).

box_a_5 box_var_cambio

The difference between a GLOBAL variable and a LOCAL variable:

As we have explained in earlier lessons (see the  lessons on programming LEDs), the controller board executes the program that we load on it by following the blocks in order (from top to bottom) and repeating them infinitely in a loop.

That is why it´s important to know at which point in the program we use and declare the variables. LOCAL and GLOBAL variables can be programmed in bitbloq.

  • GLOBAL variables: created at the beginning as soon as you switch on the board,  even before starting the program loop.
  • LOCAL variables: created at the time of declaring the variable, now within the loop.

This is an example of incorrect code, as it attempts to use and compare the local variable which has not been declared. Remember that the code will be executed from top to bottom.

This would be the correct way of using it: we declare it first and then we use it.