Blinking LED without delay()

It is easy to make the LED blink on an Arduino. We turn it on, wait, turn it off, wait again, and then we repeat the cycle. However, this wait state will completely halt the Arduino execution. We want to make the LED blink while the Arduino is performing other actions.

Getting ready

For this recipe all you need is an Arduino board connected to the computer via USB.

How to do it…

The following code will make the internal LED blink on the Arduino without ever using the delay() function:

// Variable for keeping the previous LED state
int previousLEDstate = LOW;

unsigned long lastTime = 0; // Last time the LED changed state
int interval = 200; // interval between the blinks in milliseconds

void setup() { // Declare the pin ...

Get Arduino Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.