Arduino Basics: Arrays
Table of Contents
Arrays are used to store multiple values under a single variable name. They make your code cleaner, reduce repetition, and simplify tasks like controlling multiple LEDs, reading multiple sensors, or storing sensor data over time.
Declaring and Initializing Arrays
- Syntax for an integer array:
int ledPins[] = {2, 3, 4, 5};
- Each element can be accessed by its index, starting from 0:
int firstLED = ledPins[0]; // Access first element
int secondLED = ledPins[1]; // Access second element
Example: Blink Multiple LEDs in Sequence
int ledPins[] = {2, 3, 4, 5}; // LED pins
int numLEDs = 4; // Number of LEDs
void setup() {
for (int i = 0; i < numLEDs; i++) {
pinMode(ledPins[i], OUTPUT); // Set all LED pins as output
}
}
void loop() {
for (int i = 0; i < numLEDs; i++) {
digitalWrite(ledPins[i], HIGH); // Turn on LED
delay(250);
digitalWrite(ledPins[i], LOW); // Turn off LED
}
}
Benefits of Using Arrays
- Reduces repetitive code; no need to write multiple
digitalWrite()
lines. - Makes your program easier to maintain and expand; adding another LED only requires adding its pin to the array.
- Useful for storing sensor readings, storing user input, or creating sequences of actions.
Tips for Using Arrays
- Always keep track of the number of elements (length) in the array to avoid out-of-bounds errors.
- Combine arrays with
for
loops to iterate efficiently over multiple values. - Arrays can store integers, floats, characters, or even other arrays (multidimensional arrays).
By using arrays, you can write more efficient and scalable Arduino programs, especially when dealing with multiple devices or repeated operations.
×