pid update, formatting
This commit is contained in:
parent
1c7d6984d0
commit
c646e608a0
1 changed files with 6 additions and 16 deletions
22
pid.c
22
pid.c
|
|
@ -1,6 +1,4 @@
|
|||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BUFFER_SIZE 100
|
||||
|
|
@ -8,7 +6,7 @@
|
|||
typedef struct {
|
||||
float Kp, Ki, Kd; // PID gains
|
||||
float error_buffer[BUFFER_SIZE]; // Circular buffer for integral calculation
|
||||
int buffer_index; // Current index in the buffer
|
||||
int buffer_index; // Current index in the buffer
|
||||
float integral_sum; // Running sum of integral terms
|
||||
float prev_error; // Previous error for derivative term
|
||||
float dt; // Sample time (seconds)
|
||||
|
|
@ -31,22 +29,17 @@ float pid_compute(PIDController *pid, float setpoint, float pv) {
|
|||
float error = setpoint - pv;
|
||||
|
||||
// Update integral term using circular buffer
|
||||
pid->integral_sum -=
|
||||
pid->error_buffer[pid->buffer_index]; // Remove oldest value
|
||||
pid->error_buffer[pid->buffer_index] =
|
||||
error * pid->dt; // Store new integral term
|
||||
pid->integral_sum -= pid->error_buffer[pid->buffer_index]; // Remove oldest value
|
||||
pid->error_buffer[pid->buffer_index] = error * pid->dt; // Store new integral term
|
||||
pid->integral_sum += pid->error_buffer[pid->buffer_index]; // Add new value
|
||||
|
||||
// Advance circular buffer index
|
||||
pid->buffer_index = (pid->buffer_index + 1) % BUFFER_SIZE;
|
||||
pid->buffer_index = (pid->buffer_index + 1) % BUFFER_SIZE; // Advance circular buffer index
|
||||
|
||||
// Compute derivative term
|
||||
float derivative = (error - pid->prev_error) / pid->dt;
|
||||
pid->prev_error = error;
|
||||
|
||||
// Compute PID output
|
||||
float output = (pid->Kp * error) + (pid->Ki * pid->integral_sum) +
|
||||
(pid->Kd * derivative);
|
||||
float output = (pid->Kp * error) + (pid->Ki * pid->integral_sum) + (pid->Kd * derivative);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
|
@ -61,13 +54,10 @@ int main() {
|
|||
|
||||
for (int i = 0; i < 50; i++) {
|
||||
float output = pid_compute(&pid, setpoint, pv);
|
||||
printf("Iteration %d: Setpoint: %.2f, PV: %.2f, Output: %.2f\n", i,
|
||||
setpoint, pv, output);
|
||||
printf("Iteration %d: Setpoint: %.2f, PV: %.2f, Output: %.2f\n", i, setpoint, pv, output);
|
||||
|
||||
// Simulate process variable update
|
||||
pv += output * 0.1f;
|
||||
if (fabsf(output) < 0.4)
|
||||
setpoint = 150;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue