1

What is the meaning of BitSet = bitRead(numeral[number], segment);?

const byte numeral[10] = {
  //ABCDEFG /dp
  B11111100,  // 0
  B01100000,  // 1
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7
  B11111110,  // 8
  B11100110,  // 9
};

// pins for decimal point and each segment
//                          dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

void setup()
{
  for(int i=0; i < 8; i++)
  {
    pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
  }
}


void loop()
{
  for(int i=0; i <= 10; i++)
  {
    showDigit(i);
    delay(1000);
  }
  // the last value if i is 10 and this will turn the display off
  delay(2000);  // pause two seconds with the display off
}

// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
  boolean isBitSet;

  for(int segment = 1; segment < 8; segment++)
  {
    if( number < 0 || number > 9){
      isBitSet = 0;   // turn off all segments
    }
    else{
      // isBitSet will be true if given bit is 1
      isBitSet = bitRead(numeral[number], segment);
    }
    isBitSet = ! isBitSet; // remove this line if common cathode display
    digitalWrite( segmentPins[segment], isBitSet);
  }
}
Jesse
  • 105
  • 1
  • 1
  • 6
Omkar Singh
  • 11
  • 1
  • 3

1 Answers1

3

bitRead(x, y) takes a value x, and looks at bit number y.

So, if:

  • y is the number 2;
  • x is 53 (binary number 0 0 1 1 0 1 0 1)
                                           ^

it looks at bit #2. Bits are counted from the right starting at 0 - I have indicated the bit in question above.

So, bitRead(53, 2) would return 1, since bit #2 in 53 is a 1.

In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit 8 has all seven of its LEDs lit up, so you'd expect the encoding for 8 to have lots of binary 1s in it - and sure enough, it does (B11111110)! And the digit 7 has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, B11100000.

The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...

John Burger
  • 1,875
  • 1
  • 12
  • 23