# Code Bits

A project log for Common Anode LED Control

How to hook up a 7-segment common anode display to Arduino

Mark 05/29/2016 at 20:220 Comments

The final piece of the puzzle is a bit of Arduino code necessary to display numbers on the digit. Thanks to the 74HC595 shift register software control of the LED segments is really easy. First we define the segments like this:

```#define SEGMENT_A 1
#define SEGMENT_B 2
#define SEGMENT_C 4
#define SEGMENT_D 8
#define SEGMENT_E 16
#define SEGMENT_F 32
#define SEGMENT_G 64```

Next up we declare a lookup table:

```/* using a pre-defined lookup table saves time and memory! */
const byte digits_lot[] = { SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_D | SEGMENT_E | SEGMENT_F,
SEGMENT_B | SEGMENT_C,
SEGMENT_A | SEGMENT_B | SEGMENT_D | SEGMENT_E | SEGMENT_G,
SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_D | SEGMENT_G,
SEGMENT_B | SEGMENT_C | SEGMENT_F | SEGMENT_G,
SEGMENT_A | SEGMENT_C | SEGMENT_D | SEGMENT_F | SEGMENT_G,
SEGMENT_A | SEGMENT_C | SEGMENT_D | SEGMENT_E | SEGMENT_F | SEGMENT_G,
SEGMENT_A | SEGMENT_B | SEGMENT_C,
SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_D | SEGMENT_E | SEGMENT_F | SEGMENT_G,
SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_F | SEGMENT_G,
};```
Now this is all we need to display a number. Note this is a Quick & Dirty method without array boundary checks etc
```void print_number( byte number )
{
shiftOut( digits_lot[ number ] );
}

void shiftOut(byte dataOut) {
int i=0;
int pinState;

digitalWrite(latchPin, 0);
digitalWrite(dataPin, 0);
digitalWrite(clockPin, 0);

for (i=7; i>=0; i--)
{
digitalWrite(clockPin, 0);
if ( dataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}
digitalWrite(dataPin, pinState);
digitalWrite(clockPin, 1);
digitalWrite(dataPin, 0);
}
digitalWrite(clockPin, 0);
digitalWrite(latchPin, 1);
}```

Full source code for an Arduino demo sketch can be downloaded in the Files section