Loop function, nested for loop, switch case

This is code to make a led blink 5 times then stay on till the button is pushed. --button1 pushed led blinks 5 times, led stays on, button2 pushed led goes off-- There are three different examples doing the exact same thing using loop function, nested for loop and switch case. It would be great if somebody else would post code doing the exact same thing with the same board set up to show the different and possibly better ways to do it. Possibly using simplefsm.h or other libraries. It would be better to only add one more library pure code post, or if you like to add two libraries post one code using only one library, a second code using the only the other library and a third code using both libraries. etc This may really help!

loop function

int ledPin = 8;//attach led to pin 8
int button1 = 5;//attach button1 to pin 5
int button2 = 6;//attach button2 to pin 6

void setup() 
{
  pinMode(ledPin, OUTPUT);//led pin is now an output
  pinMode(button1, INPUT_PULLUP);//button1 pullup resistor
  pinMode(button2, INPUT_PULLUP);//button2 pullup resistor
}

void loop() 
{
  if (digitalRead(button1) == LOW)//reads the state of the button
  {
    digitalWrite(ledPin, HIGH);//led on
    delay(250);
    digitalWrite(ledPin, LOW);//led off
    delay(250);
    digitalWrite(ledPin, HIGH);
    delay(250);
    digitalWrite(ledPin, LOW);
    delay(250);
    digitalWrite(ledPin, HIGH);
    delay(250);
    digitalWrite(ledPin, LOW);
    delay(250);
    digitalWrite(ledPin, HIGH);
    delay(250);
    digitalWrite(ledPin, LOW);
    delay(250);
    digitalWrite(ledPin, HIGH);
    delay(250);
    digitalWrite(ledPin, LOW);
    delay(250);
    digitalWrite(ledPin, HIGH);//turns led on after the lase blink
  }
  if (digitalRead(button2) == LOW)//reads the state of the button
  {
    digitalWrite(ledPin, LOW);// led off
  }
}

nested for loop

int ledPin = 8;//attach led to pin 8
int button1 = 5;//attach button1 to pin 5
int button2 = 6;//attach button2 to pin 6

void setup() 
{
  pinMode(ledPin, OUTPUT);//led pin is now and output
  pinMode(button1, INPUT_PULLUP);//button1 pullup resistor
  pinMode(button2, INPUT_PULLUP);//button2 pullup resistor
}

void loop() 
{
  if (digitalRead(button1) == LOW)//reads the state of the button
  {
    for (int x=0; x<5; x++)//"nested for loop" makes the led blink 5 times
    {
      digitalWrite(ledPin, HIGH);//led on
      delay(250);
      digitalWrite(ledPin, LOW);//led off
      delay(250);
    }
    digitalWrite(ledPin, HIGH);//turns led on after nested for loop
  }
  if (digitalRead(button2) == LOW)//reads the state of the button
  {
    digitalWrite(ledPin, LOW);//led off
  } 
}

switch case

int ledPin = 8;// attach led to pin 8
int button1 = 5;// attach button1 to pin 5
int button2 = 6;// attach button2 to pin 6

enum {off, blink, on} currentState;// the three states of the led

void setup() 
{
 pinMode(ledPin, OUTPUT);//led pin 8 is now an output
 pinMode(button1, INPUT_PULLUP);//button1 pullup resistor
 pinMode(button2, INPUT_PULLUP);//button2 pullup resistor
}

void loop() 
{
  switch(currentState)// currentState as the switch varible
  {
    case off://first state of the switch case
    if (digitalRead(button1) == LOW)//reads the state of button1
    {
      for (int x=0; x<5; x++)//"nested for loop" makes led blink 5 times
      {
        digitalWrite(ledPin, HIGH);//led on
        delay(250);
        digitalWrite(ledPin, LOW);//led off
        delay(250);
      }
      {
        digitalWrite(ledPin, HIGH);//turns led on after nested loop is finished
      }
      currentState = blink;//the state the switch case is in right now
    }
    break;
  
    case blink://second state of the switch case
    {
      digitalWrite(ledPin, HIGH);//the led is on in this state
      currentState = on;//the state the switch case is in right now
    }
    break;

    case on://third state of the switch case
     if (digitalRead(button2) == LOW)//reads the state of the button
     {
      digitalWrite(ledPin, LOW);//led off
      currentState = off;//the state the switch case is in right now
     }
     break;
  }
}

You did not follow your own instructions.

blink five times then stay on. ?

That would be six. That's like saying "I only took one cookie, then one cookie."

blink = on and off How many led off lines are there?

