Charlieplexing on the Raspberry Pi

If you suddenly find the need to control many LEDs and do not have the requisite electronics to do so, you can turn to your single board computer, the Raspberry Pi (RBPi) and use it to charlieplex the LEDs.

Charlieplexing is named after Charlie Allen, the inventor of the technique. Charlieplexing takes advantage of a feature of the GPIO pins of the RBPi, wherein they can change from outputs to inputs even when the RBPi is running a program. Simply setting a GPIO pin to be low does not allow enough current to pass through an LED or influence the other pins set as outputs and connected to the LED.

Using Charlieplexing, you can control up to six LEDs with three GPIO pins. For this, you will need three current limiting 470Ω resistors on each GPIO pin. The program defines a 3×6 array, which sets the state and direction of the three GPIO pins. The state defines whether the pin is set as digitally high or low, and the direction defines whether the pin is an output or an input.

Since LEDs are also diodes, they will light up only if their anodes are at a higher potential than their cathodes are, and not otherwise. Therefore, to light up a single LED, the program has to set the pin connected to its anode as output and drive it high. Next, the program must set the pin connected to the anode of the LED as input, while it sets the third pin as output and drive it low. Various combinations of the state and direction of the pins will drive all the LEDs on and off sequentially.

The array in the program holds the settings for each GPIO pin. A value of 0 means the pin is an output in a low state, 1 means the pin is an output in a high state, and -1 means the pin is set as an input.

In charlieplexing, it is easy to calculate how many LEDs each GPIO pin can control. The formula for this is, LEDs = n2-n, where n is the number of pins used. According to the charlieplexing formula, three GPIO pins can charlieplex 6 LEDs; four pins can control 12 LEDs, while 10 pins would allow control over a massive 90 LEDs.

Charlieplexing is good for not only lighting one LED at a time, but it is capable of lighting more at the same time also. For this, the program must run a refresh loop to keep the desired state of the LEDs in the array. While refreshing the display, the program must turn on other LEDs that need to be on, before moving on to the next. However, persistence of vision plays a large part here, and the program must be sufficiently fast to make it appear that more than one LED is on at a time.

However, there is a downside to lighting more LEDs at a time. Since more number of LEDs are now on to make it appear that more than one LED is on simultaneously, each LED is actually lit for a lower amount of time, which makes each LED glow less than at its full brightness.