arduino delay vs teency 3.2

Status
Not open for further replies.

philip.porhammer

Well-known member
what do i change for this to work with the teency 3.2?

unsigned long time_now = 0;

time_now = millis();
while(millis() > time_now+100)
{

delay (1);

}
 
Nothing needs to be changed except that it doesn't look right even for an Arduino.
The while loop won't loop. The first time in the while, time_now will be equal to millis() which means that millis() can't be greater than time_now+100, so the loop isn't entered.
Also it's best to use a subtraction when dealing with arithmetic with unsigned long so that you avoid a potential problem when millis() rolls over from 0xFFFFFFFF to 0.

Code:
while(millis() - time_now < 100)

will loop for 100 milliseconds.

Pete
 
Teensy has a feature called elapsedMillis, which is meant to make this sort of code simpler.

https://www.pjrc.com/teensy/td_timing_elaspedMillis.html

Of course you can use the Arduino millis() function, but as el_supremo correctly pointed out, it's very common to make mistakes.

By using elapsedMillis, things are simpler.

Code:
elapsedMillis mytimer = 0;
while (mytimer < 100) {
  delay(1);
}

Internally, elapsedMillis does the same thing using millis(). It automatically does this correctly and deals with the millis() roll-over internally, so you can just create as many variables in your code as you like and deal with them in a much simpler way that isn't error prone.
 
Status
Not open for further replies.
Back
Top