My PID Code in C on PIC18F - Help
@mattmcc-prCH6d
•
Oct 22, 2024
Oct 22, 2024
1.3K
I'm making a PID controller using a PIC18F452 in C.
signed int pid_error;
short ProportionalGain;
short IntegralGain;
short DerivitiveGain;
double AccumError;
short LastError;
short TotalGain;
signed int pid_output;
unsigned char reverse;
unsigned int Kp;
unsigned int Ki;
unsigned int Kd;
Kp = 2;
Ki = 0;
Kd = 0;
reverse = 0;
setpoint = 50;
T0CONbits.TMR0ON = 0; //Turn off tmr0
LastError = pid_error;
if (reverse = 0)
{
pid_error = ADRESH - setpoint; //Forward
}
else
{
pid_error = setpoint - ADRESH; //Reverse
}
AccumError = AccumError + pid_error;
ProportionalGain = pid_error*Kp;
IntegralGain = Kp * AccumError / Ki;
DerivitiveGain = Kp * Kd * (pid_error - LastError);
TotalGain = ProportionalGain + IntegralGain + DerivitiveGain;
pid_output = setpoint + TotalGain;My input is coming from ADRESH, 8-bit value from 1 - 5V, and my output is going to an external 8-bit I2C DAC. How can I convert "pid_error" to an 8-bit number. Also if anyone has some general comments about my code, I'll take suggestions.
Note: this is my first version, I plan on adding integral limits, derivitive spike prevention, auto/manual control, ect.