Try Embedded

7-segment counter

Count from 0 to 9 on a 7-segment display, using a lookup table of which segments make each digit.

Output · Beginner

In a real product: Kitchen timer (Consumer electronics): A lookup table drives the digits.

A 7-segment display is seven LEDs arranged as the segments a to g. Lighting the right ones draws a digit. This project counts from 0 to 9, one digit a second.

What you'll learn

  • How a 7-segment display is wired: one pin per segment plus a common pin
  • Storing a font as bit patterns in a lookup table
  • Reading single bits with bitRead()

How it works

Segments a to g go to pins 2 to 8. The display is common cathode, so all the segments' cathodes are tied together on COM, which goes to GND. A segment lights when its pin is HIGH.

DIGITS[] holds one byte per digit: bit 0 is segment a, bit 1 is b, and so on up to bit 6 for g. For example, 1 is 0b0000110: only segments b and c. show() walks the seven bits and writes each to its pin.

    --a--
   f     b
    --g--
   e     c
    --d--

On a real board, give each segment its own 220 Ω resistor.

Try this

  • Count down from 9 instead, or count in hexadecimal by adding the patterns for A to F.
  • Light the decimal point (DP) on odd numbers.
  • Use a pushbutton to step the count by hand.

sketch.ino

// Count 0 to 9 on a common-cathode 7-segment display. Segments a-g are on pins 2-8.
const byte SEGMENT_PINS[7] = {2, 3, 4, 5, 6, 7, 8};  // a, b, c, d, e, f, g

// Which segments make each digit: bit 0 is segment a, bit 6 is segment g.
const byte DIGITS[10] = {
  0b0111111, 0b0000110, 0b1011011, 0b1001111, 0b1100110,
  0b1101101, 0b1111101, 0b0000111, 0b1111111, 0b1101111,
};

void show(int digit) {
  for (int s = 0; s < 7; s++) {
    digitalWrite(SEGMENT_PINS[s], bitRead(DIGITS[digit], s));
  }
}

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

void loop() {
  for (int digit = 0; digit <= 9; digit++) {
    show(digit);
    delay(1000);
  }
}

Lessons behind it