Cloud functions
Particle.variable() - calculated
Since 1.5.0: It is also possible to register a function to compute a cloud variable. This can be more efficient if the computation of a variable takes a lot of CPU or other resources. It can also be an alternative to using a Particle.function(). A function is limited to a single int (32-bit) return value, but you can return bool, double, int, String from a Particle.variable. String data has a maximum size of 255 to 1024 bytes of UTF-8 characters; see API Field Limits as the limit varies depending on Device OS version and sometimes the device.
Such a function should return a value of one of the supported variable types and take no arguments. The function will be called only when the value of the variable is requested.
The callback function is called application loop thread context, between calls to loop(), during Particle.process(), and delay().
// EXAMPLE USAGE - registering functions as cloud variables
bool flag() {
return false;
}
int analogvalue() {
// Read the analog value of the sensor (TMP36)
return analogRead(A0);
}
double tempC() {
// Convert the reading into degree Celsius
return (((analogvalue() * 3.3) / 4095) - 0.5) * 100;
}
String message() {
return "my name is particle";
}
void setup()
{
Particle.variable("flag", flag);
Particle.variable("analogvalue", analogvalue);
Particle.variable("temp", tempC);
Particle.variable("mess", message);
pinMode(A0, INPUT);
}
void loop()
{
}
It is also possible to pass a std::function
, allowing the calculation function to be a method of a class:
// CALCULATED FUNCTION IN CLASS EXAMPLE
class MyClass {
public:
MyClass();
virtual ~MyClass();
void setup();
String calculateCounter();
protected:
int counter = 0;
};
MyClass::MyClass() {
}
MyClass::~MyClass() {
}
void MyClass::setup() {
Particle.variable("counter", [this](){ return this->calculateCounter(); });
}
String MyClass::calculateCounter() {
return String::format("counter retrieved %d times", ++counter);
}
MyClass myClass;
void setup() {
myClass.setup();
}
void loop() {
}
Each variable retrieval uses one Data Operation from your monthly or yearly quota. Setting the variable does not use Data Operations.