Writing a custom waitFor function that can be used as a member of a class

I am attempting to write and implement my own waitFor function that is a public member of a class, and waits for another public member of the same class which is of type boolean to change to true. I am using this as an acknowledgment between two functions for one to let the other know it is complete. I will write the code to explain.



#ifndef MyClass_h
#define MyClass_h

namespace myProject
    class MyClass
            bool publicFlagMember;
            bool waitForFlag();
            void simpleFunction();


Function that I have previously tried

bool MyProject::MyClass::waitForFlag(uint16_t timeout)
    uint16_t timer = millis();
    while (millis() - timer <= timeout)
        // call Particle.process() to ensure that when the variable changes we catch it
        if (publicFlagMember)
            return true;

    return false;

void MyProject::MyClass::simpleFunction(){
    // do something
   publicFlagMember = true;

Expectations vs. reality

I expected this function to work similarly to particle.io’s waitFor() function, and it does, it works exactly as you would expect it to for the first 15-20 iterations, and at a certain point the function no longer returns true even if the member boolean is set to true elsewhere in the program.

I am hoping someone can provide some insight on this topic, thanks in advance.

P.S. If there is a way to use the default particle.io waitfor function from within a class to wait on a class member that would be ideal.

This method of organization is usually not the best, as it becomes impossible to scale. The main issue is that you can only wait on one thing in the entire program. Any time you need to wait from two different classes, it becomes impossible as there is no way to interrupt the wait in progress.

There are two general solutions:

Finite state machines work by always returning immediately without blocking. They allow many simultaneous waits because each class can wait independent of every other class.

The other is threads. The difference is that each thread can block without blocking the other threads. The downside is that threads are memory-intensive so you may run out of RAM if you have more than a few threads.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.