ok - I've been trying to figure out how to start a loop when I push a button, have it run until the same button is pushed again, and then stop.
I read through the tutorials and searched the forum and all the code I've tried only works so long as the button is held down. I took this code from an answer on the forum:
First, take a look the variable named run. If it equals 0, you set it to 255, turn the LED on. Then you check to see if it's greater that 0, which it now is, so you turn it off. This is going to happen so fast your eyes can't perceive the change from on to off. On the next pass, it will still be greater than 0, so you set it to 0 and turn the LED off. Then the cycle repeats.
What you want to do is toggle the state of the LED from on to off to on to off...based on a button push. You might try something like the following (not tested):
void loop()
{
if (digitalRead(buttonPin) == HIGH)
{
run = !run;
}
digitalWrite(ledPin, run);
}
You may have to debounce the switch, and there are plenty of posts dealing with that.
Also, to get the most of those who read posts here, please read Nick Gammons posts at the top of this Forum for guidelines on posting.
You need to save if you want to run the loop or not. And if I say save, you say variable. Let's call it a bool run. All you now need to do is change the run from true to false and the other way around. And you want to do that not if pressed (because the loop will scan the button way faster then you can press and release it) but on the trasition from not being pressed to pressed.
Also, you want to debounce the button (look it up ). So the easiest way is to use the Bounce library. (Look it up as well! I'm just giving you a start, not fully writing all the code to use it.) Code would become something like:
void loop(){
static bool run;
button.update();
if(button.fell()){ //assume a switch to ground
run != run; //flip the variable
}
if(run){
//your code here
}
}