Advertisement
TolentinoCotesta

not-blocking delay

Jul 22nd, 2019
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. class nb_delay {
  2.   public:
  3.     bool isRunning = false;
  4.     void start(unsigned long delay){
  5.       if (!isRunning) {
  6.         isRunning = true;
  7.         t_start = millis();
  8.         t_delay = delay;
  9.       }
  10.     }
  11.     bool elapsed(){
  12.       if (isRunning && (millis() - t_start >= t_delay) ){
  13.         isRunning = false;
  14.         return true;  // timer is elapsed
  15.       }      
  16.       return false;
  17.     }    
  18.   private:    
  19.     unsigned long t_start = millis();
  20.     unsigned long t_delay = 1000;  
  21. };
  22.  
  23. nb_delay delay1, delay2;
  24. const byte Start_Delay2 = 2;
  25. unsigned int counter = 1;
  26.  
  27. void setup() {
  28.   Serial.begin(115200);
  29.   Serial.println(F("Non Blocking delay example"));
  30.   pinMode(LED_BUILTIN, OUTPUT);  
  31.   pinMode(Start_Delay2, INPUT_PULLUP);
  32. }
  33.  
  34. void loop() {
  35.   delay1.start(500);
  36.  
  37.   // Blink onboard LED every 500ms
  38.   if (delay1.elapsed()){
  39.     digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  40.   }
  41.  
  42.   // Start delay2 only when button on pin D2 was pressed
  43.   if(digitalRead(Start_Delay2) == LOW ){
  44.     /* Debounce if necessary.
  45.     *  Increase delay(1) for bad contact.
  46.     *  Here we need a blocking delay(!) or use a suitable RC filter.
  47.     */  
  48.     //while(digitalRead(Start_Delay2) == LOW){delay(1);}  
  49.  
  50.     // Start delay2 with a timeout depending on value of counter
  51.     Serial.print(F("\nStart delay2 at "));
  52.     Serial.println(millis());
  53.     Serial.print(F("Time to wait: "));
  54.     Serial.println(counter*1000);    
  55.     delay2.start(counter*1000);    
  56.     counter++;
  57.   }
  58.  
  59.   if (delay2.elapsed()){
  60.      Serial.print(F("delay2 time has elapsed: "));
  61.      Serial.println(millis());
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement