Menu
CoddyTech

Your First Function

Part of the Inputs section of Coddy's Arduino journey. Lesson 19 of 22.

A function is a block of code with a name. You have been calling functions all along: pinMode(), delay(), Serial.println(). setup() and loop() are functions too, ones the board calls for you. You can write your own:

void blinkOnce() {
  digitalWrite(13, HIGH);
  delay(200);
  digitalWrite(13, LOW);
  delay(200);
}

void means the function gives nothing back; it only does something. The name is followed by (), and the code it runs goes between the braces.

Writing a function does not run it. A call does: blinkOnce(); runs the whole block, then the sketch carries on from the line after the call. Call it twice and it blinks twice. The function goes outside setup() and loop(), on its own.

A good name says what the code does, so loop() reads like a list of steps.

challenge icon

Challenge

Easy

The LED is on pin 13. Make a heartbeat, two quick blinks and a rest:

  • write void blinkOnce(): LED on, wait 200 ms, off, wait 200 ms
  • in loop(), call it twice, then wait 1000 ms

Press Run, then Check.

Try it yourself

const int ledPin = 13;

// write void blinkOnce() here

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

void loop() {
  // call blinkOnce() twice, then wait 1000 ms
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground