So ive been playing around with making a toggle switch control 3 modes of an LED. I want it to have an on state, a fading in and out state, and an off state. Ive jumbled some code and kinda rigged a sketch together, but I keep having the same problem of the sketch getting stuck in the loop for the fade. Is there a way to have a loop within a case statement, or what would be the best way to tackle this. Heres is the code Im currently using. (I though that if I had the loop take place outside the case statement it would continue to detect the button states.
Any help would be awesome as I am new to this whole Arduino thing.
Thanks!
const int ledPinOne = 0; // LED1 ANODE
const int modePin = 4; // Active HIGH, held low by 4.7K
int mode = 0; // Selector State (Initial state = ALL OFF)
int val = 0; // Pin 0 HIGH/LOW Status
int butState = 0; // Last Button State
int modeState = 0; // Last Mode State
int fadeCheck = 0; //check for fade mode
//===============================================================
// SETUP
//===============================================================
void setup () {
pinMode(ledPinOne, OUTPUT);
pinMode(modePin, INPUT);
}
//===============================================================
// Main Loop
//===============================================================
void loop() {
val = digitalRead(modePin);
// If we see a change in button state, increment mode value
if (val != butState && val == HIGH){
mode++;
}
butState = val; // Keep track of most recent button state
// No need to keep setting pins *every* loop
if (modeState != mode){
// If no keys have been pressed yet don't execute
// the switch code below
// if (mode != 0) {
switch ( mode ) {
//case 1 is actually handled below as default
case 2:
digitalWrite(ledPinOne, HIGH);
fadeCheck = 0;
break;
case 3:
fadeCheck = 1;
fade();
break;
default:
mode = 1;
fadeCheck = 0;
digitalWrite(ledPinOne, LOW);
break;
} // end switch
// end of "if mode = 0" check
} // end of ModeState check
modeState = mode; // Keep track of mode recent mode value
delay(10); // slow the loop just a bit for debounce
}
void fade()
{
while(fadeCheck ==1)
{
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPinOne, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPinOne, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
}