04. Sketch Structure, Variables & Types
Write readable sketches and store values safely.
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.
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
- Use the onboard LED; no external circuit required
Worked sketch
Download .ino sketchconst 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
- const byte is sufficient for a pin number.
- The ! operator reverses a Boolean value.
- flashCount is unsigned long so it can count far beyond int range.
Test and record evidence
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.
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.