In several code examples for the Arduino, I note that there is almost no use of locally scoped variables. One of the examples in the IDE: Analog > AnalogInput
:
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
}
The variable sensorValue
is global, whereas its use is only within the loop
function. Another case is the Moving-Average-Filter library. Part of the code:
#define MAX_DATA_POINTS 20
class MovingAverageFilter {
public:
MovingAverageFilter(unsigned int newDataPointsCount);
float process(float in);
private:
float values[MAX_DATA_POINTS];
int k;
int dataPointsCount;
float out;
int i;
};
Here the out
and i
members are only used in process
, and should be local:
float MovingAverageFilter::process(float in) {
out = 0;
values[k] = in;
k = (k+1) % dataPointsCount;
for (i=0; i<dataPointsCount; i++) {
out += values[i];
}
return out/dataPointsCount;
}
Using variables in this way seems absurd to me. Is this intentional? If so, what is the reason?
The only possibility I can imagine is that the address of local variables would be known at compile time, so they can be accessed without taking into account the stack's register. Does it really make a difference?
But in the case of the class, I can not see how it could be faster to read an object through the this
pointer than to read it in the stack relative to the registered.
Another explanation might be to avoid having to allocate a stack frame to the function. But this allocation should be as simple as incrementing a registrant, I do not understand why it should be avoided. In addition, functions that take arguments will have a stack frame anyway.