30 Days Lost in Space → Help Center

Coding Concepts

Functions

Organize your code into reusable blocks. Functions make programs easier to read, debug, and maintain.

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?

  1. Readability: blinkLED(13, 500) is clearer than 4 lines of code
  2. Reusability: Write once, call many times
  3. Debugging: Fix a bug in one place
  4. Organization: Break complex programs into small pieces

Tips

  • Keep functions focused. Each one should do ONE thing
  • Use descriptive names: readTemperature() not doStuff()
  • Put function definitions above loop() or use forward declarations