Learn Arduino UNO · Lesson 5

Variables turn fixed code into a program you can control.

You have already used variables without dwelling on them. Now we make them the focus: names that hold numbers or states so the program becomes easier to read, change and extend.

25 minutesProgramming conceptReuse the LED circuit

Keep the same hardware

Use the LED on pin 8 from Lesson 1. No new components are needed. The lesson is deliberately about code, not rebuilding the circuit.

Goal: understand the difference between a fixed value, a constant and a variable that can change while the program runs.

▶ YOUTUBE DEMO PLACEHOLDERSuggested title: “Arduino Variables Explained With One LED”

Why use a variable?

Hard-coded
delay(500);
delay(500);

To change the speed, you may need to edit the same number in several places.

Named value
int delayTime = 500;

delay(delayTime);
delay(delayTime);

Change the value once and every place using the name changes with it.

Three useful kinds of value

const int ledPin = 8; — a value we do not intend to change. Good for pin numbers.

int delayTime = 500; — a whole-number variable that can change while the sketch runs.

bool ledState = false; — a true/false value, useful when something can be in one of two states.

Good variable names reduce comments. delayTime tells you far more than x. Code should be readable before it is clever.

Make the blink speed change

const int ledPin = 8;
int delayTime = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(delayTime);

  digitalWrite(ledPin, LOW);
  delay(delayTime);

  delayTime = delayTime - 100;

  if (delayTime < 100) {
    delayTime = 1000;
  }
}

Each loop subtracts 100 ms from delayTime. When it falls below 100 ms, the program resets it to 1000 ms. You can now see a variable changing while the program runs.

Experiments

  1. Start at 2000 ms and subtract 250 each loop.
  2. Change the minimum from 100 to 500.
  3. Create a second variable called offTime so ON and OFF times can be different.
  4. Predict the sequence on paper before uploading it.

Challenge

Create two variables: shortFlash and longFlash. Use them to recreate the short-short-long pattern from Lesson 1 without writing any raw timing number inside loop().