Digital Sandbox Arduino Companion

Pages
Contributors: jimblom
Favorited Favorite 5

6. Number Storage with Variables

The herky-jerky fading from experiment four accomplished the task, but just think of all the values we were missing! How do we make the LED fade smoothly? You can whip out 256 minutely different analogWrite() blocks, or you can reduce it to one, using variables.

Background Information

Variables are like storage containers for numbers. We can put any number in a variable, and either recall it and put it to use, or manipulate it to change the value it stores. Anywhere you stick a literal number (like "0" or "255") you can instead use a variable.

There are a few rules when it comes to creating a variable. They can be any word, but they must begin with a letter, and they can't have spaces (use "_" instead). They are case sensitive, so a variable named "fade" isn't the same variable as "Fade." Try to keep variables short, but use descriptive words to keep your code legible.

Active Parts

alt text

Code Components

We've been slacking off on introducing new functions and syntax, so it's time to throw some new stuff at you! As you'll discover, there's a lot that goes into creating and using a variable.

Declaring Variables

In order to use a variable, you first have to declare it. There are two parts to a variable declaration: a name and a type.

There are a few hard-coded rules to variable naming: a name can't start with a number and it can't contain spaces or special characters. Variables can only be composed of 0-9, a-z, A-Z, and _. When you're picking out a name for a variable try to make it descriptive, that'll help to make your code easier to read and write.

A variable type determines the minimum and maximum values a variable can be. There's no such thing as infinity in an Arduino -- there are limits to how big a number can be. In this example we'll be using one of the more fundamental variable types out there: int. An int variable can be anywhere from -32768 to 32767 -- plenty of room for us to play with. (Those seemingly random numbers come from the fact that an int is a 16-bit signed value, which means the range is from 215 to 215-1.)

Once you've picked out your variable type and name, you can declare it like this:

language:c
int example_variable;  // Declare a variable of type int, named example_variable

That's it! Now you can store numbers in the example_variable variable, and even manipulate it with some math.

Variable Scope

You can declare a variable anywhere in your code, but exactly where you declare it is actually really important, because every variable has scope. A variable's scope determines where it can be used and recalled. As a general rule of thumb, a variable can only be used within the curly bracket's ({ and }) that is was declared in -- that's its scope.

You can create a global variable by declaring your variable above setup(). Global variables can be used in both the setup() and loop() functions.

But, on the other hand, if you create a variable inside setup() that variable's scope is limited to the setup() function. So we can't create a variable in setup() and use it inside loop() -- it's out of scope!

Using Variables

To assign a value to a variable, you use the assignment operator -- =. The assignment operator takes the value on the right-side of the equals-sign, and stores it into the value on the left side.

So, for example, if we want to assign the value 5 to our example_variable variable, this line of code will do:

language:c
example_variable = 5;

But you can do so much more with variables than static value assignments. Variables are awesome because we can do math on them. You can add, subtract, multiply, or divide a variable with any one of these symbols:

Math OperationCode symbol
Add+
Subtract-
Multiply*
Divide/
Remainder%


You can use the Sandbox as a calculator, make it do some hard math with lines like this:

language:c
example_variable = (1024 / 8) * 52 - 163;

Parenthesis can be used, as they are in the above example, to define an order of operations. The stuff inside the parenthesis happens first, then multiplications and divisions, then additions and subtractions.

You're not limited to literal values on the right-hand side either! You can perform math on variables and store them into other variables. You can even perform math on a variable and store it in the same variable. For example, if I wanted to increase the value of example_variable by 1, this line of code would do:

language:c
example_variable = example_variable + 1;

In that case, if example_variable was 0, after running that line of code it would become 1.

Sketch and Experiment

Whew! That's a lot to read about variables. As you begin to use them, though, all of that information will start to become ingrained in your brain. Here's our sketch:

language:c
// Sandbox 06: Number Storage with Variables

/* The herky-jerky fading from experiment four accomplished the task, but just 
   think of all the values we were missing! How do we make the LED fade 
   smoothly? You can whip out 256 minutely different analogWrite() blocks, or 
   you can reduce it to one, using variables.

   Variables are like storage containers for numbers. We can put any number in a 
   variable, and either recall it and put it to use, or manipulate it to change
   the value it stores. Anywhere you stick a literal number (like "0" or "255") 
   you can instead use a variable.
*/

// To declare a variable you need two things: a type and a name. The type
// determines how much space in memory the variable takes up. The most standard
// variable type is int. int's can be either positive or negative. They take up
// 16-bits of space in your Arduino, so they can be anywhere from -32768 (2^15)
// to 32767 (2^15 - 1).
int fade;   // Decalare an int type of variable called "fade"

// Anything defined in the space _above_ setup() is GLOBAL. A global variable
// can be used in both the setup() and loop() functions. We'll want to use fade
// in both of those functions.

void setup()
{
    pinMode(5, OUTPUT); // Set pin 5 as an OUTPUT

    fade = 0;   // Set fade to 0, give it an initial value
}

void loop()
{
    // Set the LED on pin 5 to the value of "fade":
    analogWrite(5, fade);

    // Increment fade by 1. Code math takes the value on the right side of the
    // equation, and stores it into the variable on the left side.
    // This equation says take the original value of fade, add 1 to it, and
    // store that sum in the fade variable.
    fade = fade + 1;    // Increment fade by 1

    delay(500); // Wait half a second
}

Copy the code above, or open the Sandbox_06_Storage_w_Variables.ino sketch. Upload away and keep an eye on the D5 LED. Much smoother!

Your Turn!

  • Can you make the LED fade from HIGH to LOW? (Hint: You may need to change the setup value of fade, and change the + to a -.)
  • Can you make other LEDs fade? How about more than one fading at the same time? Can you do the math to make the D6 LED fade in the direction opposite of our D5 LED? (Hint: try adding an analogWrite(6, 255-fade) function call somewhere.)