Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
PID/pid.cpp
- Committer:
- nolan21
- Date:
- 2016-11-18
- Revision:
- 23:5238b046119b
- Parent:
- 22:c18f04d1dc49
File content as of revision 23:5238b046119b:
#ifndef _PID_SOURCE_
#define _PID_SOURCE_
#include <iostream>
#include <cmath>
#include "pid.h"
using namespace std;
PID::PID( float dt, float max, float min, float kp, float ki, float kd )
{
dt_ = dt;
max_ = max;
min_ = min;
kp_ = kp;
ki_ = ki;
kd_ = kd;
pre_error_ = 0;
integral_ = 0;
}
float PID::calculate(float setpoint, float pv)
{
// Calculate time changed since last PID calculation
// dt_ = current_time - dt_;
// Calculate error
float error = setpoint - pv;
// Proportional term
float Pout = kp_ * error;
// Integral term
integral_ += error * dt_;
float Iout = ki_ * integral_;
// Derivative term
float derivative = (error - pre_error_) / dt_;
float Dout = kd_ * derivative;
// Calculate total output
float output = Pout + Iout + Dout;
// Restrict to max/min
if( output > max_ ){
output = max_;
}
else if( output < min_ ){
output = min_;
}
// Save error to previous error
pre_error_ = error;
return output;
}
void PID::testError(float setpoint, float pv){
float error = setpoint - pv;
printf("Error: %f\n", error);
printf("Change in Time: %f\n", dt_);
}
PID::~PID() {}
/**
* Implementation
*/
/*
PIDImpl::PIDImpl( float dt, float max, float min, float Kp, float Kd, float Ki ) :
_dt(dt),
_max(max),
_min(min),
_Kp(Kp),
_Kd(Kd),
_Ki(Ki),
_pre_error(0),
_integral(0)
{
}
float PIDImpl::calculate( float setpoint, float pv )
{
// Calculate error
float error = setpoint - pv;
// Proportional term
float Pout = _Kp * error;
// Integral term
_integral += error * _dt;
float Iout = _Ki * _integral;
// Derivative term
float derivative = (error - _pre_error) / _dt;
float Dout = _Kd * derivative;
// Calculate total output
float output = Pout + Iout + Dout;
// Restrict to max/min
if( output > _max )
output = _max;
else if( output < _min )
output = _min;
// Save error to previous error
_pre_error = error;
return output;
}
PIDImpl::~PIDImpl()
{
}
*/
#endif