Unit A - Foundations

04. Sketch Structure, Variables & Types

Write readable sketches and store values safely.

Estimated time 3 hours

Learning outcomes

  • Use setup and loop correctly
  • Declare constants and variables
  • Choose suitable Uno data types
  • Explain scope, comments and semicolons

Parts and preparation

Arduino Uno and IDE.

Before power: inspect wiring, confirm supply voltage and ensure all connected circuits share GND.

Sketch Structure, Variables & Types instructional connection diagram
Open the diagram for a larger view. Trace every connection before building.

Program structure

Global declarations appear before setup. setup runs once for configuration. loop repeats. Functions can be added below or above these functions.

Types on an Uno

byte stores 0-255; int stores -32768 to 32767; unsigned long is useful for millis; float stores approximate decimal values; bool stores true/false; char stores one character.

Constants and scope

Use const for pin numbers and values that must not change. Name pins in UPPERCASE such as LED_PIN. A global name is visible to many functions; a local variable exists only inside its block. Prefer the narrowest useful scope.

Syntax and style

C++ is case-sensitive. Statements usually end with semicolons. Opening braces sit on the same line as if/for/while/function headers; indent nested blocks by 2 spaces. // begins a line comment and /* ... */ encloses a block comment.

Wiring and safe build sequence

  1. Use the onboard LED; no external circuit required
Power rule: switch off before moving wires. Arduino I/O pins are control signals; high-current loads require a driver and suitable external supply.
const byte ledPin = LED_BUILTIN;
unsigned long flashCount = 0;
bool ledOn = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  ledOn = !ledOn;
  digitalWrite(ledPin, ledOn);
  flashCount++;
  Serial.println(flashCount);
  delay(500);
}

How the code works

  1. const byte is sufficient for a pin number.
  2. The ! operator reverses a Boolean value.
  3. flashCount is unsigned long so it can count far beyond int range.

Test and record evidence

Expected result: The LED toggles every half-second and Serial prints the cycle count.

Practical evidence checklist

Common faults and checks
  • Check exact capitalization of setup, loop, HIGH and LOW.
  • A missing semicolon often causes an error on the next line.
Extension challenge: Move a variable inside loop and explain how that changes its lifetime and value.

Check your understanding

Q1. Why use const for a pin number?

Show answer

It documents that the value must not change and lets the compiler prevent reassignment.

Q2. What is local scope?

Show answer

The region inside a block/function where a declared name is visible.