3

(coco) #1
FORGE

int myInt;

Typically, you’ll name your variables so the variable
name says something about the value stored in
the variable; this improves code readability. For
example, if you were writing a sketch that recorded
temperature values (like the examples in the Arduino
tutorial in issue 3), you’d create a variable to store
the current temperature (and self-describe itself)
using the following:


float currentTemp;

In this example, I created a float variable since I
know temperature will be a decimal value.
To assign a value to a variable, use an equals sign:
myInt = 42;


You can also assign an initial value to a variable as
you’re defining the variable:


int myInt = 42;

To use a variable in an expression, simply refer
to the variable by name in your code. When the
compiler reaches the variable reference, it will
generate the code to retrieve the data from the
variable’s memory location and pass it into the
expression. For example, to convert a temperature
value from Celsius to Fahrenheit, you would write
the following code:


float tempC = 17.5;
float tempF;
tempF = (tempC * 1.8) + 32;

The value assigned to tempF is calculated using
the value stored in tempC.
Variables can be defined at any point in the
sketch, but they behave a little differently
depending on where they’re defined. If you
define them at the start of the sketch (before the
setup() function), you can access the variable
from anywhere. This is known as a global variable.
However, if you define a variable within a function,
you can only access the variable from within the
function you define it in. This is known as the scope
of the variable.
Variable names must be unique – you can’t create
two variables with the same name in the same
scope. You can’t have two global variables called
mySpecialVariable, but you could have two local
variables called myInt, if each variable is defined

Development languages
such as Arduino’s language
provide mechanisms for
managing data



Each variable can only hold one type of data, which
you have to define when you create the variable.
The most popular options are:

-^ int^ A whole number between -32^ 768 and^
32 767 on 16-bit boards such as the
Arduino Uno and -2 147 483 648 to
2 147 483 647 on 32-bit boards like the
Zero or MKR1000.
-^ long^ A whole number between^
-2 147 483 648 and 2 147 483 647.
-^ float^ A number that can include decimal^
places between 3.402823510^+38 and
as low as -3.4028235
10^38. However,
only the first six or seven significant
figures are preserved.
-^ string^ Text (which needs to be quoted for it
to be assigned to the variable).



  • char^ A single byte which can represent an^
    ASCII character.


VARIABLE TYPES


Figure 2
The Arduino compiler will try to highlight the line that
causes the error, but this is sometimes misleading

Assigning a value
to a variable uses a
single equals sign
(=); comparing two
values uses a double
equals sign (==).

QUICK TIP

Free download pdf