মূল বিষয়বস্তুতে যান
Learn/Programming patterns/Functions and arrays
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
Open in Lab
UNOATmega328P: The 8-bit AVR microcontroller that runs your sketch (16 MHz, 32 KB flash, 2 KB RAM).ATmega328PUSB-B: USB connection for uploading sketches and for the Serial Monitor. Also powers the board (5 V).DC jack: Barrel jack for 7–12 V from a battery pack or adapter (centre positive).ATmega16U2: Converts USB to serial for uploads and Serial.print().RESET: Restarts your sketch from the beginning (setup() runs again).L (D13): Built-in LED connected to pin 13 (LED_BUILTIN).ON: Power indicator.5 V regulator: Turns 7–12 V from VIN/jack into a steady 5 V.16 MHz: Clock source: the microcontroller runs 16 million cycles per second.ICSP: In-circuit programming header (SPI). Used to burn a bootloader; not needed for normal uploads.220 Ω220 Ω220 Ω+++
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

1int v[4] = {5, 6, 7, 8}; What is v[1]?