CYTHEIA AIOpen the editor

7-Segment Counter

Drive a 7-segment display digit from the Arduino.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

A seven-segment display is seven small LEDs shaped like a figure 8, named a to g. Each segment has its own pin, wired here to Arduino pins 2 to 8, and the display’s common pin goes to ground, so a segment lights when its pin is high. Showing a digit means choosing which of the seven are on: for a 1 only b and c, for an 8 all seven.

The array digits holds one number for each digit from 0 to 9, with one bit per segment: bit 0 is segment a, bit 1 is b, and so on up to bit 6 for g. For example 0x06 is binary 0000110, bits 1 and 2, which are segments b and c: that draws a 1. showDigit() loops over the seven bits, shifts each into place with >> and isolates it with & 1, and writes the result to the matching pin. loop() counts from 0 to 9, showing each digit for half a second and printing it to the Serial tab.

Parts

Wiring

Arduino code

// 7-Segment Counter
// Segments a-g are wired to pins 2-8, and the common pin to ground.
// Each number below says which segments make up one digit: bit 0 is
// segment a, bit 1 is b, and so on up to bit 6 for g.
int digits[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};

void showDigit(int d) {
  for (int segment = 0; segment < 7; segment++) {
    digitalWrite(2 + segment, (digits[d] >> segment) & 1);
  }
}

void setup() {
  for (int i = 2; i <= 8; i++) {
    pinMode(i, OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  for (int digit = 0; digit <= 9; digit++) {
    showDigit(digit);
    Serial.print("Count: ");
    Serial.println(digit);
    delay(500);
  }
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Displays