pid update, formatting

This commit is contained in:
Imbus 2025-08-16 17:13:53 +02:00
parent 1c7d6984d0
commit c646e608a0

20
pid.c
View file

@ -1,6 +1,4 @@
#include <math.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#define BUFFER_SIZE 100 #define BUFFER_SIZE 100
@ -31,22 +29,17 @@ float pid_compute(PIDController *pid, float setpoint, float pv) {
float error = setpoint - pv; float error = setpoint - pv;
// Update integral term using circular buffer // Update integral term using circular buffer
pid->integral_sum -= pid->integral_sum -= pid->error_buffer[pid->buffer_index]; // Remove oldest value
pid->error_buffer[pid->buffer_index]; // Remove oldest value pid->error_buffer[pid->buffer_index] = error * pid->dt; // Store new integral term
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 pid->integral_sum += pid->error_buffer[pid->buffer_index]; // Add new value
pid->buffer_index = (pid->buffer_index + 1) % BUFFER_SIZE; // Advance circular buffer index
// Advance circular buffer index
pid->buffer_index = (pid->buffer_index + 1) % BUFFER_SIZE;
// Compute derivative term // Compute derivative term
float derivative = (error - pid->prev_error) / pid->dt; float derivative = (error - pid->prev_error) / pid->dt;
pid->prev_error = error; pid->prev_error = error;
// Compute PID output // Compute PID output
float output = (pid->Kp * error) + (pid->Ki * pid->integral_sum) + float output = (pid->Kp * error) + (pid->Ki * pid->integral_sum) + (pid->Kd * derivative);
(pid->Kd * derivative);
return output; return output;
} }
@ -61,13 +54,10 @@ int main() {
for (int i = 0; i < 50; i++) { for (int i = 0; i < 50; i++) {
float output = pid_compute(&pid, setpoint, pv); float output = pid_compute(&pid, setpoint, pv);
printf("Iteration %d: Setpoint: %.2f, PV: %.2f, Output: %.2f\n", i, printf("Iteration %d: Setpoint: %.2f, PV: %.2f, Output: %.2f\n", i, setpoint, pv, output);
setpoint, pv, output);
// Simulate process variable update // Simulate process variable update
pv += output * 0.1f; pv += output * 0.1f;
if (fabsf(output) < 0.4)
setpoint = 150;
} }
return 0; return 0;