Arduino Variables
A variable is a symbol associated with a chunk of computer memory in the running program. Think of a variable as a box that can hold different types of information such as integers, fractions, letters or logical values (True
or False
).
Mike Likes Science has an rap on variables and a longer review video on variables.
Table of contents
- Introducing Variable Types
- Bits and Bytes
- Integers
- Floating point
- Lecture notes and exercises from ME 120
Introducing Variable Types
Each variable in an Arduino sketch must be declared and in the declaration the variable is given a type. Here are some variable declarations.
float a, b, d;
int c;
The first line declares (think “creates”) three variables, a
, b
and d
that have the type called float
. A float
is a variable type that can store fractional values. Here are examples of fractional values that can be stored in float
variables.
1.2345
-0.00023
5.0
The statement int c
declares that c
can only hold integer values, i.e., numerical values with no fractional part. More information on variable types is
Declaring variables
All variables must be declared before being used.
Old school: Declare variables at the start of a function.
Java style: Declare variables where they are first used
Global versus local variables
Bits and Bytes
Humans usually think in decimal (base 10) values when counting.
Binary (base 2) values are at the core of all programming languages and hardware implementations.
- A bit is a binary digit, either a 1 or a 0 (zero).
- A byte is a group of 8 bits.
Integers
int
and long
An int
is an integer (usually) stored with 16 bits. The range of values stored in a (16 bit) int
is -32768 to 32767.
A long
is an integer (usually) stored with 32 bits
Unsigned integer types
Integer arithmetic
Floating point
Floating point arithmetic
Lecture notes and exercises from ME 120
- Lecture slides in PDF start with
blink
and introduce variables - Detailed lecture notes on variable types
- Demonstration of integer types for counting time: or, Why you need to use
long
instead ofint
when storing output frommillis()
- Worksheet to compare variable types: Blank version (recommended for learning) and the completed version after you have studied with the blank version