Can you make a part of loop() happen before a part of setup()?

I'm working on a mini elevator which uses a distance sensor to stop on different floors and I want it to return to the first floor every time I start the program, but in order to do that it would have to happen in setup().

The thing is that it can't hapoen in setup since the distance reading is included in loop(). Is there anything I could do here?

Put the distance reading in a function and call it from wherever it is needed

1 Like

The setup is supposed to just set things up to an initial state

If the loop handles setting the initial state too then you have some sort of design flaw

As suggested above, both the loop and the setup could use some shared functions to get things moving though

You set a boolean variable true and set it false this way

void setup() {
  pinMode(Motor1, OUTPUT);
  pinMode(CallButton, INPUT);

  firstLoop = true;
}


void loop() {
  distanceReading();

  if (firstLoop ) {
    firstLoop = false;
    driveElevatorHome();
  }  

as the code inside the if-condition sets the boolean variable to false

this kind of "locks-out" from executing it again.

from second loop to infinity the variable firstLoop stays false
and the if-condition never becomes true again except for
a reset or power-OFF-ON

best regards Stefan

well, why wouldn't you do simply

void setup() {
  pinMode(Motor1, OUTPUT);
  pinMode(CallButton, INPUT);
  driveElevatorHome();
}

void loop() {
  ...
}

and not pay the price of the test against your boolean at every loop ? (unless you want to be able to soft reset)

the TO wrote that distanceReading is done inside loop
So your version would require doing the distance-reading in setup too.
Which of course is possible.

@ceesarg : Post your code. I guess your code can be improved through defining functions.
defining functions enables what J-M-L suggested
best regards Stefan

I stand by my original suggestion to put the homing instructions in a function and to call them when required be it from setup(), loop() or elsewhere

I figured it out, thanks for help everyone!

Trust the helicopter! That is the method I use too

Please share the solution for future searchers.