Introduction: Non-blocking Virtual Delay Library for the Arduino
Introduction
The standard Arduino delay() function blocks the Arduino, that is not always allowed. The standard delay has limitations too; it is not possible to use multiple delays at the same time. So I decided to developed a VirtualDelay library which has many advantages:
Step 1: Advantages of the VirtualDelay Library
- The delay is virtual, during the delay, the code execution is continued
- We can use multiple delays sequentially in a loop.
- We can use multiple delays simultaneously and independent of each other.
- The delay time can set in micro-seconds or milli-seconds.
- No hardware timers are used
There is another article HERE.
Step 2: Video
Step 3: Virtual Delay Library Files
You can download the library from GitHub.
Step 4: Simple Blinking LED Sketch With the VirtualDelay Library
#include <arduino.h><br>#include "avdweb_VirtualDelay.h" #include <streaming.h></streaming.h></arduino.h>
const byte ledPin = 13; bool b; int i; VirtualDelay singleDelay; // default = millis
void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); }
void loop() { singleDelay.start(400); // calls while running are ignored if(singleDelay.elapsed()) digitalWrite(ledPin, b=!b); // blink the onboard LED Serial << endl << i++; }
Attachments
Step 5: Using 3 VirtualDelays in Sequence
Here we need three separate VirtualDelay instances: delay1, delay2 and delay3. The line with the macro DO_ONCE ensures that the sequence is started. You may use any instance e.g. delay2.start(0).
#include <arduino.h><br>#include "avdweb_VirtualDelay.h" #include <streaming.h></streaming.h></arduino.h>
const byte ledPin = 13; bool b; int i; VirtualDelay singleDelay; // default = millis
void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); }
void loop() { singleDelay.start(400); // calls while running are ignored if(singleDelay.elapsed()) digitalWrite(ledPin, b=!b); Serial << endl << i++; }
This is the serial output:
delay1 200ms 200
delay2 100ms 300
delay3 400ms 700
delay1 200ms 900
delay2 100ms 1000
delay3 400ms 1400
delay1 200ms 1600
Attachments
Step 6: One-shot Example
To create a one-shot, start() may only be called once during the loop, to do so, the macro DO_ONCE is used.
#include
#include #include "avdweb_VirtualDelay.h"
VirtualDelay delay1;
void setup() { Serial.begin(9600); Serial << "\ntestOneShot 2s\n"; }
void loop() { DO_ONCE(delay1.start(2000)) // do only one time in the loop if(delay1.elapsed()) Serial << millis() << "ms" ; }