Having problems reinitializing a loop

Hello!
I have an Arduino class and we have a project to do:

Material:

  • 4 LEDs (3 green, one red)
  • 1 push button

Objective:

  • Realize the count and the order for the launch
    of a rocket

Minimum specifications:

  • We start in a waiting state, the LEDs are off.
  • When you press the button (and keep this button
    pressed), a countdown of 7 seconds takes place and is displayed
    on the leds (7,6,5,4,3,2,1,0) in binary.
  • Arrived at zero, we launch the rocket (ignition of the red led)
    for 10 seconds.
  • After 10 seconds, the red LED goes out and you can
    new rocket launch*

I've got most of the program done, the only problem is that after the countdown is finished, I can't restart it.

here's the code:

#include <EasyButton.h>

#define BUTTON_PIN 9  // Arduino pin number where the button is connected.

const int greenPin_left = 10;
const int greenPin_middle = 11;
const int greenPin_right = 12;
const int redPin = 13;
const int redTime = 10000;  // How long the red LED is on
int i = 8;                  // Used for binary countdown

// Button
EasyButton button(BUTTON_PIN);

// Callback
void CountDown() {
  while (i > 0) {
    digitalWrite(greenPin_left, LOW);
    digitalWrite(greenPin_middle, LOW);
    digitalWrite(greenPin_right, LOW);
    delay(1000);

    i--;  // Start the counter:

    if ((i % 2) > 0) {
      digitalWrite(greenPin_right, HIGH);
    } else {
      digitalWrite(greenPin_right, LOW);
    }

    if ((i % 4) > 1) {
      digitalWrite(greenPin_middle, HIGH);
    } else {
      digitalWrite(greenPin_middle, LOW);
    }

    if ((i % 8) > 3) {
      digitalWrite(greenPin_left, HIGH);
    } else {
      digitalWrite(greenPin_left, LOW);
    }
    if (i == 0) {
      digitalWrite(redPin, HIGH);
      delay(redTime);
      digitalWrite(redPin, LOW);
    }

    delay(1000);
  }
}
void setup() {
  pinMode(greenPin_left, OUTPUT);
  pinMode(greenPin_middle, OUTPUT);
  pinMode(greenPin_right, OUTPUT);
  pinMode(redPin, OUTPUT);

  // Initialize the button.
  button.begin();

  // Attach callback.
  button.onPressedFor(1000, CountDown);
}

void loop() {
  button.read();
}

here's the circuit:

Any help would be of great help!
Thank you! :slight_smile:

You have to set 'i' back to 8 to reset the count down. A good place to do that would be where you turn the redPin off, but then the CountDown() function would never end. You have to force it to end with a 'return;' statement to get control back to loop().

    if (i == 0) {
      digitalWrite(redPin, HIGH);
      delay(redTime);
      digitalWrite(redPin, LOW);
      i = 8;
      return;
    }
1 Like

Thanks for the quick response ! The code works now :slight_smile:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.