Quick question -
Which language allows me to stop a loop from continuing?
I modified the beginner tutorial code for blinking the onboard LED to look like this (a heartbeat):
There are also while-loops and do-while loops. Most loops are conditional... They loop until some condition... The Arduino main loop is an exception.
[u]break[/u] (usually along with an if-statement) can break you out of a loop at any time, but usually that's used for "unusual" conditions.
You'll have to consider what happens when your for-loop ends... You probably don't want to start your main loop over immediately. Do you want it to freeze-up 'till you reset? Do you want to wait for a button-push before it starts over? Just a longer delay? etc.?
Could also do something like this to make it restart with a button press. Button would be wired between digital pin 2 and ground.
int count = 0;
byte buttonIn = 2; //byte because an Arduino has less than 255 pins
void setup() {
pinMode(buttonIn, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop(){
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(50);
digitalWrite(LED_BUILTIN, HIGH);
delay(400);
digitalWrite(LED_BUILTIN, LOW);
delay(450);
++count;
while (count > 10){
if (digitalRead(buttonIn) == LOW){ //looking for low because pin is high when button not pressed
count = 0;
}
}
}
Do you want it to freeze-up 'till you reset? Do you want to wait for a button-push before it starts over? Just a longer delay? etc.?
I figure a reset initialization would be fine in my case. I also figure that this project is about getting good about working with a coding language, and my goal is to understand how to tell Arduino what to do about processes and variables.
When I consider a conditional, then the number of times the loop goes is the variable, and the condition has to be false when that variable exceeds 1. That's when the loop ends. Then I do not know how to tell Arduino that the loop needs to be counted and that number to be considered the variable. Is there a return integer for the number of times a loop cycles?
Setting up the code in the void setup() works for a single run. It's cool, but I think I want to adjust the number of times before the loops stops.
I didn't see what count was until I tried what SteevyT suggested and added a button. I get that count is exactly what (it sounds like) I was looking for! And the experiment worked. Thank you all.