• 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/

This Article Has Been Shared 349 Times!

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 Temperature Humidity Sensor : New DHT11, DHT21, DHT22 Test Code

    Here is New Test Codes For Arduino Temperature Humidity Sensor DHT11, DHT21, DHT22 Test Code as Hardware (Not Shields). 2 Libraries Needed.

  • What is I²C Protocol? Relevance of I²C in Arduino

    Previously, we discussed about UART. What is I²C Protocol? I squared C (also pronounced as I-two-C) or I²C is a bus serial communication protocol designed by Philips for home automation and home electronics applications. Since 2006, licensing fees not needed to implement the I²C protocol. Fees needed to obtain I²C slave addresses allocated by NXP. […]

  • M5Stack (ESP32 Arduino) : Modular, Stackable, Wearable IoT Platform

    M5Stack is ESP32 Arduino by heart. It is a modular, stackable, wearable IoT platform for development which is obviously Open Source.

  • How to Work With Tasmota on ESP32

    Tasmota is an Open-Source firmware for ESP devices developed by Theo Arends (from the Netherlands). He is also the webmaster of a technology blog with nice tutorials. Tasmota is not written in “Arduino language”, however, you will not need to code with Tasmota. It is mostly about uploading the code, hardly changing 1-2 lines for […]

  • How to Test USB to TTL Converter

    A USB-to-TTL adapter (USB-to-UART adapter, USB-to-UART bridge) is a USB device that lets us connect a device with TTL/UART port to our PC through the regular USB port. We can use it to update firmware on routers, modems, mobile phones, hard disks, and so on. For testing AT Commands, we need a USB-TTL module built […]

Additionally, 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

  • Exploring the Benefits and Advantages of Microsoft’s Operating System March 22, 2023
  • Web Design Cookbook: Accessibility March 21, 2023
  • Online Dating: How to Find Your Match March 20, 2023
  • Web Design Cookbook: Logo March 19, 2023
  • How Starlink Internet Works March 17, 2023

About This Article

Cite this article as: Abhishek Ghosh, "How to Replace delay() with millis() : Arduino Programming," in The Customize Windows, December 19, 2021, March 22, 2023, https://thecustomizewindows.com/2021/12/how-to-replace-delay-with-millis-arduino-programming/.

Source:The Customize Windows, JiMA.in

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

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT