Here is the code which I have been trying to get to work. As soon as I upload the program the LED turns blue and pressing the button doesn't do anything . Help me please!
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int buttonPin = 2;
int buttonPress = 3;
int buttonState = 0;
One side of your switch has been left floating (unconnected).
Connect the Arduino i/p and the switch pin to 10K resistor to ground. Then connect other end of the switch to +5V.
The 10K will make the i/p look like a low (0) until you push the switch which is then +5V (HIGH).
Because after the code turns on the blue LED it sets buttonPress to 0. After that nothing else gets executed in any of the if statements because there is not a state where buttonPress has to correspond to 0
It can be frustrating when you start learning a new concept.
Go through this code:
Something you have not considered is de-bouncing a switch i/p, that is the purpose of the Bounce library.
If you are not sure of any line ask us for help.
// Down load the library and place it in ....\Documents\Arduino\libraries\Bounce
// http://playground.arduino.cc//Code/Bounce
#include <Bounce.h>
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int buttonPin = 2;
int buttonPress = 0;
// EDIT int buttonState = 0; // Start in State 0
// Instantiate a Bounce object with a 20 millisecond de-bounce time
Bounce bouncer = Bounce( buttonPin,20);
void setup() {
pinMode(redPin, OUTPUT);
digitalWrite(redPin,LOW);
pinMode(greenPin, OUTPUT);
digitalWrite(greenPin,LOW);
pinMode(bluePin, OUTPUT);
digitalWrite(bluePin,LOW);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin,HIGH); // turn on Pull Up
} // END of setup()
void loop()
{
// Update the debouncer
// has the button changed state and is it now HIGH?
if (bouncer.update ( )&& bouncer.read()== HIGH)
{
if(buttonPress == 0)
{
digitalWrite(redPin, HIGH);
digitalWrite(bluePin, LOW);
buttonPress++;
}
else if(buttonPress == 1)
{
digitalWrite(greenPin, HIGH);
digitalWrite(redPin, LOW);
buttonPress++;
}
else if(buttonPress == 2)
{
digitalWrite(bluePin, HIGH);
digitalWrite(greenPin, LOW);
buttonPress = 0;
}
}
} // END of loop()
bouncer.update ( ) <<< will return True if there has been a change in the switch position. Low to High OR High Low
EDIT: False if there has been no switch press.
&&
bouncer.read()== HIGH <<< checks to see if the switch is pushed right now (HIGH in your case)
EDIT:
So if we get True in both cases, we execute some code.