(I apologize if this is the wrong forum for asking this, but I wasn't sure exactly where this goes. It's sort of a "this works, someone please explain why." It's also an outgrowth of this post: http://arduino.cc/forum/index.php/topic,77892.0.html)
Having successfully created an array of LEDs, my next step was to abstract this into a couple of classes: LedArray, which is used to define an array of LEDs and turn them off and on; and BinaryLedArray, which inherits from LedArray and lets me feed in a number and have the array display it in binary. I'm doing this not because I think it's necessarily useful to do so, but because I want to fool around a bit with classes and inheritance, and this seemed like a good way to start.
Now, when making my LedArray class, I was getting very inconsistent results from the LEDs. The circuit was good, the code checked out, I know the board can power all ten at once because I've seen it do so, but some just wouldn't light. The most recent of the many things I tried to correct this was to move the pinMode call, which sets the pins in the array to OUTPUT, from the class constructor to the method that actually lights the pin. Basically, instead of setting them all at object instantiation, it only sets the pins as it needs them to light the LEDs. And suddenly everything works perfectly.
Now, it's nice that I got it working and all, but I don't understand why that worked. Anyone able to explain to this poor, addle-brained neophyte? I've attached the .cpp file for reference.
/*
LedArray.cpp - Arduino library to control an array of LEDs
Created by Michael C. Smith, Nov. 4, 2011
Released into the public domain.
*/
#include "WProgram.h"
#include "LedArray.h"
LedArray::LedArray( int startingPin, int numberOfPins ) {
for( int i = 0; i < 20; i++ )
{
if( i < startingPin || i >= startingPin + numberOfPins )
{
_pins[ i ] = -1;
} else {
//pinMode( _pins[ i ], OUTPUT ); <---this is where it was originally
_pins[ i ] = i - startingPin;
}
}
}
int LedArray::getPinFromIndex( int index )
{
for( int i = 0; i < 20; i++ ) {
if( _pins[ i ] == index )
{
return i;
}
}
return -1;
}
void LedArray::setLight( int index, bool isHigh )
{
int pin = getPinFromIndex( index );
if( pin > -1 && pin < 14 ) {
pinMode( pin, isHigh );
digitalWrite( pin, isHigh );
} else if( pin > 13 && pin < 20 ) {
//eventually add code to handle analog pins with an else statement
}
}
void LedArray::light( int index )
{
setLight( index, true );
}
void LedArray::extinguish( int index )
{
setLight( index, false );
}