{"id":15742,"date":"2015-12-26T15:13:35","date_gmt":"2015-12-26T15:13:35","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=15742"},"modified":"2019-04-02T10:23:33","modified_gmt":"2019-04-02T10:23:33","slug":"why-you-shouldnt-always-use-the-arduino-delay-function","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/why-you-shouldnt-always-use-the-arduino-delay-function\/","title":{"rendered":"Why You Shouldn\u2019t Always Use the Arduino Delay Function"},"content":{"rendered":"<p>The very first time you used an <a href=\"https:\/\/makeradvisor.com\/tools\/compatible-arduino-uno-r3-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">Arduino\u00a0board<\/a>, you probably did something like this:<\/p>\n<ul>\n<li>Connected an LED\u00a0to your Arduino<\/li>\n<li>Uploaded the default blink sketch\u00a0that\u00a0would turn on and off your\u00a0LED every second<\/li>\n<\/ul>\n<p><!--more--><\/p>\n<p>This is called the\u00a0\u201cHello World\u201d program of Arduino and shows\u00a0that\u00a0with just a few lines of code you can create something\u00a0that\u00a0has a real world application.<\/p>\n<p><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-15744\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/12\/blink-sketch.jpg?resize=632%2C423&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"blink sketch\" width=\"632\" height=\"423\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/12\/blink-sketch.jpg?w=720&amp;quality=100&amp;strip=all&amp;ssl=1 720w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/12\/blink-sketch.jpg?resize=300%2C201&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 632px) 100vw, 632px\" \/><\/p>\n<p>In the preceding example, you use the<em>\u00a0delay()<\/em> function to define the intervals between the LED\u00a0turning on and off.<\/p>\n<p>Here\u2019s the deal: while <em>delay()<\/em> is handy and works for basic examples, you really shouldn\u2019t be using it in the real world&#8230; Keep reading to learn why.<\/p>\n<h2 id=\"how-delay-works\">How <em>delay()<\/em> Function Works<\/h2>\n<p>The way the Arduino\u00a0<em>delay()<\/em> function works is pretty straight forward.<\/p>\n<p>It accepts a single integer as an argument. This number represents the time in milliseconds the program has to wait until moving on to the next line of code.<\/p>\n<p>When you do <em>delay(1000)<\/em> your Arduino stops on that line for 1 second.<\/p>\n<p id=\"the-difference-between-blocking-and-non-blocking-functions\"><strong><em>delay()<\/em> is a blocking function.\u00a0<\/strong>Blocking functions prevent a program from doing anything else until that particular task has completed. If you need\u00a0multiple tasks to occur\u00a0at the same time, you simply cannot use <em>delay()<\/em>.<\/p>\n<p>If your application requires that you constantly read\/save data from inputs, you should avoid using the <em>delay()<\/em> function. Luckily there is a solution.<\/p>\n<h2 id=\"meet-millis\"><em>millis()<\/em> Function to the Rescue<\/h2>\n<p>The <em>millis()<\/em> function\u00a0when called, returns\u00a0the number of milliseconds that have passed\u00a0since the program was first started.<\/p>\n<p><strong>Why is that useful?<\/strong><\/p>\n<p>Because by using some math, you can easily verify how much time has passed without blocking your code.<\/p>\n<p>The sketch below shows how you can use the\u00a0<em>millis()<\/em>\u00a0function to create a blink project. It\u00a0turns the LED light on for 1000 milliseconds, and then turns it off.\u00a0But, it does it in a way that\u2019s <strong>non-blocking<\/strong>.<\/p>\n<p>Let&#8217;s take a closer look at a blink sketch\u00a0that works without a delay function:<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/* \n    Blink without Delay, example here: arduino.cc\/en\/Tutorial\/BlinkWithoutDelay\n*\/\n\n\/\/ constants won't change. Used here to set a pin number :\nconst int ledPin =  13;      \/\/ the number of the LED pin\n\n\/\/ Variables will change :\nint ledState = LOW;             \/\/ ledState used to set the LED\n\n\/\/ Generally, you should use &quot;unsigned long&quot; for variables that hold time\n\/\/ The value will quickly become too large for an int to store\nunsigned long previousMillis = 0;        \/\/ will store last time LED was updated\n\n\/\/ constants won't change :\nconst long interval = 1000;           \/\/ interval at which to blink (milliseconds)\n\nvoid setup() {\n  \/\/ set the digital pin as output:\n  pinMode(ledPin, OUTPUT);\n}\n\nvoid loop() {\n  \/\/ here is where you'd put code that needs to be running all the time.\n\n  \/\/ check to see if it's time to blink the LED; that is, if the\n  \/\/ difference between the current time and last time you blinked\n  \/\/ the LED is bigger than the interval at which you want to\n  \/\/ blink the LED.\n  unsigned long currentMillis = millis();\n\n  if (currentMillis - previousMillis &gt;= interval) {\n    \/\/ save the last time you blinked the LED\n    previousMillis = currentMillis;\n\n    \/\/ if the LED is off turn it on and vice-versa:\n    if (ledState == LOW) {\n      ledState = HIGH;\n    } else {\n      ledState = LOW;\n    }\n\n    \/\/ set the LED with the ledState of the variable:\n    digitalWrite(ledPin, ledState);\n  }\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/blinkWithoutDelay.ino\" target=\"_blank\">View raw code<\/a><\/p>\n<p>This sketch\u00a0above can be found <a href=\"https:\/\/www.arduino.cc\/en\/Tutorial\/BlinkWithoutDelay\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>\u00a0and it\u00a0works by subtracting the previous recorded\u00a0time (<em>previousMillis<\/em>) from the current time (<em>currentMillis<\/em>). If the remainder is greater than the interval (in this case, 1000\u00a0milliseconds), the program updates\u00a0the <em>previousMillis<\/em> variable to the current time, and either turns the LED on or off.<\/p>\n<p><strong>And because it\u2019s a non-blocking<\/strong>, any code\u00a0that\u2019s located\u00a0outside of that first <em>if statement<\/em>\u00a0should work normally.<\/p>\n<p>You can now understand that you could add other tasks to your <em>loop()<\/em> function and your code would still be blinking the LED every one second.<\/p>\n<h2>Which function should\u00a0you use?<\/h2>\n<p>We\u2019ve learned two different ways of dealing with time with the Arduino. Using the\u00a0<em>millis()<\/em>\u00a0functions takes a little of extra work when compared to using\u00a0<em>delay()<\/em>. But your programs can\u2019t do multitasking on the Arduino without it.<\/p>\n<p><strong>Share this post<\/strong> with a friend that also likes electronics!<\/p>\n<p>You can contact me by leaving a comment. If you like this post probably you might like my next ones, so please support me by <a href=\"https:\/\/randomnerdtutorials.com\/download\">subscribing my blog<\/a> and my Facebook Page.<\/p>\n<p>Thanks for reading,<\/p>\n<p>-Rui Santos<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The very first time you used an Arduino\u00a0board, you probably did something like this: Connected an LED\u00a0to your Arduino Uploaded the default blink sketch\u00a0that\u00a0would turn on and off your\u00a0LED every &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Why You Shouldn\u2019t Always Use the Arduino Delay Function\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/why-you-shouldnt-always-use-the-arduino-delay-function\/#more-15742\" aria-label=\"Read more about Why You Shouldn\u2019t Always Use the Arduino Delay Function\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":15749,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[303,2,245,269,264,7,10],"tags":[],"class_list":["post-15742","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-arduino","category-arduino","category-arduino-ide","category-guide-project","category-project","category-a-theory-and-blog","category-a-tutorials"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/12\/delay-vs-timer-arduino.png?fit=1208%2C826&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/15742","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=15742"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/15742\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/15749"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=15742"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=15742"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=15742"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}