Go Down

Topic: Blink Without Delay Revisited (Read 2646 times) previous topic - next topic

oric_dan


Quote

The subtraction method of calculating elapsed time means you don't need to care if it overflows or not.


Nick, bravo to you and Coding Badly. I made one last test, and now I can get on with the rest of
my life. I took Morris' original example, start of this thread, and tried both sets of lines below,
along with starting the clock near the wraparound point.

Code: [Select]

- startup:
extern unsigned long timer0_millis;

  timer0_millis = 4294967295UL - 5000UL;

- original: this crashes on wrap, and it crashes horribly if change >= to > in the test.

   blinkTime = millis() + 250;         /* Schedule next state change          */
.....
  if (millis() >= blinkTime) blink(); /* If it's time to change state, do it */

- subtraction method - this flows:

   blinkTime = millis();         /* Schedule next state change          */
........
  if( (millis() - blinkTime) >= 250) blink(); /* If it's time to change state, do it */


Morris Dovey

Summary with modifications to allow the demo program to run forever:
Code: [Select]
#define LED 13
unsigned long blinkTime = 0;           /* [s]When to execute[/s] When scheduled      */

void blink(void)
{  static int x = 0;                   /* Current LED state 0=>off, 1=>on     */
   digitalWrite(LED,x ^= 1);           /* Set LED to opposite state           */
   blinkTime = millis();               /* Schedule next state change          */
}
void watch(void)
{  if (millis() - blinkTime >= 250)    /* If it's time to change state        */
      blink();                         /*  then go do it                      */
}
void setup(void)
{  pinMode(LED,OUTPUT);                /* Use on-board LED as output          */
}
void loop(void)
{  watch();                            /* Change state whenever it's time     */
}
There's always a better way!

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy