Menu
CoddyTech

Count on the Display

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

With showDigit(), a digit is one function call. A for loop can call it with every number in turn:

for (int n = 0; n <= 9; n++) {
  showDigit(n);
  delay(500);
}

The condition decides the last number. n <= 9 runs up to and including 9; n < 9 stops at 8.

Put the loop inside loop(), and when the count finishes, loop() runs again and the count starts over from 0.

challenge icon

Challenge

Easy

showDigit() is ready. Count on the display:

  • show 0, 1, 2 and so on up to 9
  • keep each number on for 500 ms
  • after 9, start again at 0

Press Run to watch it count, 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
    }
  }
}

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

void loop() {
  // show 0 to 9, half a second each
}
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