Unable to get switch to change LED color, just loops through all colors regardless of switch pressed or not

StackOverflow https://stackoverflow.com/questions/23101167

  •  04-07-2023
  •  | 
  •  

Question

I am trying to learn how to do basic things on Arduino by working through this tutorial http://lilypadarduino.org/?page_id=216. I would like to write a program that would allow me to control a 3 color LED with a switch and each time the switch is pressed I want the LED to change from red to green to blue. From what I understand the loop method is supposed to run over and over again which should test to see if the switch is pressed. If it has been pressed then it should increment a counter until it gets to 2 (blue) and the counter is reset. It changes colors from red to green to blue but not when I press the switch it just loops through them as if the switch is always pressed. My code is below.

int ledPin = 13;    // LED is connected to digital pin 13
int redPin = 11;    // R petal on RGB LED module connected to digital pin 11
int greenPin = 9;   // G petal on RGB LED module connected to digital pin 9
int bluePin = 10;   // B petal on RGB LED module connected to digital pin 10
int switchValue;
int switchPin = 2;
int count = 0;          
int red = 255;          //red value, initially set at 255
int blue = 0;          //blue value, initially set at 0

void setup()     
{    
  pinMode(ledPin, OUTPUT);  // sets the ledPin to be an output
  pinMode(redPin, OUTPUT);  // sets the redPin to be an output
  pinMode(greenPin, OUTPUT);    // sets the greenPin to be an output
  pinMode(bluePin, OUTPUT); // sets the bluePin to be an output
  //redtoblue();
}    

void loop() // run over and over again
{    
  if(switchValue == LOW){  
    if (count == 0){
      color(255, 0, 0); // turn the RGB LED red
      delay(1000);  // delay for 1 second
      count += 1;    //increment the count
    }
    else if (count == 1){
      color(0,255, 0);  // turn the RGB LED green
      delay(1000);  // delay for 1 second
      count += 1;    //increment the count
    }
    else if (count == 2){
      color(0, 0, 255); // turn the RGB LED blue
      delay(1000);  // delay for 1 second
      count = 0;    // set the count back to 0
    }
  }

}
void color (unsigned char red, unsigned char green, unsigned char blue)     // the color generating function
{    
  analogWrite(redPin, 255-red);  
  analogWrite(bluePin, 255-blue);
  analogWrite(greenPin, 255-green);
}    
Was it helpful?

Solution

You are not reading the value of the switchpin, or setting the pin to Input.

So SwitchValue is always low and your condition always True. So it just loops.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top