Sub topic 3
Scope and lifetime: local, global, and static variables
This chapter assumes you can open, verify, and upload a sketch, and that you have an Arduino board with an LED and resistor on a breadboard. You should also know the basics of setup(), loop(), and the data types int, byte, and unsigned long.
Scope is where a variable name can be used. Lifetime is how long the variable exists in memory.
- A global variable is declared outside every function. It can be used anywhere, and it lives for the whole run.
- A local variable is declared inside a function. It exists only while that function runs. Each call creates it fresh.
- A static local variable is declared inside a function with the
statickeyword. It is visible only in that function, but it keeps its value between calls.
int ticks = 0; // global: lives for the whole run
int addOne(int value) { // 'value' is a parameter, local to addOne()
int result = value + 1; // local: created on each call, destroyed on return
return result;
}
void setup() {
Serial.begin(9600);
}
void loop() {
static int calls = 0; // static: keeps its value between loop() passes
calls++;
ticks = addOne(ticks);
Serial.print(calls);
Serial.print(" ");
Serial.println(ticks);
delay(1000);
}Writing your own functions
A function is a named block of code you call by name. Its header lists the return type, the name, and the parameters in parentheses. addOne() above returns an int and takes one int parameter.
Parameters and return values
A parameter passes a copy of a value into a function. Changing it inside the function does not change the caller's variable. A return value sends one result back to the caller.
int readAverage(int pin, byte samples) {
long total = 0;
for (byte i = 0; i < samples; i++) {
total += analogRead(pin);
delay(2);
}
return total / samples;
}> Note: the delay() calls in this function block the whole sketch until they finish.
Timing without delay() using millis()
delay() stops the sketch, so nothing else can run. millis() returns the milliseconds since the board started. Comparing against it lets loop() keep running.
const byte ledPin = LED_BUILTIN;
const unsigned long interval = 500;
unsigned long previousMillis = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= interval) {
previousMillis = now;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
// Other work can run here on every pass through loop().
}Exercise
In the first example, what does ticks print after loop() has run three times?
Show answer
It prints 1, 2, and 3 on successive passes. Here ticks is global, so each call to addOne() adds one to the value kept from the previous pass, and the printed calls value rises alongside it.