3

I have an Arduino vehicle and I upload projects to it that I want them to function once I use a strong light on a light sensor attached to A4 analog pin. So far, I have used the following code:

void setup() {
 while (analogRead(A4) < 900) {}
}
void loop() {
 // do something with the vehicle
}

I know it's a bad design, but there's a limitation that I can't use the loop() function for this (it's actually a limitation of a specific IDE usage scenario), I need to do it in the setup() function, so I would like to know if I'm doing any harm to Arduino or the light sensor by using the previous code. Should I also use delay() or millis() in this while loop? The sensing of the strong light doesn't have to be accurate.

asked Mar 18 at 13:19
2
  • 2
    if the code works as intended, then use it Commented Mar 18 at 15:28
  • I vote to reopen. The OP asks "I would like to know if I'm doing any harm to Arduino or the light sensor by using the previous code". How is this opinion-based? Running such a loop either does, or does not, harm one or both of the Arduino or the sensor and is easily demonstrated. Their second question is hardly controversial; the program is so trivial that a delay, a millis() loop, or using neither will still accomplish their stated goal, and is likewise, easily demonstrated. Commented Mar 19 at 16:30

1 Answer 1

1

No, you won't do any harm to the Arduino or the light sensor using this code. And there is no point in adding anything (delay(), millis(), whatever) to the loop body. The only thing I would add is a comment stating the purpose of this loop.

I know it's a bad design

It doesn't conform to the rules of "non-blocking" code. I wouldn't worry too much about this though: when non-blocking matters, it usually only matters within loop(), not in setup(). If you really wanted to be non-blocking everywhere, you could do something like this:

bool start_signal_received = false;
void loop() {
 if (!start_signal_received) {
 if (analogRead(A4) >= 900) // check for the start signal
 start_signal_received = true;
 else
 return; // go no further without that signal
 }
 // The code below only runs after the start signal.
 ...
}

Your blocking loop is simpler than this, so I suggest you keep it unless you have a good reason not to.

answered Mar 18 at 17:53
1
  • 1
    Yeah. It is comparable with the common while (!Serial); in many sketches. Commented Mar 19 at 6:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.