Menu
CoddyTech

Remember the Mode

Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 7 of 18.

A button press lasts a fraction of a second, but what it starts can last much longer. To carry on after the button is let go, the sketch has to remember what it is doing. A variable for that is called a state or a mode:

int mode = 0;   // 0 = off, 1 = blinking

Split loop() in two. First, the inputs only change the mode. Then, the rest of the loop does what the mode says:

// 1. inputs change the mode
if (digitalRead(blinkButton) == LOW) {
  mode = 1;
}

// 2. the mode decides what happens
if (mode == 1) {
  // blink with millis()
} else {
  digitalWrite(ledPin, LOW);
}

Each number stands for one thing the sketch can be doing. Write what each number means in a comment. A sketch can have as many modes as it needs: 0, 1, 2, 3 and more.

challenge icon

Challenge

Easy

The green button is on pin 2 and the red one on pin 3.

  • green sets mode to 1, red sets it to 0
  • when mode is 1, the LED on pin 13 blinks with millis(), 500 ms on and 500 ms off
  • when mode is 0, the LED is off

Press Run, press green, let go, then press red. Then Check.

Try it yourself

const int ledPin = 13;
const int blinkButton = 2;   // green
const int offButton = 3;     // red

int mode = 0;   // 0 = off, 1 = blinking

unsigned long previousMillis = 0;
int ledState = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(blinkButton, INPUT_PULLUP);
  pinMode(offButton, INPUT_PULLUP);
}

void loop() {
  // 1. the buttons only change mode

  // 2. then do what the mode says
}
quiz iconTest yourself

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

All lessons in Timing Without Delay

Practice on your own: Arduino playground