New to arduino coding. I bought the digispark breakout board and trying to write a code to change the color, on a common Anode LED dies, with a single push button.
I have a 220 Ohm resistor for each output to the RGB. However it isn't working, and I'm not sure if it is a hardware or a software problem.
My PWM is set to Pin 0, 1, and 4. The issue I'm having is that it is starting with an initial color, but it will not increase the color index, or read the button state
int redPin = 0;
int greenPin = 1;
int bluePin = 4;
int buttonPin = 5;
int buttonState = 0;
// The "counter" variable is used to keep track of how many cycles
// the button has been held down for.
int counter = 0;
// The "colorIndex" variable is used to keep track of which color is
// currently selected.
int colorIndex = 0;
// The "numberOfColors" variable is used to tell the colorIndex when to
// loop back around.
int numberOfColors = 8;
void setup() {
pinMode (redPin, OUTPUT);
pinMode (greenPin, OUTPUT);
pinMode (bluePin, OUTPUT);
pinMode (buttonPin, INPUT);
digitalWrite(buttonState, LOW);
setColor(100, 0, 0); // set initial color to red
Serial.begin(9600); // Use serial for debugging
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// If the button is being pressed
if (buttonState == HIGH) {
// Increase the
counter++;
} else
{
// Otherwise the user has released or is not pressing the button and,
// reset the counter
counter = 0;
}
// If the button has been held down for 30 cycles
if (counter > 30)
{
// If we haven't reached the maximum number of colors yet
if (colorIndex <= numberOfColors - 1)
{
// Move on to the next color
colorIndex++;
} else
{
// Go back to the first color
colorIndex = 0;
}
// A color change has been performed, reset the counter
counter = 0;
}
switch (colorIndex) {
case 0:
// Red
setColor(100, 0, 0);
break;
case 1:
// Violet
setColor(65, 0, 100);
break;
case 2:
// Blue
setColor(0, 0, 100);
break;
case 3:
// Green
setColor(0, 100, 0);
break;
case 4:
// Yellow
setColor(65, 95, 0);
break;
case 5:
// Orange
setColor(95, 65, 13);
break;
case 6:
// Brilliant White
setColor(100, 100, 100);
break;
case 7:
// Dull White
setColor(35, 35, 35);
break;
}
// Wait 100 milliseconds before checking again
delay(100);
}
// Function used to set the color of the LED
void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}