Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: arduino delay vs teency 3.2

  1. #1

    arduino delay vs teency 3.2

    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);

    }

  2. #2
    Senior Member
    Join Date
    Nov 2012
    Posts
    956
    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

  3. #3
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    18,511
    Teensy has a feature called elapsedMillis, which is meant to make this sort of code simpler.

    https://www.pjrc.com/teensy/td_timin...pedMillis.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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •