Scott Penrose

Arduino Blink

Scott Penrose is a perl hacker with an interest in home automation. He has been playing with electronics since he was old enough to burn his fingers with a soldering iron.

Alternatives to blink...

Have you seen the basic blink example:

#!C
void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  delay(1000);              // wait for a second
}

Now the more no delay version:

#!C
long interval = 1000;           // interval at which to blink (milliseconds)
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
const int ledPin =  13;      // the number of the LED pin
void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;   
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

Both of these keep the state either in code or in a variable. But my thought is, why not allow it to be in the pin itself.

Here is the pin version. 2 lines removed.

#!C
void loop() {
  digitalWrite(13, digitalRead(13) == HIGH ? LOW : HIGH);
  delay(1000);  
}

And the no delay version.

#!C
const long interval = 1000;           // interval at which to blink (milliseconds)
long previousMillis = 0;        // will store last time LED was updated
const int ledPin =  13;      // the number of the LED pin
void loop() {
  if(millis() - previousMillis > interval) {
    previousMillis = millis();   
    digitalWrite(ledPin, digitalRead(ledPin) == HIGH ? LOW : HIGH);
  }
}

In this case I removed lots of lines, a global variable and a local variable.

BTW. Some other notes on the non-delay version:

  • It uses millis() which will wrap around after 52 days. Most hardware I build runs a long time. You need to be aware of the overflow.
  • The interval above has been changed to a constant. You could also use a #define. Again, no variables.
  • My preference for milli test is written like this:
    • if (millis() > nextMillis)
    • nextMillis = millis() + interval;

  • Arduino