billpealer:
thanks.
i have a code mechanics question...
Why do i need the saber_is_on (or any bool statement) to be set to false in the setup,.. when i am declaring it false after the if statement?
example:
bool saber_on
void setup
saber_on = false;
void loop
{
if(digitalRead(button) == LOW) //button is pressed
{
if(saber_on) //Saber is on, so turn it off
{
//ADD CODE HERE TO TURN OFF THE LED AND PLAY OFF SOUND
saber_is_on = false;
}
else //Saber is off, so turn it on
{
//ADD CODE HERE TO TURN ON LED AND PLAY ON SOUND
saber_is_on = true;
}
}
}
so,.. it has been declared false in the set up AND after the if statement? Double false? isn't that a true? why cant i just have this and ditch the bool altogether?
void loop
{
if(digitalRead(button) == LOW) {//button is pressed
send_command(0); // off sound
delay(100);
}
else //Saber is off, so turn it on
{
send_command(1); //on sound
delay(100);
}
}
//end
i am pretty sure i started with that type of code, and when the button was toggled, it repeated like crazy.... "ma-ma-ma-ma-ma-ma" mamasita que es pasando!"
i am going to re-test,.. and i like your != simple debounce variant. simple. i'll try it.
Well, the code I posted was just supposed to give you an idea. Actually, it won't work unless you also wait for them to let off the button, otherwise it'll rapidly toggle between off and on as long as the button is pressed.
Your code won't work either and will have a similar problem.
void loop
{
if(digitalRead(button) == LOW) {//button is pressed
send_command(0); // off sound
delay(100);
}
else //Saber is off, so turn it on
{
send_command(1); //on sound
delay(100);
}
}
Here is what will happen (go ahead, try it):
Action: Press the button and hold it
Result: The off sound is played over and over and over every 100 ms until the button is released.
Action: Button is pressed and released
Result: The off sound is played for 100 ms and then the on sound is played every 100 ms.
Your solution provides no way to turn off the saber.
My solution was flawed as well; not intended to be complete. For it to work, you have to wait for the user to let off the button before you look for it again.
loop()
{
if(digitalRead(button) == LOW) //button is pressed
{
if(saber_is_on) //Saber is on, so turn it off
{
//ADD CODE HERE TO TURN OFF THE LED AND PLAY OFF SOUND
saber_is_on = false;
}
else //Saber is off, so turn it on
{
//ADD CODE HERE TO TURN ON LED AND PLAY ON SOUND
saber_is_on = true;
}
delay(20); //de-bounce it a little
while(digitalRead(button) == LOW) {} //Wait for them to let off the button
}
}
Something like that will set up the logic to allow for toggling states and prevent rapid-fire activation event triggering.