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.
-
2if the code works as intended, then use itjsotola– jsotola03/18/2025 15:28:51Commented 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.JRobert– JRobert03/19/2025 16:30:21Commented Mar 19 at 16:30
1 Answer 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.
-
1Yeah. It is comparable with the common
while (!Serial);
in many sketches.the busybee– the busybee03/19/2025 06:56:00Commented Mar 19 at 6:56