Help in Arduino code! [SOLVED]

yes. The way I got the requirements was

  • LED On for 5 loops cycles
  • LED Off for 5 loops cycles

rinse & repeat.

➜ a state machine might be a nice readable way to implement this

Here is a small introduction to the topic: Yet another Finite State Machine introduction

const int ledPin = 3;
enum {LED_ON, LED_OFF} state = LED_OFF;
int loopCounter = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  Serial.print("Loop #"); Serial.println(loopCounter+1);

  switch (state) {
    case LED_ON:
      if (++loopCounter >= 5) {
        Serial.println(F("Turning Led Off"));
        digitalWrite(ledPin, LOW);
        state = LED_OFF;
        loopCounter = 0;
      }
      break;

    case LED_OFF:
      if (++loopCounter >= 5) {
        Serial.println(F("Turning Led On"));
        digitalWrite(ledPin, HIGH);
        state = LED_ON;
        loopCounter = 0;
      }
      break;
  }

  // so that we can see what's going on
  delay(100);
}

1 Like