I have searched the web for example sketches that will stop flashing an LED after x number of times. None seem to work. Here is an example: int ledPin = 13; // select the pin for the LED int val = 6; // variable to store the data upper limit void setup() { pinMode(ledPin,OUTPUT); // declare the LED's pin as output } void loop () { // blink the LED that number for(int i=0; i<val; i++) { digitalWrite(ledPin,HIGH); delay(150); digitalWrite(ledPin, LOW); delay(150); } }
int ledPin = 13; // select the pin for the LED
int val = 6; // variable to store the data upper limit
void setup() {
pinMode(ledPin,OUTPUT); // declare the LED's pin as output
// blink the LED that number
for(int i=0; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
}
void loop(){
;
}
or
void setup() {
pinMode(ledPin,OUTPUT); // declare the LED's pin as output
}
void loop () {
static bool end = false;
if(!end){
// blink the LED that number
for(int i=0; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
end = true;
}
}
or
void setup() {
pinMode(ledPin,OUTPUT); // declare the LED's pin as output
}
void loop () {
static int i = 0;
// blink the LED that number
for(; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
}
It's flashing the LED six times, then it's finished with the code in the loop() function, which then returns. The thing about loop() is that it's called repeatedly, since it's designed to be the body of a loop.
So you could do this:
void loop () {
// blink the LED that number
for(int i=0; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
// all done; do nothing now
while ( true )
{}
}
which just feels wrong somehow,
or you could do this
bool flashedLED = false;
void loop () {
if ( ! flashedLED )
{
// blink the LED that number
for(int i=0; i<val; i++) {
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin, LOW);
delay(150);
}
flashedLED = true;
}
}
which is probably closer to what you'll do when you evolve the code to do something more.
I have a strong preference for the static local variable as in Brig's suggestion (static bool end = false;) because scopes should be as narrow as possible to reduce conflicts and the temptations of excessive coupling. I was under the impression that compiling this in the Arduino environment would result in linker errors because of missing cxa_guard functions. I was wrong. I recommend his solution.
THANKS all! I am sculptor with zero intuitive programming skills. This problem occurs when I want sensors/motors to start when the viewer approaches and turn off after a certain count or time. I gave up several years ago but am anxious to begin anew. Thank you so much for the timely responses. Works great!