What a complete mess that code was.
Most of the errors were:-
-
Not defining a variable that you use in a function. Should some of the variables be global. If a variable is defined in a function it is independent of any variable of the same name declared in another function.
-
When defining a function you need to declare the variable type you are passing into it.
-
Not enough closing braces in the only line in the loop() function - you needed an extra 3.
I have defined variables inside the functions that you have missed but you will probably have to define them where you need them with the value you need.
int sensePin = 0;
void setup()
{
analogReference(DEFAULT);
pinMode (3, OUTPUT);
pinMode (5, OUTPUT);
Serial.begin(9600);
}
void loop()
{
actuate(PID(calculateError(getSetpoint(), getFeedback())));
}
//setpoint data acquisition
float getSetpoint()
{
int setpointPin = A1;
float setpoint = analogRead(setpointPin);
return setpointPin;
}
//feedback data acquisition
float getFeedback()
{
int feedbackPin = A5;
float feedback = analogRead(sensePin);
return feedback;
}
//calculate error
float calculateError(float setpoint, float feedback)
{
float error;
error = setpoint - feedback;
return error;
}
//PID function===>returns output
float PID(float error)
{
float pGain = 0;
float IGain = 0;
float DGain = 0;
float output;
output = proportional(error) + integral(error) + differential(error);
}
//proportional function
float proportional( float pError)
{
float pGain = 0;
float pOutput = pError * pGain; //calculate de proportional part of the output
return pOutput;
}
//integral function
float integral(float Error)
{
float iState = 0; //sum of the past errors
float iMax = 0; //max value of iState
float iMin = 0; //min value of iState
iState += Error; //update iState
iState = constrain(iState, iMin, iMax); //constrain iState to avoid windup
float iGain = 0;
float iOutput = iState * iGain; //calculate the integral output
return iOutput;
}
//differential function
float differential(float Error)
{
float lastError;
float dGain = 0;
float errorDifference = Error - lastError; //error variation
float dOutput = dGain * errorDifference; //calculate the differential output
lastError = Error; //save the current error to reuse it next time
return dOutput;
}
//actuate
void actuate(float output)
{
output = constrain(output, 0, 1023);
map(output, 0, 1023, 0, 255);
analogWrite(3, output);
analogWrite(5, output);
}