Introduction

Here’s a sketch with three different stages. Each stage acts like a mini-sketch. It has its own behavior, and is implemented by its own code*.* There is a rule for when to change to a different stage.

The program’s knowledge of which stage it is in at the moment is part of its program state. This state is stored in a variable (stage).

This particular sketch could be written more simply, by putting everything inside of loop(). (There is an example of this at the end of this document.) This is because each of the stages is very simple. This pattern also works for larger and more complicated sketches, though.

const int PIN_LED_1 = 13;
const int PIN_LED_2 = 4;
const int PIN_BUTTON = 5;

int stage = 1;

void setup() {
  pinMode(PIN_BUTTON, INPUT);
  pinMode(PIN_LED_1, OUTPUT);
  pinMode(PIN_LED_2, OUTPUT);
}

void loop() {
  switch (stage) {
    case 1:
      stage1();
      break;
    case 2:
      stage2();
      break;
    case 3:
      stage3();
      break;
  }
}

// Stage 1:
// LED 1 is on, LED 2 is off.
// If the button is pressed, advance to stage 2.
void stage1() {
  digitalWrite(PIN_LED_1, HIGH);
  digitalWrite(PIN_LED_2, LOW);
  if (digitalRead(PIN_BUTTON) == HIGH) {
    stage = 2;
  }
}

// Stage 2:
// LED 1 is off, LED 2 is on.
// If the button is released, advance to stage 3.
void stage2() {
  digitalWrite(PIN_LED_1, LOW);
  digitalWrite(PIN_LED_2, HIGH);
  if (digitalRead(PIN_BUTTON) == LOW) {
    stage = 3;
  }
}

// Stage 3:
// Both LEDs are on.
// Delay for 100 millis, then advance to to stage 1.
void stage3() {
  digitalWrite(PIN_LED_1, HIGH);
  digitalWrite(PIN_LED_2, HIGH);
  delay(100);
  stage = 1;
}

Screenshot of Safari (3-17-22, 10-23-42 PM).png

Combining Sketches into Stages

Anatomy of a Sketch

A sketch has these parts:

  1. Include statements #include
  2. Variable declarations
  3. setup()
  4. loop()
  5. other functions

Merge each of these sections. For example, combine the variable declarations from the source sketches into the variable declaration section of the combined sketch. (The next subsection will illustrate this.)

The Merge

The example at the top of the page has three stages.

For this example, of how to combine sketches into a single multi-stage sketch, we’ll combine just two sketches: