Skip to content

Instantly share code, notes, and snippets.

@syfluqs
Last active December 19, 2023 21:48
Show Gist options
  • Save syfluqs/bb614bbd65c5b468a9db107dbaea12ea to your computer and use it in GitHub Desktop.
Save syfluqs/bb614bbd65c5b468a9db107dbaea12ea to your computer and use it in GitHub Desktop.
A very basic PID controller in C
/*
* pid_controller.c
*
* Created on: Apr 24, 2016
* Author: subham roy
*/
#include "pid_controller.h"
double pid(PID_vars *vars, double current_err) {
/* current_error = setpoint - current_process_variable */
vars->_integral_sum += current_err*(vars->_dt);
double output = (vars->Kp)*current_err \
+ (vars->Ki)*(vars->_integral_sum) \
+ (vars->Kd)*((current_err-(vars->_prev_err))\
/(vars->_dt));
vars->_prev_err = current_err;
/* limit output within output_min and output_max */
if (output>(vars->output_max))
output = vars->output_max;
else if (output<(vars->output_min))
output = vars->output_min;
return output;
}
/*
* pid_controller.h
*
* Created on: Apr 24, 2016
* Author: subham roy
*/
#ifndef __PID_CONTROLLER_H
#define __PID_CONTROLLER_H
typedef struct {
/* PID controller parameters */
double Kp;
double Ki;
double Kd;
/* max output limits for the PID controller */
double output_max;
double output_min;
/* below are session variables for the PID controller */
double _integral_sum;
double _prev_err;
double _dt;
} PID_vars;
#define PID_VARS_INIT(x) PID_vars x = {.Kp=0.0,.Ki=0.0,.Kd=0.0,.output_max=100.0, \
.output_min=0.0,._integral_sum=0.0,._prev_err=0.0,._dt=1.0}
/* Function Prototypes */
double pid(PID_vars *vars, double current_err);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment