Reading sensor values in Spark.function() vs loop()?

I don’t know what made me think of this, but would there be any advantages or disadvantages in reading sensor data by calling a function via Spark.function() versus always updating a variable in the user loop(). It may be better explained using a code example:

Always-updated variable:
int a;
void setup() {
    pinMode(A0, INPUT);
    Spark.variable(“a”, &a, INT);
}

void loop() {
    a = analogRead(A0);
}

Spark.function:
void setup() {
    Spark.function(“getAnalog”, getAnalog);
}

int getAnalog(String command) {
    pinMode(A0, INPUT);
    return analogRead(A0);
}

void loop() {
    // Do nothing
}

Disclaimer: The code above is “free-hand”, meaning I didn’t attempt to compile it; it’s just an example.

Would it generate less heat? Use less power? Solve global warming?

The loop() example will run about 200 times per second.

The function example will run as fast as you can call it from the web, which is probably once or twice per second reliably.

Advantages for speed would be depending on what your analog sensor is. If the sensor updates fast (accelerometer) you would want to read it fast so you don’t miss any data. If the sensor updates slow (temperature) you don’t need to oversample it so much and slow reads would be appropriate.

Advantages for function are remote polling obviously, which is one reason you probably have the Spark Core in the first place :wink:

Obviously you are remotely polling for the variable & loop() example as well, but the sensor is read faster. This is probably the best of both worlds, that is of course if you need the speed.

If you don’t need the speed, then you are wasting real time by oversampling your analog input that could be used for other processing. Right now you have about 5-6 milliseconds of real time to play with per loop() execution. This may change later so check the current specs if you are reading this in the future!

pinMode(A0, INPUT); should be in setup() for both examples. I know I know, free-hand… just saying!

Here’s an example sketch to control how fast your loop() executes code:

Using Interrupts might be even more efficient, where you only listen to changes of the analog input.