I'm very new at programming and Arduino.
I'm basically using a momentary pushbutton to turn on an RGB Led, and at each press it changes the color; Solid states first, then a fading state by button press 8.
Now when using a for loop in my switch statements for PWM fading, it is impossible to exit the for loop with a button press!
I'm following along in a book, exploring arduino, but it doesnt explain this.
HOW DO I EXIT THE FOR LOOP WITH THE PUSH BUTTON??? Ive tried so many things
Here is my code:
const int BLED = 8;
const int GLED = 9;
const int RLED = 10;
const int BUTTON = 2;
bool lastButton = LOW;
bool currentButton = LOW;
int ledMode = 0; //Cycle betweeen LED states
void setup() {
pinMode(BLED, OUTPUT);
pinMode(GLED, OUTPUT);
pinMode(RLED, OUTPUT);
pinMode(BUTTON, INPUT);
}
bool debounce(bool last)
{
bool current = digitalRead(BUTTON);
if(last != current)
{
delay(5);
current = digitalRead(BUTTON);
}
return current;
}
/*
* LED MODE SELECTION
* Pass a number for the LED state and set it accordingly
*/
void setMode(int mode)
{
//RED
switch(mode)
{
case 1:
digitalWrite(RLED, HIGH);
digitalWrite(GLED, LOW);
digitalWrite(BLED, LOW);
break;
case 2:
digitalWrite(RLED, LOW);
digitalWrite(GLED, HIGH);
digitalWrite(BLED, LOW);
break;
case 3:
digitalWrite(RLED, LOW);
digitalWrite(GLED, LOW);
digitalWrite(BLED, HIGH);
break;
case 4:
analogWrite(RLED, 255);
analogWrite(GLED, 0);
analogWrite(BLED, 255);
break;
case 5:
analogWrite(RLED, 0);
analogWrite(GLED, 255);
analogWrite(BLED, 255);
break;
case 6:
analogWrite(RLED, 255);
analogWrite(GLED, 255);
analogWrite(BLED, 0);
break;
case 7:
analogWrite(RLED, 220);
analogWrite(GLED, 220);
analogWrite(BLED, 220);
break;
case 8:
//RED FADE
for (int i = 0; i < 256; i++)
{
analogWrite(RLED, i);
digitalWrite(GLED, LOW);
digitalWrite(BLED, LOW);
delay(10);
}
for(int i = 255; i > 0; i--)
{
analogWrite(RLED, i);
digitalWrite(GLED, LOW);
digitalWrite(BLED, LOW);
delay(10);
}
default:
digitalWrite(RLED, LOW);
digitalWrite(GLED, LOW);
digitalWrite(BLED, LOW);
}
}
void loop() {
currentButton = debounce(lastButton);
if(lastButton == LOW && currentButton == HIGH)
{
ledMode++;
}
lastButton = currentButton;
/*
* If you've cycled through the different options,
* reset the counter to 0
*/
if(ledMode == 9) ledMode = 0;
setMode(ledMode);
}