#define NUM_LEDS 3
#define NUM_PATTERNS 6
//pins
const uint8_t Button = 4;
const uint8_t grLEDs[NUM_LEDS] = { 3, 2, 1 };
//LED patterns
uint8_t patternIndex;
const uint8_t grPatterns[NUM_PATTERNS] =
{
0b00000000, //all off
0b00000001, //LED1 on
0b00000011, //LED1 and 2 on
0b00000111, //LED1, 2, and 3 on
0b00000110, //LED2 and 3 on
0b00000100 //LED3 on
};
//for tracking enabled or disabled
bool bEnable = false;
//last button reading
uint8_t sLast;
//for timing of button reads and LED patterns
unsigned long
tButton,
tLED,
tNow;
void setup()
{
//set the LED pins to output
for( uint8_t i=0; i<NUM_LEDS; i++ )
pinMode( grLEDs[i], OUTPUT );
//button to input with a pullup
pinMode( Button, INPUT_PULLUP );
sLast = digitalRead( Button );
//initialize to the first LED pattern
patternIndex = 0;
//set up the timing variables
tNow = millis();
tLED = tNow;
tButton = tNow;
}//setup
void loop()
{
//read the millis counter
tNow = millis();
//LED pattern timing
// has 1-second elapsed since the last pattern change?
if( (tNow - tLED) >= 1000ul )
{
//yes; save the time for the next change
tLED = tNow;
//bump the pattern index by 1
patternIndex++;
//if we've done the last pattern, go back to the beginning
if( patternIndex == NUM_PATTERNS )
patternIndex = 0;
}//if
//control the LEDs
// the "digitalWrite(...)" line is a complicated way of putting all this:
//for( uint8_t i=0; i<NUM_LEDS; i++ )
// if( bEnable == false )
// {
// digitalWrite( grLEDs[i], LOW );
// }//if
// else
// {
// if( grPatterns[patternIndex] & (1 << i) )
// digitalWrite( grLEDs[i], HIGH );
// else
// digitalWrite( grLEDs[i], LOW );
// }//else
//}//for
//
// on one line
for( uint8_t i=0; i<NUM_LEDS; i++ )
digitalWrite( grLEDs[i], (bEnable == false) ? LOW : ((grPatterns[patternIndex] & (1 << i)) ? HIGH : LOW) );
//read the button once every 50mS
if( (tNow - tButton) >= 50ul )
{
tButton = tNow;
uint8_t sNow = digitalRead( Button );
if( sNow != sLast )
{
//on each button press, toggle the enable flag
sLast = sNow;
if( sNow == LOW )
{
bEnable ^= true;
//when we enable, set the pattern index to zero
//to start from a known place
if( bEnable == true )
patternIndex = 0;
}//if
}//if
}//if
}//loop