Pages: 1 2 [3]   Go Down
Author Topic: Blink Without Delay Revisited  (Read 2122 times)
0 Members and 1 Guest are viewing this topic.
the land of sun+snow
Offline Offline
Faraday Member
**
Karma: 159
Posts: 2916
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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:
- 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 */
Logged

West Des Moines, Iowa USA
Offline Offline
Sr. Member
****
Karma: 2
Posts: 428
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Summary with modifications to allow the demo program to run forever:
Code:
#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     */
}
Logged

There's always a better way!

Pages: 1 2 [3]   Go Up
Jump to: