Blinks LEDs using millis()

blue circuit board
blue circuit board

Imagine you want to make an LED light blink on and off, but you also want your Arduino to stay responsive and not get stuck while blinking. That's where the `millis()` function comes to the rescue! It's a smart way to handle time in your projects. Let's learn how to use it step by step.

What You'll Need:

- An Arduino board (like Uno or Nano)

- A computer with Arduino IDE installed

- A simple LED

- A breadboard and wires to connect everything

Step 1: Setting Up the Basics

First, make sure your LED is connected to one of the digital pins on your Arduino. The longer leg (anode) should be connected to the pin, and the shorter leg (cathode) to the ground (GND) pin.

Step 2: The Code Explained

Here's an example of how to use the `millis()` function to blink your LED:

How It Works:

- `millis()` returns the current time since the Arduino started running.

- The `previousMillis` variable keeps track of when the LED was last changed.

- `interval` defines how long the LED stays on or off (here, 1000 milliseconds or 1 second).


Step 3: What the Code Does

The code checks if the time interval specified by `interval` has passed since the last time the LED changed state. If it has, the LED state toggles (on to off or off to on). This way, your LED blinks without freezing the Arduino.

Step 4: Upload and see the Magic

1. Connect your Arduino to your computer and select your board in the Arduino IDE.

2. Click the "Upload" button to send the code to your Arduino.

3. Watch as your LED blinks on and off smoothly without freezing the Arduino!

Using `millis()` lets your Arduino do multiple tasks at once, making your projects more dynamic and responsive. So go ahead, experiment with different intervals, and enjoy the power of precise timing in your Arduino adventures! All the best.