Personally I would always use the nested loop approach. Mainly because its less lines of code - and therefore less demading on programme storage space. As we do more and more with Arduino we end up confronting the compiler telling is that the sketch will not fit on the programme space available on the board. Then we start learning how to cut resource use in the way we write our code.
But your embedded loop example has three lines of what appears to be uneccsary code.
The embedded loop ends with the ledPin in LOW state. Not sure why you carry on after the loop and turn it back to HIGH, then add an if test to turn it to LOW again. The reality is that after flashing 5 (or 6) times and ending up LOW . Its not clear why you need a second button to turn it to LOW.
Also, in my code I avoid delay() as much as possible because it is a blocking statement - the main loop stops. So if you want it to do something else while the LED is flashing for two and a quater seconds it can't.
Better to use a millis() counter ( if((millis() - LEDonoff) >= 250) to allow the main loop to contine and change the status of the LED pin when it gets to that millis if test.

In relation to libaries - not sure what advantage you would get using a machine state library to carry out a simple function like flashing an LED? But we need to be aware that every time we add another library we consume more programme space on the board. But I got lost tring to understand the last sentence of you post (only add one more library pure code post, or if you like to add two libraries post one code using only one library etc) so I might be missing something there?
Cheers

Every LED in every part of this universe starts OFF. "On" is the end of cycle 1. You have six cycles.

Hello johnathonj

Consider:

//https://forum.arduino.cc/t/loop-function-nested-for-loop-switch-case/1229818
//https://europe1.discourse-cdn.com/arduino/original/4X/7/e/0/7e0ee1e51f1df32e30893550c85f0dd33244fb0e.jpeg
#define ProjectName "Loop function, nested for loop, switch case"
#define NotesOnRelease "Arduino MEGA tested"
// make names
enum TimerEvent {NotExpired, Expired};
enum TimerControl {Halt, Run};
enum ButtonNames {One, Two};
enum ButtonStates {Released, Pressed};
enum OnOff {Off, On};
// make variables

constexpr uint8_t ButtonPins[] {5,6};
constexpr uint8_t LedPin {8};

constexpr uint8_t NumberOfBlinks {5};
constexpr uint32_t RateOfBlinks {250};
uint32_t currentMillis = millis();
// make structures
struct TIMER
{
  uint32_t interval;
  uint8_t control;
  uint32_t now;
  uint8_t expired(uint32_t currentMillis)
  {
    uint8_t timerEvent = currentMillis - now >= interval and control;
    if (timerEvent == Expired) now = currentMillis;
    return timerEvent;
  }
};
struct BUTTONBLINK
{
  uint8_t name;
  uint8_t led;
  uint8_t button;
  uint8_t stateOld;
  uint8_t numberOfBlinks;
  TIMER myBlink;
  TIMER debounce;
  void make(uint8_t name_, uint8_t led_, uint8_t button_, uint32_t rateOfBlinks_, uint8_t numberOfBlinks_)
  {
    name = name_;
    led = led_;
    button = button_;
    numberOfBlinks = numberOfBlinks_;
    pinMode(led, OUTPUT);
    digitalWrite (led, On);
    delay(1000);
    digitalWrite (led, Off);
    delay(1000);
    pinMode(button, INPUT_PULLUP);
    stateOld = digitalRead(button) ? LOW : HIGH;
    debounce.control = Run;
    debounce.interval = 200;
    myBlink.control = Halt;
    myBlink.interval = rateOfBlinks_;
  }
  void run()
  {
    if (debounce.expired(currentMillis) == Expired)
    {
      uint8_t stateNew = digitalRead(button) ? LOW : HIGH;
      if (stateOld != stateNew)
      {
        stateOld = stateNew;
        if (stateNew == Pressed)
        {
          myBlink.now = currentMillis;
          name == One ? myBlink.control = numberOfBlinks * 2 : myBlink.control = (numberOfBlinks * 2) + 1;
          digitalWrite(led, Off);
        }
      }
    }
    if (myBlink.expired(currentMillis) == Expired)
    {
      myBlink.control--;
      digitalWrite(led, digitalRead(led) ? LOW : HIGH);
    }
  }
} buttonBlinks[sizeof(ButtonPins)];
// make support
void heartBeat(const uint8_t LedPin, uint32_t currentMillis)
{
  static bool setUp = false;
  if (setUp == false) pinMode (LedPin, OUTPUT), setUp = true;
  digitalWrite(LedPin, (currentMillis / 500) % 2);
}
// make application
void setup()
{
  Serial.begin(115200);
  Serial.print("Source: "), Serial.println(__FILE__);
  Serial.print(ProjectName), Serial.print(" - "), Serial.println(NotesOnRelease);
  uint8_t element = 0;
  for (auto &buttonBlink : buttonBlinks)
  {
    buttonBlink.make(element, LedPin, ButtonPins[element], RateOfBlinks, NumberOfBlinks);
    element++;
  }
  Serial.println(" =-> and off we go\n");
}
void loop()
{
  currentMillis = millis();
  heartBeat(LED_BUILTIN, currentMillis);
  for (auto &buttonBlink : buttonBlinks) buttonBlink.run();
}

Have a nice day and enjoy coding in C++.

Thank you for your suggestions. I made this post hoping it may help others. I added the led staying on just to have another element. It could be a different led comes on or a dc motor running to drive a conveyor until a break beam sensor is triggered but i wanted to keep it simple. Please make your suggested changes to the code and post it so that it may help myself or future readers looking for help. Please keep it simple and dont vary from the oringinal code so that we can see it does the exact same thing. Using libraries is a suggestion. Libraries have example code but none say this does the exact same thing as that code but using this library. It may be a big help to us trying to learn how.

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