Link Search Menu Expand Document

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

  1. Introducing Variable Types
    1. Declaring variables
    2. Global versus local variables
  2. Bits and Bytes
  3. Integers
    1. int and long
    2. Unsigned integer types
    3. Integer arithmetic
  4. Floating point
    1. Floating point arithmetic
  5. 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