Menu
CoddyTech

Named Constants

Part of the First Circuits section of Coddy's Arduino journey. Lesson 13 of 22.

Put const in front of a variable and it becomes a constant: its value is set once and can never change.

const int ledPin = 7;

A name says what a pin is for: digitalWrite(ledPin, HIGH) reads better than digitalWrite(7, HIGH), which makes you remember what is on pin 7. If the LED moves to another pin, you change one line instead of hunting for every 7.

Storing a new value in a constant stops the sketch from compiling, with an error that says the variable is read-only. That protects values that should never change.

challenge icon

Challenge

Easy

The LED has moved to pin 7, but the starter still uses 13 in three places.

  • at the top, add const int ledPin = 7;
  • replace every 13 with ledPin

Press Run, then Check.

Try it yourself

// add the constant here

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

void loop() {
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
}
quiz iconTest yourself

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

All lessons in First Circuits

Practice on your own: Arduino playground