Sub topic 3
Variables and data types
This chapter covers how Arduino sketches store values in named variables, and how the choice of data type affects memory use, arithmetic, and correctness. It assumes you can open, verify, and upload a sketch in the Arduino IDE. It also assumes you have an Uno-class board and know what a pin and a voltage are. You should already know that setup() runs once and loop() repeats.
What a variable is
A variable is a named location in memory that holds a value your program can read and change. When you declare one, you give it a type and a name. The type tells the compiler how many bytes to reserve and how to interpret the bits stored there.
int sensorValue = 0;This line declares a variable named sensorValue, gives it the type int, and sets its starting value to 0. If you leave out the starting value, a variable declared inside a function holds whatever garbage happened to be in memory. A global variable (declared outside every function) is set to 0 automatically. Initialize every variable explicitly so you never depend on that difference.
Names must start with a letter or underscore and may contain letters, digits, and underscores. They are case sensitive, so ledPin and LedPin are different variables. A common style is camelCase, such as previousReading.
Why types matter on a microcontroller
An Arduino Uno has an ATmega328P chip with only 2 KB of RAM. A desktop computer has millions of times more. Every byte counts, so choosing a type that is large enough but not wasteful is part of the craft. A wrong choice also causes bugs: a value that does not fit wraps around silently, and the compiler does not warn you at runtime.
The common data types
The sizes below are for AVR boards such as the Uno and Nano. Boards based on ARM or ESP chips use different sizes for some types, notably int.
| Type | Size on Uno | Range | Typical use |
|---|---|---|---|
| `bool` | 1 byte | `true` or `false` | Flags, on/off state |
| `byte` | 1 byte | 0 to 255 | Pin numbers, small counts |
| `char` | 1 byte | -128 to 127 | A single character |
| `int` | 2 bytes | -32,768 to 32,767 | Sensor readings, general integers |
| `unsigned int` | 2 bytes | 0 to 65,535 | Counts that never go negative |
| `long` | 4 bytes | about -2.1 billion to 2.1 billion | Large sums |
| `unsigned long` | 4 bytes | 0 to about 4.29 billion | Times from `millis()` |
| `float` | 4 bytes | about 6 to 7 significant digits | Fractional values |
Two details are worth remembering. First, double on the Uno is the same as float, with 4 bytes and no extra precision. Second, byte is an Arduino alias for unsigned char. The standard types uint8_t, int16_t, and uint32_t state the exact size in their names. Many programmers prefer them when the size matters, because they mean the same thing on every board.
Integers
Integer types hold whole numbers. The analogRead() function returns values from 0 to 1023 on the Uno, which fits comfortably in an int. A pin number such as 13 fits in a byte, which saves one byte compared to an int.
Types with the word unsigned hold only zero and positive values. That gives them twice the positive range of the signed version, because the bit that would mark the sign is used for the value.
Floating point
A float stores a number with a decimal point, such as 3.14 or 0.001. It is approximate, not exact. For example, adding 0.1 ten times may not give exactly 1.0. Floating-point math is also slow on AVR chips, because they have no hardware for it, and it adds code size. When you can, use integers. A temperature of 23.5 degrees can be stored as 235 tenths of a degree in an int, and you divide only when you print it.
Booleans and characters
A bool holds true or false. In practice, any nonzero value converts to true and zero converts to false. A char holds one character in single quotes, such as 'A'. Internally it is a small integer, and 'A' is 65 in the ASCII table.
Declaring and assigning
You can declare and assign in one step, or separately. Assignment uses a single =, which copies the value on the right into the variable on the left.
byte ledPin = 9;
int threshold;
bool ledOn = false;
void setup() {
Serial.begin(9600);
threshold = 512;
Serial.println(threshold);
}
void loop() {
}Here threshold is declared first and assigned in setup(). Both forms are legal. Declaring and initializing together is safer, since there is no moment when the variable holds an undefined value.
Overflow and wraparound
When arithmetic produces a value outside a type's range, the result wraps around. This is called overflow. It is one of the most common sources of confusing bugs in sketches.
void setup() {
Serial.begin(9600);
int big = 32767;
big = big + 1;
Serial.println(big);
byte small = 255;
small = small + 1;
Serial.println(small);
}
void loop() {
}On an Uno this prints -32768 and then 0. The int wraps from its maximum to its minimum, and the byte wraps from 255 to 0. Nothing crashes and no error appears. The program just continues with a wrong number.
A frequent real case is multiplying two int values that look small. Computing 60 * 1000 with plain integer literals on an Uno overflows, because both operands are 16-bit int values and the true answer, 60,000, exceeds 32,767. Mark at least one operand as a long to force 32-bit math:
unsigned long ms = 60UL * 1000;The UL suffix means "unsigned long." With it, the multiplication is done in 32 bits and the result 60,000 is stored correctly.
Integer division and mixing types
When both operands are integers, division discards the fractional part. So 7 / 2 is 3, not 3.5. Assigning that result to a float does not recover the lost fraction, because the division was already done in integers.
void setup() {
Serial.begin(9600);
int a = 7;
int b = 2;
float wrong = a / b;
float right = (float)a / b;
Serial.println(wrong);
Serial.println(right);
}
void loop() {
}This prints 3.00 and then 3.50. The expression (float)a is a cast, which converts the value to another type for that one calculation. Once one operand is a float, the other is promoted to float and the division keeps its fraction.
Mixing signed and unsigned values is a related trap. If you compare a negative int with an unsigned int, the negative number is converted to a large positive one, and the comparison can give a surprising answer. Keep the types of values you compare the same.
Choosing a type
A short checklist helps you decide:
- Is the value a whole number? Use an integer type. Reserve
floatfor cases that truly need fractions. - Can it be negative? If not, an
unsignedtype orbyteis a natural fit. - What is its largest possible value, including intermediate results of math? Pick the smallest type that holds it with room to spare.
- Is it a time from
millis()? Useunsigned long, always. - Is it a yes/no state? Use
bool.
Saving a byte or two in a single variable rarely matters. The savings add up for large arrays, which a later chapter covers, and they matter most when you store hundreds of readings.
Common errors
- Using
intformillis()results. The function returns anunsigned long. Storing it in a 16-bitintoverflows after about 32 seconds. - Forgetting the fraction in integer division. Cast one operand to
float, or use afloatliteral such as2.0. - Overflow in intermediate math. The type of the variable receiving the result does not matter. The type of the operands decides how the math is done.
- Assuming
intis 2 bytes everywhere. On 32-bit boards it is 4 bytes. If your code depends on the size, useint16_torint32_t. - Reading an uninitialized local variable. It holds leftover data. Always give it a starting value.
Putting it together
The sketch below reads an analog sensor, scales it to a percentage using integer math, and uses a bool flag for state. Each type is chosen for the range of its value.
const byte sensorPin = A0;
const byte ledPin = LED_BUILTIN;
const int highLevel = 70;
int rawValue = 0;
byte percent = 0;
bool isHigh = false;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
rawValue = analogRead(sensorPin);
percent = (long)rawValue * 100 / 1023;
isHigh = percent >= highLevel;
digitalWrite(ledPin, isHigh ? HIGH : LOW);
Serial.print("Raw: ");
Serial.print(rawValue);
Serial.print(" Percent: ");
Serial.println(percent);
delay(300);
}The cast (long)rawValue matters. Without it, rawValue * 100 could reach 102,300, which overflows a 16-bit int. The result is 0 to 100, so a byte holds it. The pin numbers never change, so they are const byte values.
Exercise
On an Uno, what does int x = 300 * 200; store in x, and how would you change the code so it stores the correct product of 60,000?
Show answer
The multiplication uses 16-bit int operands, so the true result of 60,000 exceeds the 32,767 limit and wraps around, leaving a wrong value (it is -5536). To fix it, do the math in 32 bits and store the result in a type that can hold it, for example unsigned long x = 300UL * 200; or long x = 300L * 200;. Note that a plain long holds 60,000 easily, but only if at least one operand is a long before the multiplication happens.
Exercise
A sketch computes float average = total / count; where total and count are both int, and it prints 2.00 when the real average is 2.5. What is wrong, and what is one fix?
Show answer
Both operands are integers, so the division discards the fraction before the result is assigned to the float. One fix is to cast an operand: float average = (float)total / count;. Writing total / (float)count or using 2.0-style float literals also works.