ArduinoLibs
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
Charlieplexing Example

Charlieplexing is a technique for multiplexing large numbers of LED's on a small number of microcontroller output pins. LED's are arranged in complementary pairs and managed by the Charlieplex class. For this example we are going to use 3 output pins to drive 6 LED's:

charlieplexeg.png

The technique can be expanded to even larger numbers of LED's. See the documentation for the Charlieplex class for a description of how to connect up larger numbers of pins in a Charlieplexed arrangement.

The first step is to initialize a Charlieplex object with the output pins it needs to drive:

#include <Charlieplex.h>
byte pins[3] = {9, 10, 11};
Charlieplex charlie(pins, sizeof(pins));

Then in setup() we use Charlieplex::setLed() and Charlieplex::setPwmLed() to set three of the six LED's to the desired output values:

void setup() {
charlie.setLed(0, true); // Turn on LED1
charlie.setLed(3, true); // Turn on LED4
charlie.setPwmLed(5, 64); // Set LED6 to one-quarter on
}

Charlieplexing can only light a single LED at a time. It is therefore necessary to constantly scan the entire LED array, alternatively turning LED's on and off. The user's peristence of vision fills in the gaps. To do this, we call Charlieplex::loop():

void loop() {
charlie.loop();
}

The downside of Charlieplexing is that when multiple LED's are lit, each LED will appear to be dimmer than if only a single LED was lit. This can be counteracted by using brighter LED's or smaller resistors. The danger with smaller resistors is that if the program crashes or locks up for some reason, a large amount of continuous current could be fed through a single LED and cause it to exceed its maximum rating and burn out.

The full source code for the example follows:

/* This example is placed into the public domain */
#include <Charlieplex.h>
byte pins[3] = {9, 10, 11};
Charlieplex charlie(pins, sizeof(pins));
void setup() {
charlie.setLed(0, true); // Turn on LED1
charlie.setLed(3, true); // Turn on LED4
charlie.setPwmLed(5, 64); // Set LED6 to one-quarter on
}
void loop() {
charlie.loop();
}

A more complex example that performs a LED chase over the 6 LED's follows:

/* This example is placed into the public domain */
#include <Charlieplex.h>
byte pins[3] = {9, 10, 11};
Charlieplex charlie(pins, sizeof(pins));
int previous = 1;
int current = 0;
int step = 1;
unsigned long lastTime;
void setup() {
lastTime = millis();
charlie.setLed(current, true);
charlie.setPwmLed(previous, 64);
}
void loop() {
if ((millis() - lastTime) >= 100) {
charlie.setLed(previous, false);
charlie.setPwmLed(current, 64);
previous = current;
current += step;
if (current < 0) {
current = 1;
step = 1;
} else if (current >= charlie.count()) {
current = charlie.count() - 2;
step = -1;
}
charlie.setLed(current, true);
lastTime += 100;
}
charlie.loop();
}