I can’t see any memory change in my .map file when I try to compare the two different codes.
Is there a “good practice” to follow here? Should I or shouldn’t I put the variables in the header?
As a note, I can have multiple PIDUpdate() functions, I allready have two (if that makes any difference).
First example without variables in the header -> main.c
static int16_t PIDUpdate(int16_t target, int16_t feedback) // Valve
{
static float pTerm, iTerm, dTerm;
static float PID;
int16_t CurrentError;
static float LastError, SumError;
uint16_t tick;
static uint16_t elapsed;
float Kp = 0.1, Ki = 0.1, Kd = 0.1;
Kp = (float) pGain/10000.0;
Ki = (float) iGain/10000.0;
Kd = (float) dGain/10000.0;
....
if(elapsed = tick - timestamp, elapsed < TRACKING_PERIOD)
goto leave;
timestamp = tick;
CurrentError = target - feedback;
pTerm = Kp * CurrentError;
// Calculate the Integral State with appropriate Limiting
....
iTerm = Ki * SumError;
dTerm = Kd * (LastError - CurrentError);
LastError = CurrentError;
PID = pTerm + iTerm + dTerm;
control = PID;
....
leave:
return (control);
}
The other example with variabels in header instead -> main.h
typedef struct PID
{
// PID parameters
uint16_t Kp; // pGain
uint16_t Ki; // iGain
uint16_t Kd; // dGain
// PID calculations
float pTerm;
float iTerm;
float dTerm;
float PID;
// Extra variabels
int16_t CurrentError;
// PID Time
uint16_t tick;
}pid_object;
typedef static struct staticPID
{
// Extra variabels
int16_t control;
float LastError;
float SumError;
// PID Time
uint16_t elapsed;
uint16_t timestamp;
}StaticPid_object;
Now the main.c code togheter with above .h-file
static int16_t PIDUpdate(int16_t target, int16_t feedback) // Valve
{
pid_object _PID_t;
StaticPid_object _StatPID_t;
_PID_t.Kp = (float) pGain/10000.0;
_PID_t.Ki = (float) iGain/10000.0;
_PID_t.Kd = (float) dGain/10000.0;
if(_StatPID_t.elapsed = _PID_t.tick - _StatPID_t.timestamp, _StatPID_t.elapsed < TRACKING_PERIOD)
goto leave;
_StatPID_t.timestamp = _PID_t.tick;
_PID_t.CurrentError = target - feedback;
_PID_t.pTerm = _PID_t.Kp * _PID_t.CurrentError;
// Calculate the Integral State with appropriate Limiting
....
_PID_t.iTerm = _PID_t.Ki * _StatPID_t.SumError;
_PID_t.dTerm = _PID_t.Kd * (_StatPID_t.LastError - _PID_t.CurrentError);
_StatPID_t.LastError = _PID_t.CurrentError;
_PID_t.PID = _PID_t.pTerm + _PID_t.iTerm + _PID_t.dTerm;
_StatPID_t.control = 255-_PID_t.PID; // Make it work oposite to Heater
leave:
return (_StatPID_t.control);
}
It doesn’t matter where your code is — in
.hor in.c, but if you include the header defining static variable in multiple files, you’ll have different instance for each file. What matters here is if this is what you want.