New design for built-in blinkWithoutDelay sketch

I have found a simpler design for the blinkWithoutDelay sketch:

void setup() {
//Setup
pinMode(13, OUTPUT);
}

void loop() {
//Loop
digitalWrite(13, (millis()/1000)%2);
}

The original (I haven't done the syntaxic coloration):
Admit this is WAY longer than mine

const int ledPin = LED_BUILTIN;

int ledState = LOW;

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store

unsigned long previousMillis = 0; // will store last time LED was updated

// constants won't change:
const long interval = 1000; // interval at which to blink (milliseconds)

void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}

void loop() {
// here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the difference
// between the current time and last time you blinked the LED is bigger than
// the interval at which you want to blink the LED.
unsigned long currentMillis = millis();

if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}

// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}

arduino_uno_cool:
I have found a simpler design for the blinkWithoutDelay sketch:

In what way is it simpler?

And is it better as a teaching aid for beginners?

...R

arduino_uno_cool:
I have found a simpler design for the blinkWithoutDelay sketch:

It has a flaw.

It consumes significantly more CPU time than the alternative.

Variable delays range from difficult to impossible.

void loop() {

digitalWrite(13, (millis()/1000)%2);
}



... consumes significantly more CPU time than the alternative

For non-critical times, you could do something like:

   digitalWrite(13, millis() & 1024);

:slight_smile:
I still like The functions I wrote. I don't know why we're so obsessed with putting the millis() manipulation in-line with the rest of the code, where they can really obscure wha's going on...

  if (delay_without_delaying(ledtime, 500)) {
    ledstate = !ledstate;
    digitalWrite(13, ledstate);
  }

westfw:
For non-critical times, you could do something like:

   digitalWrite(13, millis() & 1024);

:slight_smile:

That won't blink on an AVR. :wink:
What happens when you put millis() & 1024 into uint8_t?