Variables, Decisions, Loops and Functions
Store values in the right data types, make decisions with if and else, repeat with for loops, and organize code into your own functions.
Welcome back!
Step 1 of 13Learn
Why your counter went negative
Ana builds a people counter for a school event. It works all morning, then at 32,768 visitors the display suddenly shows −32,768. Nothing is wrong with the sensor. She stored the count in an int.
Every variable has a type that decides how much memory it uses and what values it can hold. On the Uno (an 8-bit board):
| Type | Size | Range |
|---|---|---|
bool | 1 byte | true or false |
byte | 1 byte | 0 to 255 |
int | 2 bytes | −32,768 to 32,767 |
unsigned int | 2 bytes | 0 to 65,535 |
long | 4 bytes | about ±2.1 billion |
unsigned long | 4 bytes | 0 to about 4.29 billion |
float | 4 bytes | decimals, about 6 to 7 significant digits |
When a value passes the top of its range it overflows and wraps around, which is exactly what happened to Ana's counter. A long would have been fine.
On 32-bit boards such as the Uno R4 or ESP32, int is 4 bytes, so code that works there can overflow on a classic Uno. Memory is tight too: the Uno R3 has only 2,048 bytes of SRAM for all your variables, so choosing byte over int for small numbers sometimes matters.
Step 2 of 13Practice · Match the pairs
Match each value to the smallest sensible Uno data type.
Tap an answer, then tap the place where it belongs (or drag it there).
- Whether the alarm is armed
- An analogWrite level from 0 to 255
- An analogRead value from 0 to 1023
- The result of millis() after a week of running
- A temperature of 23.6 degrees
Step 3 of 13Compare
Uno data types: size and range
| Aspect | Size | Range |
|---|---|---|
| bool | 1 byte | true or false |
| byte | 1 byte | 0 to 255 |
| int | 2 bytes | −32,768 to 32,767 |
| unsigned int | 2 bytes | 0 to 65,535 |
| long | 4 bytes | about ±2.1 billion |
| unsigned long | 4 bytes | 0 to about 4.29 billion |
| float | 4 bytes | decimals, about 6–7 significant digits |
Step 4 of 13Learn
Constants, scope and naming
Good sketches name their pins instead of scattering numbers everywhere:
const int LED_PIN = 9;
const int BUTTON_PIN = 2;
int pressCount = 0; // global: visible everywhereconst tells the compiler the value never changes, so it can't be overwritten by accident, and changing the wiring later means editing one line. Names written in capitals for constants are a common convention.
Scope decides where a variable exists:
- A global variable, declared outside any function, keeps its value for the whole run and is visible in setup(), loop() and your own functions.
- A local variable, declared inside a function or a block, is created fresh each time that code runs and disappears when it ends.
A classic bug: declaring int count = 0; inside loop(). The count is reset to zero on every pass and never seems to grow. If a value must survive from one loop pass to the next, declare it globally, or inside the function with the keyword static.
Comments are free: they never reach the board. Use them to explain why (for example, "// 30 ms debounce, longer felt laggy") rather than repeating what the line obviously does.
Step 5 of 13Practice · Spot the mistake
This sketch should count button presses, but the count never goes above 1. Click the line that causes it.
Step 6 of 13Learn
Making decisions with if, else and comparisons
Hardware programs are full of decisions: if it's dark, turn on the light; if the temperature is above 30 °C, start the fan.
int light = analogRead(A0);
if (light < 300) {
digitalWrite(LED_PIN, HIGH);
} else if (light < 600) {
analogWrite(LED_PIN, 60);
} else {
digitalWrite(LED_PIN, LOW);
}Comparison operators: == equal, != not equal, <, >, <=, >=. Combine conditions with && (and), || (or) and ! (not):
if (temp > 30 && fanEnabled) { ... }The most famous C++ trap is writing = instead of ==. if (mode = 2) doesn't compare: it assigns 2 to mode, and since 2 counts as true, the block runs every time. The compiler allows it, so the bug can hide for hours.
Another real-world issue is chatter at a threshold. If the light hovers around 300, the lamp flickers on and off. The fix is hysteresis: switch on below 300 but only switch off above 350, so small wobbles don't toggle the output.
Step 7 of 13Practice · Choose one
A night light should turn on below a reading of 300 and off above 350. Why use two different thresholds?
Step 8 of 13Practice · Chart
Night light with two thresholds
The light turns on when the reading drops below 300 and only turns off again above 350. Small wobbles in between change nothing.
The light turned on at t4. Tap the first sample where it turns off again.
Tap the point that answers the question, then press Check.
| Sample | Light reading | Turn-on threshold | Turn-off threshold |
|---|---|---|---|
| t1 | 380 | 300 | 350 |
| t2 | 340 | 300 | 350 |
| t3 | 310 | 300 | 350 |
| t4 | 295 | 300 | 350 |
| t5 | 305 | 300 | 350 |
| t6 | 298 | 300 | 350 |
| t7 | 320 | 300 | 350 |
| t8 | 345 | 300 | 350 |
| t9 | 360 | 300 | 350 |
| t10 | 330 | 300 | 350 |
Step 9 of 13Learn
Loops and your own functions
A for loop repeats a block a set number of times:
for (int i = 0; i < 5; i++) {
digitalWrite(LED_PIN, HIGH); delay(100);
digitalWrite(LED_PIN, LOW); delay(100);
}The three parts are: start (i = 0), keep going while (i < 5), and step (i++). This runs with i = 0, 1, 2, 3, 4: five times. Writing i <= 5 would run six times, a classic off-by-one error.
Loops are perfect for arrays. An array stores several values under one name, counted from index 0:
const int leds[] = {4, 5, 6, 7};
for (int i = 0; i < 4; i++) pinMode(leds[i], OUTPUT);When a block of code is repeated or has a clear purpose, give it a name with a function:
void flash(int pin, int times) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH); delay(150);
digitalWrite(pin, LOW); delay(150);
}
}
float readVolts(int pin) {
return analogRead(pin) * 5.0 / 1023;
}void means the function returns nothing; float readVolts returns a decimal with return. Now loop() can read like a story: if (readVolts(A0) < 1.0) flash(9, 3);
Step 10 of 13Diagram
How a for loop runs
Tap a shape with to see more.
- Test: i < 5?
Checked before every pass. When it is false, the loop ends. The start value i = 0 is set once, before the first test.
- Run the body
Everything between the braces.
- Update: i++
Runs after the body, then control goes back to the test.
Step 11 of 13Practice · Work it out
How many times does the body of for (int i = 2; i <= 10; i += 2) run?
Step 12 of 13Note
Step 13 of 13Practice · Select all that apply
Which of these lines contain a bug, assuming int leds[4] holds four pin numbers? Select all that apply.
Select all that apply.
Lesson complete!