Book Image

Arduino Development Cookbook

By : Cornel M Amariei
Book Image

Arduino Development Cookbook

By: Cornel M Amariei

Overview of this book

Table of Contents (16 chapters)
Arduino Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 for the LED as Output
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop(){
  
  // Here we can write any code we want to execute continuously
  // Read the current time
  unsigned long currentTime = millis();
  
  // Compare the current time with the...