A better Arduino “blink without delay”

IMAG1379A while back, I was thinking about the blink without delay sketch that is included with the Arduino IDE, and I’ve come up with a way to blink an LED while still maintaining program flow, yet without all the nasty “currentmillis” variables.

I believe this is the first instance of this method online, as I couldn’t seem to find it anywhere other than where I have posted it in the Arduino forum. Please pick it apart:

1
2
3
4
5
if((millis() % 1000) >; 500){
digitalWrite(ledpin, 1);
} else {
digitalWrite(ledpin, 0);
}

This is saying to turn on or off the LED if it’s in the other half second, using the modulo comparison operator.

For Instance, the code will call the millis() function, which will return the number of milliseconds past the start of the code execution. The modulo will divide that number by 1000 (or 1 second) then compare it to 500 (one half second).

This example allows for the led to be on for approximately half a second, then off for approximately half a second. If you wanted to change the ratio, you simply change the 500 number to either higher (less on time) or lower (more on time, less off time).

The above example cannot be used if you only want something to occur once, as the statements in the if/else may execute tens of thousands of times per second.

Below is a sample code where I used the same method to only execute a line of code (the rbctl function) ONCE every 100 milliseconds:

1
2
3
4
5
6
7
8
9
boolean flipflop = 1;
  for (unsigned int j = 0; j < 60000; j++){
    if(((millis() % 200) > 100) && (flipflop)){           //run rgbctl function every 100 milliseconds
      rgbCtl(255, 255, 0, 30, 1, 0);
      flipflop = 0;
    } else if(((millis() % 200) < 100) && (!flipflop)) {
      flipflop = 1;
    }
  }

Please pick it apart and tell me if I’m missing anything. Enjoy!