Menu
CoddyTech

Digit Patterns in Bytes

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

Seven digitalWrite() lines for every digit is a lot of code. Store each digit as a pattern: one bit a segment, 1 for lit and 0 for off.

A byte is a whole number from 0 to 255 made of eight bits. Write it in binary with 0b in front. Read the bits from the right: the last bit is segment a, the one before it b, and so on up to g.

//           gfedcba
byte one = 0b0000110;  // b and c: a 1

Ten patterns fit in an array, so digits[3] is the pattern of a 3. bitRead(), from the binary counter, reads one bit of it, counting from the right and starting at 0:

bitRead(0b0000110, 0)  // 0: segment a is off
bitRead(0b0000110, 1)  // 1: segment b is lit

A function can go through the seven bits with a for loop and set each segment pin, so drawing any digit is one call: showDigit(7);

challenge icon

Challenge

Medium

The starter has every pattern except 4 and 7, and loop() shows 1, 4 and 7.

  • fill in 4 (segments b, c, f, g) and 7 (a, b, c)
  • write showDigit(n): for each i from 0 to 6, set segmentPins[i] LOW when bit i of digits[n] is 1, HIGH when it is 0

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
  0b0000000,  // 4: fill in
  0b1101101,  // 5
  0b1111101,  // 6
  0b0000000,  // 7: fill in
  0b1111111,  // 8
  0b1101111   // 9
};

void showDigit(int n) {
  // light the segments of digits[n], turn the others off
}

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

void loop() {
  showDigit(1);
  delay(1000);
  showDigit(4);
  delay(1000);
  showDigit(7);
  delay(1000);
}
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