Menu
CoddyTech

Countdown to Zero

Part of the Displays and Sensors section of Coddy's Arduino journey. Lesson 4 of 24.

As in the servo sweep, a for loop can count down: start high, keep going while the number is 0 or more, and take one away each time with n--:

for (int n = 5; n >= 0; n--) {
  showDigit(n);
  delay(1000);
}

This shows 5, 4, 3, 2, 1 and 0. With n > 0 it would stop at 1 and never show 0.

A countdown should happen once, not again and again. Code in setup() runs once, so put the countdown there and whatever happens at 0 after it. loop() can stay empty, and the 0 stays on the display.

challenge icon

Challenge

Easy

The buzzer is on pin 9. Make a launch countdown:

  • in setup(), count down from 5 to 0, one number a second
  • at 0, sound the buzzer with tone(buzzerPin, 880, 1000)
  • leave the 0 on the display

Press Run, then Check.

Try it yourself

const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};  // a, b, c, d, e, f, g

// One pattern a digit, read from the right: the last bit is segment a.
//                     gfedcba
const byte digits[10] = {
  0b0111111,  // 0
  0b0000110,  // 1
  0b1011011,  // 2
  0b1001111,  // 3
  0b1100110,  // 4
  0b1101101,  // 5
  0b1111101,  // 6
  0b0000111,  // 7
  0b1111111,  // 8
  0b1101111   // 9
};

void showDigit(int n) {
  for (int i = 0; i < 7; i++) {
    if (bitRead(digits[n], i) == 1) {
      digitalWrite(segmentPins[i], LOW);   // lit
    } else {
      digitalWrite(segmentPins[i], HIGH);  // off
    }
  }
}

const int buzzerPin = 9;

void setup() {
  for (int i = 0; i < 7; i++) {
    pinMode(segmentPins[i], OUTPUT);
  }

  // count down from 5 to 0 here, then sound the buzzer
}

void loop() {
}
quiz iconTest yourself

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

All lessons in Displays and Sensors

Practice on your own: Arduino playground