I am trying to make an led controller that selects different colors based on the button count.
I have a push button hooked to pin 2 from 5v+.
A 10K resistor from pin 2 to ground.
RGB led to
pin 11 red through 1K resistor
pin12 green through 1K resistor
pin 13 blue through 1K resistor
When the code runs all led colors light up I get no change from the button. I tried to use the switch case but something is not right. Here is my code. Any help would be greatly appreciated.
/*
The circuit:
* RGB LED attached from pin 11,12,13 to -5V
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int red = 11; // this sets the red led pin
const int green = 12; // this sets the green led pin
const int blue = 13; // this sets the blue led pin
// variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0;// previous state of the button
int ledcolor =0;
void setup() {
// initialize the LED pin as an output:
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
//compare the button state to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH){
// if the current state is HIGH then the button was pressed
buttonPushCounter++;
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
switch (ledcolor){
case 1: //if ledcolor equals 0 then the led will turn red
digitalWrite(red, HIGH);
break;
case 2: //if ledcolor equals 1 then the led will turn green
digitalWrite(green, HIGH);
break;
case 3: //if ledcolor equals 2 then the led will turn blue
digitalWrite(blue, HIGH);
break;
case 4: //if ledcolor equals 3 then the led will turn yellow
analogWrite(red, 160);
digitalWrite(green, HIGH);
break;
case 5: //if ledcolor equals 4 then the led will turn cyan
analogWrite(red, 168);
digitalWrite(blue, HIGH);
break;
case 6: //if ledcolor equals 5 then the led will turn magenta
digitalWrite(green, HIGH);
digitalWrite(blue, HIGH);
break;
case 7: //if ledcolor equals 6 then the led will turn white
analogWrite(red, 100);
digitalWrite(green, HIGH);
digitalWrite(blue, HIGH);
break;
}
}