Go Down

Topic: Loop for repeating a finite amount of time, doing something else, then back (Read 2010 times) previous topic - next topic


Hi I've come up to a little beginning programming logic question. How can I make my code so that a programmed LED blinks at a certain speed for a certain amount of times (let's say, 2) and then I want to switch to a different speed after, and then back to the beginning successfully creating an ongoing loop? But instead of copy and pasting the blink code to create another blink of the same speed, I'm wondering if I can use a for loop for one entry in a way that repeats that speed a certain amount of times, then going to the other speed once, and then repeating the whole thing.

Hopefully I explained the question well enough. Thanks!


One way is to use a state variable.  If it's FALSE, blink at a certain speed.  If it's TRUE, blink at a different speed.
Code: [Select]
int pause = 250;
int stateTrack = 0;
int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);

void loop() {
  for (int cnt = 0; cnt < 4; cnt++) {  // each blink is counted as 2: on and off
    if (!stateTrack) {
      pause = 250;
    } else {
      pause = 500;
    digitalWrite(ledPin, digitalRead(ledPin) == HIGH ? LOW : HIGH);
  if (stateTrack > 1) stateTrack = 0;

Of course you'd probably want to write this without using delay() ...

Go Up