Pages: [1]   Go Down
Author Topic: Loop for repeating a finite amount of time, doing something else, then back  (Read 1101 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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!

Offline Offline
Edison Member
Karma: 47
Posts: 1562
Reviving dead brain cells with Arduinos.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
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() ...

Pages: [1]   Go Up
Jump to: