Simplifying the code will help you quite a bit I'm sure, for example the code you wrote for the button press is below (I've re-formatted it to use a 'regular' indent pattern.
Code: Select all
val2 = digitalRead(switchPin); // read the input again to check for bounces
if (val == val2) { // make sure we got 2 consistant readings!
if (val != buttonState) { // the button state has changed!
if (val == LOW) { // check if the button is pressed
if (lightMode == 0) { // if its off
lightMode = 1; // make it all on!
} else {
if (lightMode == 1) { // if its all on
lightMode = 2; // make it blink!
} else {
if (lightMode == 2) { // if its blinking
lightMode = 3; // make it wave!
} else {
if (lightMode == 3) { // if its waving,
lightMode = 4; // make it dubble wave!
} else {
if (lightMode == 4) { // if its dubble waving
lightMode = 5; // make it reverse wave!
} else {
if (lightMode ==5) {
lightMode =0;
}
}
}
}
}
}
buttonState = val; // save the new state in our variable
}
Something to be aware of is that the last brace here (the } character) is still two braces short of closing off the top level "if" statement. What is worse, I don't believe this code is doing what you think it is doing.
This code is what switch statements were designed for, the form of a switch statement is as follows:
Code: Select all
switch (<expression>) {
case <value-1>:
<statements>;
break;
case <value-2>:
<statements>;
break;
case <value-n>:
<statements>;
break;
default:
<statements>;
}
In English, the compiler evaluates the expression that is inside the parenthesis and gets back a number. Then it looks for a label of the form "case
n:" where
n is the same number, so if the expression evaluated to the number 1 it would look for "case 1:" and then it does a 'goto' to that label and starts running the statements it finds. Until it sees the statement 'break' at which point it jumps all the way down to the next statement after the closing brace. Finally, the "special" label is
default: this tells the compiler that if you can't find the value in the various case statements, do the one labelled default.
So for your bit of code you probably wanted to write:
Code: Select all
switch (lightMode) { // 'lightMode' is the expression here
case 0: lightMode = 1; // if it was 0 make it 1
break;
case 1: lightMode = 2; // if it was 1 make it 2
break;
case 2: lightMode = 3; // if it was 2 make it 3
break;
case 3: lightMode = 4; // if it was 3 make it 4
break;
case 4: lightMode = 0; // if it was 4 make it go back to 0
break;
default: lightMode = 0; // if it was anything else, make it 0
break;
}
If you used a switch statement (and thus simpler braces and indentation) you would see that your program (as written) has unbalanced braces and, as written, won't do anything unless you hold the button down.
--Chuck