Anyone know how to put a delay in a for loop without using the traditional delay()?
if(digitalRead(beam)==HIGH){
for(int i=1; i<=10; i++){
Serial.println(i);
delay(1000);
Anyone know how to put a delay in a for loop without using the traditional delay()?
if(digitalRead(beam)==HIGH){
for(int i=1; i<=10; i++){
Serial.println(i);
delay(1000);
Yes, but why have a delay in the first place?
Search the forum for:
Blink Without Delay
State Machine
.
Yes it is a reversal of the way for loop works and YES it is confusing
for() method:
unsigned long t = 1000
for (static unsigned long _ETimer; millis() -_ETimer >= (t); _ETimer += (t)){
static unsigned int i;
Serial.println(i);
i++
}
Everyone here will tell you that it is too confusing don't use it and you should use the if() method for readability.
if() method:
unsigned long t = 1000
static unsigned long _ETimer;
if ( millis() - _ETimer >= (t)) {
_ETimer += (t);
static unsigned int i;
Serial.println(i);
i++
}
Pick your poison
google "blink without delay" arduino for many more examples including class examples
@zhomeslice: How is the time-wasting for loop an improvement over using delay()? NOTHING else can happen until that for loop is complete.
Anyone know how to put a delay in a for loop without using the traditional delay()?
Can I suggest that you are asking the wrong question ?
Don't use a for loop in the first place. The cunningly named loop() function will allow you to repeat code as many times as you like, as frequently as you like if you use millis() for timing as in the BlinkWithoutDelay example.
You can use millis() for timing inside a for loop but why would you as that effectively blocks program execution just as much as using delay().
PaulS:
@zhomeslice: How is the time-wasting for loop an improvement over using delay()? NOTHING else can happen until that for loop is complete.
Did you try it? ... nope!
The for() example rejects entry into the loop until time is up (true). then creates a false condition to prevent it from looping more than once.
Like I said it's confusing.
I would recommend using my second example. I posted.
delay in loop
void delayInLoop(long microSeconds)
{
const unsigned long start = micros();
while (true)
{
unsigned long now = micros();
if (now - start >= microSeconds)
{
return;
}
}
}
for (...)
{
// wait 1000 micro seconds
delayInLoop(1000);
// and after that
doSomething();
}
kino-:
This is the more Arduinistic way because this is how the developer of Arduino has written codes in base libraries such as Stepper.h.
This is complete nonsense. It works, but all you’ve done is implement your own blocking version of delay() but using microseconds instead of milliseconds.
Also, this is a thread that fizzled out in 2016.