For my code I use a couple of static variables. But when I search the internet, they seem "evil".
For example: I have a function which will be executed every loop (5ms looptime). to increase the speed I added some static variables to it. Is the way I am doing this bad? Are there simple solutions for it?
Code:
int ProgFormula() {
static int StartPosition;
static int DeltaPosition;
static int LoopTime = 5;
static int AccelerationLoops;
static int TotalLoops;
static int EndOne;
static float VelocityLoop;
static float VelocityFactor;
int Setpoint;
if (Iteration == -1) {
StartPosition = PID.ActualPosition;
DeltaPosition = abs(SetPosition - StartPosition);
VelocityLoop = Velocity / (1000 / LoopTime);
TotalLoops = DeltaPosition / VelocityLoop;
if (TotalLoops <= (AccelerationLoops * 2)) {
AccelerationLoops = (TotalLoops / 2);
VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
}
else {
AccelerationLoops = 70;
VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
}
TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
}
else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
if (StartPosition < SetPosition) {
Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
}
else {
Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
}
}
else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
if (StartPosition < SetPosition) {
Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
}
else {
Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
}
}
else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
if (StartPosition < SetPosition) {
Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
}
else {
Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
}
}
else {
Setpoint = Setpoint;
}
return(Setpoint);
}
Is it better to avoid statics? If so why?
Thanks in advance, Koen
#define <name> <value>
orconst <Type> <name> = <value>
. These declarations/definitions get 'smoothed out' by the compiler and so don't take up any program memory.to increase the speed I added some static variables to it.
- how does that increase the speed?pow(AccelerationLoops, 2)
- you want fast speed but then you call a function that will be slow?