analogRead inside a software timer

Is it safe to call analogRead from a software timer , perform some simple math, and store the result in a global variable? Is there potential for a data race if this variable is used in the loop? I am trying to build an digital adc filter using software timers.

I have several apps that do this. Here is some sample code that shows the logic that I use. This sample compiles and has a particle variable so you can "get"the computed value via the Web IDE console.

const int analogReadInterval = 2; // interval (in seconds)
time_t nextAnalogReadTime = 0;
double computedValue = 0;

void setup() {
    // added so you can see the computed value in Particle Console
    Particle.variable("cValue", computedValue);
}

void loop() {
    if (Time.now() >= nextAnalogReadTime) {
        nextAnalogReadTime += analogReadInterval;               // schedule the next read
        computedValue = (analogRead() + 39) * 2 / 3;            // read and compute
    }
}

double analogRead() {
    return (random(1000));
}

@felixgalindo, treat a Software Timer like an Interrupt Service Routine. That is, keep it short and quick. As such, doing an analog read (integer) and some simple math (ideally integer) will be fine. Again, if you are concerned about sharing a global variable, as you asked in another topic, then create a circular buffer. The timer would write to it and loop() would read from it. This is a common “decoupling” mechanism. Using a circular buffer means the timer reads/writes “head” pointer while loop() reads/writes the “tail” pointer so there is no conflict. :wink:

1 Like