Sub topic 11
Writing Your Own Functions
Assume you can open, verify, and upload an Arduino sketch, and that you understand setup() and loop(). You should also know how to declare variables and use basic if statements.
A function is a named block of code that performs one task. You call the function when you need that task. Functions make a sketch easier to read, test, and change.
Why use functions?
Without functions, loop() can become a long list of unrelated instructions. A function gives each task a clear name:
blinkOnce()controls one blink.printStatus()sends information to the Serial Monitor.readAverage()reads and combines sensor values.
The Arduino framework calls setup() once and calls loop() repeatedly. You can define and call your own functions from either one.
Defining and calling a function
A function definition contains a return type, a name, parentheses, and a block of statements.
void blinkOnce() {
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}The return type is void, which means this function does not send a value back. The function name is blinkOnce. The statements inside the braces run whenever you call it.
Call the function by writing its name followed by parentheses:
const byte ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
blinkOnce();
delay(750);
}
void blinkOnce() {
digitalWrite(ledPin, HIGH);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
}The Arduino compiler accepts this common layout and finds the function after compiling the sketch. In ordinary C++, a function prototype may be needed before setup(). A prototype is a declaration that tells the compiler a function's name, return type, and parameters.
Passing information to a function
A parameter is a variable that receives a value from the caller. Parameters let one function handle different inputs.
const byte ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
blinkFor(100);
delay(900);
blinkFor(500);
delay(900);
}
void blinkFor(unsigned long duration) {
digitalWrite(ledPin, HIGH);
delay(duration);
digitalWrite(ledPin, LOW);
delay(duration);
}Here, duration is an unsigned long parameter. The call blinkFor(100) copies 100 into duration. The call blinkFor(500) uses a different value without requiring a second function.
Parameter types should match the values you expect. Use byte for small pin numbers, int for many whole-number readings, and unsigned long for values from functions such as millis().
Returning a value
A function can calculate and return a result. Replace void with the result's data type, then use return.
int doubleValue(int number) {
return number * 2;
}The caller can store the result in a variable:
int result = doubleValue(21);
Serial.println(result);A return statement immediately ends the function. Every path through a function with a non-void return type must provide a value.
Scope inside functions
A variable declared inside a function has local scope. It can be used only inside that function. A global variable is declared outside all functions and can be used by every function after its declaration.
Prefer parameters and return values when passing data. They make a function's inputs and outputs visible. Use global variables for shared hardware state when that is practical, but avoid making every value global.
A complete example
This sketch separates reading, deciding, and reporting. The function isDark() returns a Boolean value, which is either true or false.
const byte sensorPin = A0;
const byte ledPin = LED_BUILTIN;
const int darkLimit = 400;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int lightLevel = analogRead(sensorPin);
if (isDark(lightLevel)) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
printReading(lightLevel);
delay(250);
}
bool isDark(int reading) {
return reading < darkLimit;
}
void printReading(int reading) {
Serial.print("Light level: ");
Serial.println(reading);
}The loop() function coordinates the work. isDark() hides the comparison rule, while printReading() hides the Serial output details. If the threshold changes, you can edit darkLimit without rewriting the decision function.
Exercise
Write a function named isValidTemperature that accepts an int and returns true when the value is between 10 and 35 inclusive. Then show a call that stores the result in a variable named valid.
Show answer
bool isValidTemperature(int value) { return value >= 10 && value <= 35; } followed by bool valid = isValidTemperature(22);