Categories
Arduino

Arduino delay(), millis(), etc. cause execution to halt in a library

I ran into an interesting issue yesterday while rewriting some Arduino code into a library. I figure out what was the issue but I’m not sure as to why. If someone reads this and can point me to the reason why this was an issue, please comment on this post. I would appreciate it.

PROBLEM STATEMENT (Observation): Adding any timing function in my library file would halt the execution. The time functions includes delay(), delayMicroseconds(), micros(), and millis().

ROOT CAUSE: The time function was being called in the constructor of the class. If the time function was moved to another method and called separately, the time function would work.

RESOLUTION: Modified the code to create the object, then make a call to a public method of the class. I used begin() as I have seen in other classes.

Problem code demonstrating the issue

sample.ino

#include "mylib.h"

mylib myObject = mylib();

const int ledPin =  LED_BUILTIN;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
   pinMode(ledPin, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    digitalWrite(ledPin, !digitalRead(13));
  }
}

mylib.h

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class mylib {
  public:
    // Constructors
    mylib();

  private:
    void initialize();
};

mylib.cpp

#include "mylib.h"

mylib::mylib() {
  initialize();
}

mylib::initialize() {
  delay(100);
}

Working code demonstrating the solution

sample.ino

#include "mylib.h"

mylib myObject = mylib();

const int ledPin =  LED_BUILTIN;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
  myObject.begin();
}

void loop() {
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    digitalWrite(ledPin, !digitalRead(ledPin));
  }
}

mylib.h

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class mylib {
  public:
    // Constructors
    mylib();

    void begin();

  private:
    void initialize();
};

mylib.cpp

#include "mylib.h"

mylib::mylib() {
  
}

mylib::begin() {
  initialize();
}

mylib::initialize() {
  delay(100);
}

By richteel

Software and hardware developer who likes learning new things with a passion of sharing knowledge with others.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: