0
0
Arduinoprogramming~5 mins

Code organization with functions in Arduino

Choose your learning style9 modes available
Introduction

Functions help keep your code neat and easy to understand. They let you reuse code without writing it again.

When you want to repeat a task multiple times in your program.
When your code is getting long and hard to read.
When you want to separate different parts of your program for clarity.
When you want to test small parts of your code separately.
When you want to make your program easier to fix or change later.
Syntax
Arduino
returnType functionName(parameters) {
  // code to run
}

returnType is the type of value the function gives back (like int, void, etc.).

If the function does not return a value, use void as returnType.

Examples
This function turns the built-in LED on and off with a half-second delay.
Arduino
void blinkLED() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}
This function takes two numbers and returns their sum.
Arduino
int addNumbers(int a, int b) {
  return a + b;
}
Sample Program

This program uses a function blinkLED to turn the built-in LED on and off repeatedly. The loop calls the function to keep blinking.

Arduino
#include <Arduino.h>

void blinkLED() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  blinkLED();
}
OutputSuccess
Important Notes

Functions make your code easier to read and fix.

Use clear names for your functions to know what they do.

Functions can take inputs (parameters) and give back outputs (return values).

Summary

Functions help organize code by grouping tasks.

They let you reuse code without repeating it.

Using functions makes your program easier to understand and maintain.