Posted on

LED Blinking using Arduino without Delay

In our previous blog, we have discussed a simple LED blinking project with the delay() function. Some time we need to do multiple works in one Arduino board and the code gets complex. The unnecessary usage of delay blocks can create problem. In this work, a simple project on LED Blinking using Arduino without Delay is demonstrated which is based on millis() function. This function returns the number of milliseconds passed since the Arduino board began running the current program.

Initially a constant interval is set equal to the desired value of delay. Inside the void loop, the current time instant is saved in a variable called currentMillis. Another variable previousMillis is used which initially zero. Now, an if-else loop is initiated. If the difference, (currentMillis – previousMillis) is greater than or equal to the constant interval, then the variable previousMillis gets the value of currentMillis and the state of the LED is altered. At the beginning of the loop, variable currentMillis again gets the time instant when the state of the LED is changed last time. This way LED is turned on and off using the if-else loop.

Required Components

  • Arduino Uno Board
  • LED
  • 1 Resistor (100 to 220 ohm)

Connections for LED Blinking using Arduino

The positive terminal of the LED is connected to the pin ‘13’ of the Arduino through a resistor and the negative terminal of the LED is connected to the GND pin of the Arduino pin.  The connection diagram is shown in Figure 1.

LED blinking using Arduino without delay
Figure 1: The schematic of the LED blinking project.

Code for the LED Blinking using Arduino without Delay

//project name- Blink LED without Delay.
int ledPin =   13 ;       // the number of the LED pin
const long interval = 1000 ; // interval at which to blink the LED (in ms)

void setup ( ) {
  // set the digital pin as output:
  pinMode ( ledPin , OUTPUT ) ;
}

void loop ( ) {
  // here is where you'd put code that needs to be running all the time.
    unsigned long currentMillis = millis ( ) ;

  if ( currentMillis - previousMillis >= interval ) {
    // save the last time you blinked the LED 
    previousMillis = currentMillis ;

    // if the LED is off turn it on and if it is off , turned it on :
    if ( ledState == LOW ) {
      ledState = HIGH ;
    } else {
      ledState = LOW ;
    }
    // set the LED with the ledState of the variable:
    digitalWrite ( ledPin , ledState ) ;
  }
}

Conclusion

The code which is depicted here is easy to understand and an efficient one. The circuit may help anyone to blink a led without any delay continuously. It is a basic example of multitasking; you may use it in any project without any problem.