Multiple LED Patterns

INPUT: 1 Momentary Button
OUTPUT: 3 LEDs

DESCRIPTION: Pressing button runs through sequential order of LED patterns, I stopped it at 3 presses. Press button – turn on 2 and off 1 LED. Press a second time – turn all LEDs on. Press a third time – blink all LEDs

[code lang=”arduino” light=”true”] /*
* Counting presses
* source code from ladyada.net
*/

int switchPin = 2; // switch is connected to pin 2
int ledPin = 5;
int ledPin2 = 6;
int ledPin3 = A2;

int val; // variable for reading the pin status
int val2;
int buttonState; // variable to hold the button state
int lightMode = 0; // how many times the button has been pressed

void setup() {
pinMode(switchPin, INPUT_PULLUP); // Set the switch pin as input
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);

Serial.begin(9600); // Set up serial communication at 9600bps
buttonState = digitalRead(switchPin); // read the initial state
}

void loop(){
val = digitalRead(switchPin); // read input value and store it in val
delay (10);
val2 = digitalRead(switchPin);
if (val == val2) {
if (val != buttonState) { // the button state has changed!
if (val == LOW) { // check if the button is pressed
if (lightMode == 0) {
lightMode = 1;
}
else{
if (lightMode == 1) {
lightMode = 2;
}
else{
if (lightMode == 2) {
lightMode = 0;
}

}
}
}
}
buttonState = val; // save the new state in our variable

}
if (lightMode == 0) {
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
}

if (lightMode == 1) {
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
}

if (lightMode == 2) {
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
delay(1000);
}
}
[/code]

Leave a Reply