Programming patterns · Lesson
10 min read
Functions and arrays
Stop repeating yourself: group code into functions and data into arrays.
What You Will Learn
- Write functions with parameters and return values
- Loop over arrays of pins
A function packages steps under a name. Parameters pass values in; return passes a result out.
Arduino C++
int pins[] = {10, 11, 12};
void allOff() {
for (int i = 0; i < 3; i++) digitalWrite(pins[i], LOW);
}
int average(int a, int b) {
return (a + b) / 2;
}Traffic lightarduino-uno
Note: The traffic light uses a show() function with five parameters.
Arrays start at index 0. pins[3] in a 3-element array is outside the array — the simulator stops with an error; a real board silently corrupts memory.
Check Your Understanding
Test what you learned in this lesson