• Home
  • Archive
  • Tools
  • Contact Us

The Customize Windows

Technology Journal

  • Cloud Computing
  • Computer
  • Digital Photography
  • Windows 7
  • Archive
  • Cloud Computing
  • Virtualization
  • Computer and Internet
  • Digital Photography
  • Android
  • Sysadmin
  • Electronics
  • Big Data
  • Virtualization
  • Downloads
  • Web Development
  • Apple
  • Android
Advertisement
You are here:Home » How to Replace delay() with millis() : Arduino Programming

By Abhishek Ghosh December 19, 2021 8:24 pm Updated on December 19, 2021

How to Replace delay() with millis() : Arduino Programming

Advertisement

In many of the sketches shared by us have the millis() instead of delay(). Not always it is possible to explain a function within a guide on how to do a thing. In this article, we will explain about millis() and provide some easy examples so that you can reproduce yourself.

It is normal that the Arduino users initially use the delay() function. The main reason is the blink example is the thing that almost every newbie starts with. While the delay() function is easy to use it has side effects.
One of the main complain (or side effects) of the delay() function is that it stops all activity on the Arduino until the delay is finished. It is not quite true, but this is what usually the problem becomes.

We already know how to set the pinMode() of input and output. Any pin including pins A1, A2, A3 other than 0 and 1 can be used as digital inputs.

Advertisement

---

There are two type of delay functions, first is delay() and second is delayMicroseconds(). Both functions are near the same except unit. When we are adding a delay of 1 second, the microcontroller cannot proceed till that 1 second is passed. It is like a pause function. This essentially hampers the performance and speed. If we want to control two LEDs using two pushbuttons, then the delay() function will not work. Arduino 2 Push Button One LED Switch On/Off is a situation where we still could use the delay() function.

This is the traditional example of Blink :

Vim
1
2
3
4
5
6
7
8
9
10
11
int led = 13;
 
void setup() {                
  pinMode(led, OUTPUT);    
}
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Blink without Delay is the example where the delay() function is replaced by millis() :

Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
bool ledState = false; // state variable for the LED
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, ledState);
}
void loop() {
unsigned long currentMillis = millis(); // grab current time
// check if "interval" time has passed (1000 milliseconds)
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
  
   ledState = !ledState; // "toggles" the state
   digitalWrite(13, ledState); // sets the LED based on ledState
   // save the "current" time
   previousMillis = millis();
}
}

Above is the shortest, easiest “Blink without Delay” sketch. The advantage is that if you want to add two LEDs in the above sketch, then add in this way :

Vim
1
2
unsigned long previousMillisLED12=0;
unsigned long previousMillisLED13=0;

You need not to alter this :

Vim
1
2
3
4
void loop() {
   // get current time stamp
   // only need one for both if-statements
   unsigned long currentMillis = millis();

Slightly complex version can be this example :

Vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int ledPin =  13;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
long OnTime = 250;           // milliseconds of on-time
long OffTime = 750;          // milliseconds of off-time
 
void setup()
{
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);      
}
 
void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();
  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis;  // Remember the time
    digitalWrite(ledPin, ledState);  // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis;   // Remember the time
    digitalWrite(ledPin, ledState);  // Update the actual LED
  }
}

As you can see, using the millis() function will make a sketch more complicated but the sketch becomes significantly more mature.

How to Replace delay with millis

Now the above sketches will run happily deducting the current time by turning the LED on and off. But if you code in a manner to compare, after just over 49 days, the value returned by millis() will get so large that it will not fit in an unsigned long variable and it will roll over to zero and start incrementing again. After handling the basics, you should read the below webpages:

Vim
1
2
3
https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover
https://www.learncpp.com/cpp-tutorial/unsigned-integers-and-why-to-avoid-them/
https://www.gammon.com.au/millis

Tagged With https://thecustomizewindows com/2021/12/how-to-replace-delay-with-millis-arduino-programming/
Facebook Twitter Pinterest

Abhishek Ghosh

About Abhishek Ghosh

Abhishek Ghosh is a Businessman, Surgeon, Author and Blogger. You can keep touch with him on Twitter - @AbhishekCTRL.

Here’s what we’ve got for you which might like :

Articles Related to How to Replace delay() with millis() : Arduino Programming

  • Arduino and LED Bar Display : Circuit Diagram, Code

    Here is a Guide Explaining the Basics, Circuit Diagram, Code on Arduino and LED Bar Display. LED Bar Display is Actually Like Multiple LED.

  • How to Control Multiple Relays With Single Arduino ESP32?

    Before How to Control Multiple Relays With Single Arduino ESP32 Testing, You Need to Learn How to Create Multiple MQTT Channels & Fetch Data.

  • Arduino ESP32 : Turn on LED on Button Press and Turn Off After a Period

    Here is How to Turn on LED on Button Press and Turn Off After a Period on Arduino ESP32. For this guide, we will use onboard boot button and onboard LED.

  • Arduino : Independently Blink Multiple LED

    A practical question which comes up every day is how to blink two LEDs at different rates? That simply means an independent control on each LED. That small wish is a big jump to visual animation. In real life, the multi-coloured Christmas lights (aka Dewali lights) blinks in that fashion to give us a great […]

performing a search on this website can help you. Also, we have YouTube Videos.

Take The Conversation Further ...

We'd love to know your thoughts on this article.
Meet the Author over on Twitter to join the conversation right now!

If you want to Advertise on our Article or want a Sponsored Article, you are invited to Contact us.

Contact Us

Subscribe To Our Free Newsletter

Get new posts by email:

Please Confirm the Subscription When Approval Email Will Arrive in Your Email Inbox as Second Step.

Search this website…

 

Popular Articles

Our Homepage is best place to find popular articles!

Here Are Some Good to Read Articles :

  • Cloud Computing Service Models
  • What is Cloud Computing?
  • Cloud Computing and Social Networks in Mobile Space
  • ARM Processor Architecture
  • What Camera Mode to Choose
  • Indispensable MySQL queries for custom fields in WordPress
  • Windows 7 Speech Recognition Scripting Related Tutorials

Social Networks

  • Pinterest (24.3K Followers)
  • Twitter (5.8k Followers)
  • Facebook (5.7k Followers)
  • LinkedIn (3.7k Followers)
  • YouTube (1.3k Followers)
  • GitHub (Repository)
  • GitHub (Gists)
Looking to publish sponsored article on our website?

Contact us

Recent Posts

  • PowerAmp Settings for Higher Sound QualityOctober 4, 2023
  • Affordable Earphone/IEM for Audiophiles: HiFiMan RE-400 WaterlineOctober 2, 2023
  • What is Hardware Security Module (HSM)September 30, 2023
  • Transducer Technologies of HeadphonesSeptember 28, 2023
  • What is Analog-to-Digital Converter (ADC)September 27, 2023
PC users can consult Corrine Chorney for Security.

Want to know more about us?

Read Notability and Mentions & Our Setup.

Copyright © 2023 - The Customize Windows | dESIGNed by The Customize Windows

Copyright  · Privacy Policy  · Advertising Policy  · Terms of Service  · Refund Policy