What is a Function?
A function is a named block of code that performs a specific task. You write it once and call it whenever you need it.
Arduino's Built-in Functions
Every Arduino sketch has two required functions:
void setup() {
// Runs once at startup
}
void loop() {
// Runs forever, repeatedly
}
Creating Your Own
returnType functionName(parameters) {
// code
return value; // if not void
}
Examples
Function with no return value
void blinkLED(int pin, int duration) {
digitalWrite(pin, HIGH);
delay(duration);
digitalWrite(pin, LOW);
delay(duration);
}
Function that returns a value
float celsiusToFahrenheit(float celsius) {
return (celsius * 9.0 / 5.0) + 32.0;
}
Function that returns bool
bool isButtonPressed(int pin) {
return digitalRead(pin) == LOW;
}
Why Use Functions?
- Readability:
blinkLED(13, 500)is clearer than 4 lines of code - Reusability: Write once, call many times
- Debugging: Fix a bug in one place
- Organization: Break complex programs into small pieces
Tips
- Keep functions focused. Each one should do ONE thing
- Use descriptive names:
readTemperature()notdoStuff() - Put function definitions above
loop()or use forward declarations