Find a course

Module 4: Programming Your ArduinoLesson 7 of 1215 min

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.

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):

TypeSizeRange
bool1 bytetrue or false
byte1 byte0 to 255
int2 bytes−32,768 to 32,767
unsigned int2 bytes0 to 65,535
long4 bytesabout ±2.1 billion
unsigned long4 bytes0 to about 4.29 billion
float4 bytesdecimals, 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).

  1. Whether the alarm is armed
  2. An analogWrite level from 0 to 255
  3. An analogRead value from 0 to 1023
  4. The result of millis() after a week of running
  5. A temperature of 23.6 degrees

Step 3 of 13Compare

Uno data types: size and range

AspectSizeRange
bool1 bytetrue or false
byte1 byte0 to 255
int2 bytes−32,768 to 32,767
unsigned int2 bytes0 to 65,535
long4 bytesabout ±2.1 billion
unsigned long4 bytes0 to about 4.29 billion
float4 bytesdecimals, 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 everywhere

const 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.

Night light with two thresholdsLine chart with 10 categories: t1: Light reading 380, Turn-on threshold 300, Turn-off threshold 350; t2: Light reading 340, Turn-on threshold 300, Turn-off threshold 350; t3: Light reading 310, Turn-on threshold 300, Turn-off threshold 350; t4: Light reading 295, Turn-on threshold 300, Turn-off threshold 350; t5: Light reading 305, Turn-on threshold 300, Turn-off threshold 350; t6: Light reading 298, Turn-on threshold 300, Turn-off threshold 350; t7: Light reading 320, Turn-on threshold 300, Turn-off threshold 350; t8: Light reading 345, Turn-on threshold 300, Turn-off threshold 350; t9: Light reading 360, Turn-on threshold 300, Turn-off threshold 350; t10: Light reading 330, Turn-on threshold 300, Turn-off threshold 350.250300350400t1t2t3t4t5t6t7t8t9t10Sample
Illustrative readings at dusk and dawn.
Night light with two thresholds
SampleLight readingTurn-on thresholdTurn-off threshold
t1380300350
t2340300350
t3310300350
t4295300350
t5305300350
t6298300350
t7320300350
t8345300350
t9360300350
t10330300350

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

How a for loop runsCycle diagram: Test: i < 5? → Run the body → Update: i++.for (int i = 0;i < 5; i++)Test: i < 5?Run the bodyUpdate: i++

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.