Seven segment LED display


What you want

Wouldn't it be nice if you could print to a 7-segment display just like printing to the serial terminal? Well, there are modules to do that, but just to show a single digit they are too expensive.
Controlling that display should not make the rest of the code unreadable. (However, if you need a multidigit display you have to program a multiplex control not to run out of pins.)

Implementation

To control a 7 segment display you need this: There is a special option: blanking the display is done by selecting number "10".
The decimal point will be treated as segment no 8.

The code of the procedure disp7seg is programmed for a display with common cathode. If done properly you need a resistor for each of these segments (and the decimal point as well). If you don't mind that "1" looks much brighter than "8" only one resistor for the common cathode will do.
In the loop of the procedure disp7seg the layout of the number is found in the layout array (seg7[b]), the bit which is needed will be shiftet to the right and masked. This value (0 or 1) will be sent to the pin where the segment is connected to.
In case you use a display with common anode you have to invert the boolean value before writing it to the port.

Example:

In this example, the numbers from 0 to 19 are sent to the display. For values above 9 the decimal point will be shown.

// 7-Segment LED Display:
// FND 560   840 09  KOREA
const byte segA = 4;
const byte segB = 9;
const byte segC = 7;
const byte segD = 6;
const byte segE = 5;
const byte segF = 3;
const byte segG = 2; 
const byte segDp = 8;
const byte segs[] = {segA, segB, segC, segD, segE, segF, segG, segDp};
const byte seg7[] = { B0111111,     // 0
                      B0000110,     // 1
                      B1011011, 
                      B1001111, 
                      B1100110, 
                      B1101101, 
                      B1111101, 
                      B0000111, 
                      B1111111, 
                      B1101111,      // 9
                      B0000000};     // blank
//-------------------------------------------------                      
                      
void disp7seg(byte b) {
  for (byte i = 0; i <= 6; i++) 
    digitalWrite(segs[i], (seg7[b] >> i) & 1);
}

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

int c;

void loop() {
  disp7seg(c % 10);
  digitalWrite(segDp, c > 9);
  if (c++ > 19) c = 0;
  delay(500);
}



contact: nji(at)gmx.de