Writing and Using Functions

Writing and Using Functions in Arduino

If you’ve been writing Arduino sketches for a while, you might notice your code starting to get a little… messy. Maybe you’re repeating the same few lines over and over, or it’s getting hard to find where one section ends and another begins.

That’s where functions come in!

Functions are like little mini-programs inside your main code. They let you group tasks together, give them a name, and reuse them whenever you want. Think of them as “shortcuts” for your code that make everything cleaner and easier to understand.


🧠 What Is a Function?

A function is a reusable block of code that performs a specific task. You can write it once and call it whenever you need it.

You’ve already been using functions — like setup() and loop() — since your very first sketch!

Here’s what a simple custom function looks like:

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

Now you can call it anytime in your loop() function like this:

blinkLED();

Nice and clean!


🛠️ Parts of a Function

A typical function has three parts:

returnType functionName(parameters) {
  // code to execute
}

Let’s break that down:

  • returnType: tells Arduino what the function gives back (like int, float, or void if it returns nothing).
  • functionName: what you call it (try to name it something meaningful).
  • parameters: optional inputs your function can use.

Example:

int addNumbers(int a, int b) {
  return a + b;
}

You can use this function like:

int sum = addNumbers(3, 7);
Serial.println(sum);

🧩 The function adds the numbers and returns the total.


💡 Why Use Functions?

Using functions makes your code:
✅ Easier to read and debug
✅ Faster to modify
✅ Reusable for future projects
✅ More organized (no spaghetti code!)

When your projects start to grow — with sensors, motors, displays, and buttons — functions keep everything manageable.


🧰 Example: Controlling Multiple LEDs with Functions

Here’s a simple example where a function controls any LED you choose:

void setup() {
  for (int i = 2; i <= 6; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  blinkLED(3);
  blinkLED(5);
}

void blinkLED(int pinNumber) {
  digitalWrite(pinNumber, HIGH);
  delay(300);
  digitalWrite(pinNumber, LOW);
  delay(300);
}

🟢 What’s happening:
You can now blink any LED by just calling blinkLED() with a pin number — no repeated code!


🚀 In Summary

Functions are a programmer’s best friend.
They help you structure your Arduino code, save time, and make your sketches much easier to read.

Next time you find yourself copying the same lines more than once — stop and make a function!

Your future self will thank you.