Variables
Learn how to initialize, store, and manipulate variables
What are Variables?
Variables are a way to store information in a program. The easiest way to think of them is as if they were boxes. In these boxes we can store stuff and we can write a name on the box to help us know which box is the one we want. One box can be named kitchen and has plates in it, another could be named books and has books in it, of course another could be named blankets and has lamps in it. With variables we can do the same thing.
[crayon-670b2de7a4665373215859/]
This creates a variable named “values” and puts the number 6 into it. We can also store more than just numbers.
[crayon-670b2de7a466b002888031/]
This one creates a variable named “letters” and stores the letter ‘S’ into it. You may notice that with values we started with “int”, but then with letters we started with “char”. That first word tells it what type of information will be stored in the variable. There are three main types that we will be using:
int: numbers from -32,768 to 32,767
char: letters (it really holds number that represent letters)
byte: numbers from -128 to 127
We only need to have the data type labeled when we create the variable, not every time we use it, for example in this code:
[crayon-670b2de7a466d665162371/]
We do not need the int the second time since we already created the variable.
Also we can set variables equal to other variables.
[crayon-670b2de7a466f146791745/]
Or even to themselves (with some math too):
[crayon-670b2de7a4670420279347/]
Here is an example program using variables:
[crayon-670b2de7a4671337459350/]
At the top of the code we created two variables, A and B. Then inside of setup we started the communication with the Serial monitor (Serial.begin(9600);). Then inside of loop we have a few things happening. Firstly we add one to A every time through the loop (A = A + 1;), then we print out the value of A onto the Serial monitor. Next we set B to half of A (B = A / 2;), and then print it out onto the screen. Then we have a short delay of 0.1 seconds to slow down the loop so that we can see what is happening (delay(100);). If we run this program and watch the Serial monitor we can see the values of A going up by one every time, and B always being half of A. To open the Serial monitor click on the magnifying glass in the top right corner.