Skip to content

Commit

Permalink
add pid calculate
Browse files Browse the repository at this point in the history
  • Loading branch information
Watanabe1101 committed Sep 23, 2023
1 parent 00771c4 commit 17624e8
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/PID.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#ifndef PID_H
#define PID_H

#include <Arduino.h>

class PID{
private:
double Kp, Ki, Kd;
double previousRadian = 0;
double error = 0;
double integral = 0;
double targetRadian = 0;
const double dt = 0.001;
const int volt = 5;
double inputVoltage = 0;

public:
PID(double p, double i, double d);
double calculateIPD(double radian);
void setTarget(double target) {targetRadian = target;}
double getVoltage() {return inputVoltage;}
void printParameter();

};

PID::PID(double proportionalGain, double integralGain, double derivativeGain){
Kp = proportionalGain;
Ki = integralGain;
Kd = derivativeGain;
}
double PID::calculateIPD(double radian){
error = targetRadian - radian;
integral += error*dt;
inputVoltage = -Kp*radian + Ki*integral - Kd*(radian-previousRadian)/dt;
previousRadian = radian;
if(inputVoltage > volt) {inputVoltage = volt; integral -= error*dt;}
else if(inputVoltage < -volt) {inputVoltage = -volt; integral -= error*dt;}
return inputVoltage;
}
void PID::printParameter(){
Serial.printf("Kp: %f, Ki: %f, Kd: %f, previousRadian: %f, error: %f, integral %f\n", Kp, Ki, Kd, previousRadian, error, integral);
}
#endif

0 comments on commit 17624e8

Please sign in to comment.