Discuss on GitHub

Using a Four-Digit LED Display

Problem

You want to display a four-digit number in an old-fashioned, seven-segment LED display.

Solution

Use an I2C LED module, such as the model shown in Figure 9-1 attached via a breadboard to a Raspberry Pi.

Figure 9-1. Seven-segment LED display with Raspberry Pi

To make this recipe, you need:

Figure 9-2 shows the arrangement of components on the breadboard.

Figure 9-2. The breadboard layout for an LED display with Raspberry Pi

For this recipe to work, you will also need to set up your Raspberry Pi for I2C, so follow “Setting up I2C” first.

The display has an accompanying Python library written by Adafruit. It isn’t installed as a proper library, so to use it, you first need to download the folder structure. If you do not have Git installed, install it now with the following command (see “Fetching Source Code with git”).

$ sudo apt-get install git

Now, you can download the folder structure from GitHub:

$ git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git

Change directory into the Adafruit code using:

$ cd Adafruit-Raspberry-Pi-Python-Code
$ cd Adafruit_LEDBackpack

In this folder, you will find a test program that will display the time. Run it using the command:

$ sudo python ex_7segment_clock.py

Discussion

If you open the example file ex_7segment_clock.py in nano, you’ll see that the key commands are:

from Adafruit_7Segment import SevenSegment

which import the library code into your program. You then need to create a instance of SevenSegment using the next line of code. The address supplied as an argument is the I2C address (see “Setting up I2C”).

Every I2C slave device has an address number. The LED board has three pairs of solder pads on the back that can be bridged with solder if you want to change the address. This is essential if you need to operate more than one of the displays from a single Raspberry Pi.

segment = SevenSegment(address=0x70)

To actually set the contents of a particular digit, use a line like this one:

segment.writeDigit(0, int(hour / 10))

The first argument (0) is the digit position. Note that these positions are 0, 1, 3, and 4. Position 2 is reserved for the two dots in the center of the display.

The second argument is the number to display.

See Also

You can find out more about the Adafruit library at http://bit.ly/HQBE6W.