Arduino Basics: Functions
Table of Contents
Functions are blocks of code that perform a specific task. They help you organize your Arduino program, avoid repeating code, and make your sketches easier to read, debug, and maintain. By using functions, you can break complex programs into smaller, manageable pieces.
Built-in Functions
Arduino provides some essential built-in functions that every sketch uses:
-
setup(): This function runs once at the beginning of the program. It is typically used to initialize pins, variables, and other settings. For example:
void setup() { pinMode(ledPin, OUTPUT); // Set LED pin as output }
-
loop(): After
setup()
finishes, theloop()
function runs repeatedly. It contains the main logic of your program and allows your Arduino to respond continuously to inputs or events:void loop() { blinkLED(); // Call a custom function to blink the LED }
Custom Functions
In addition to the built-in functions, you can create your own functions to perform repetitive or specialized tasks. This helps reduce code duplication and makes your program easier to understand.
Example:
void blinkLED() {
digitalWrite(ledPin, HIGH); // Turn LED on
delay(500); // Wait 500 milliseconds
digitalWrite(ledPin, LOW); // Turn LED off
delay(500); // Wait 500 milliseconds
}
Once you define blinkLED()
, you can call it multiple times within loop()
or even from other functions.
Why Functions Are Important
Reusability: You can write code once and use it many times without rewriting it.
Organization: Functions help break your program into logical sections, making it easier to read and debug.
Abstraction: By using functions, you can focus on high-level logic without worrying about the low-level details every time.
Collaboration: Functions allow multiple people to work on different parts of a program without interfering with each other’s code.
Example: Combining Built-in and Custom Functions
Here’s how a complete Arduino sketch might use both built-in and custom functions:
int ledPin = 13; // Built-in LED pin
void setup() {
pinMode(ledPin, OUTPUT); // Initialize LED pin
}
void loop() {
blinkLED(); // Call custom function
}
void blinkLED() {
digitalWrite(ledPin, HIGH); // Turn LED on
delay(500);
digitalWrite(ledPin, LOW); // Turn LED off
delay(500);
}
In this example, setup()
prepares the pin, loop()
repeatedly calls blinkLED()
, and blinkLED()
contains the specific instructions to blink the LED.