Professional Documents
Culture Documents
Code Backup + Autotune
Code Backup + Autotune
#include <PID_AutoTune_v0.h>//-----------------------------------------------------
double kpmodel=1.5, taup=100, theta[50];//-------------------------------------
double outputStart=5;//------------------------------------
byte ATuneModeRemember=2;////-------------------------------------
double aTuneStep=50, aTuneNoise=1,
aTuneStartValue=100;//-------------------------------------
unsigned int aTuneLookBack=20;//-------------------------------------
boolean tuning = true;//------------------------------------
unsigned long modelTime, serialTime;//------------------------------
//#define PIN_OUTPUT 3
ESP32Encoder encoder; //encoder created by the name "encoder"
if(useSimulation)
{
for(byte i=0;i<50;i++)
{
theta[i]=outputStart;
}
modelTime = 0;
}
if(tuning)
{
tuning=false;
changeAutoTune();
tuning=true;
}
serialTime = 0;
}
void loop(){
Input = encoder.getCount(); // update the input value with new encoder value
myPID.Compute(); // compute PID
//---------------------------------------------------------------------
unsigned long now = millis();
if(!useSimulation)
{ //pull the input in from the real world
Input = encoder.getCount();
}
if(tuning)
{
byte val = (aTune.Runtime());
if (val!=0)
{
tuning = false;
}
if(!tuning)
{ //we're done, set the tuning parameters
Kp = aTune.GetKp();
Ki = aTune.GetKi();
Kd = aTune.GetKd();
myPID.SetTunings(Kp,Ki,Kd);
AutoTuneHelper(false);
}
}
else myPID.Compute();
if(useSimulation)
{
theta[30]=Output;
if(now>=modelTime)
{
modelTime +=100;
DoModel();
}
}
else
{
analogWrite(2,Output);
}
//++++++++++++++++++++++++++++++++++
+====================================================
void changeAutoTune()
{
if(!tuning)
{
//Set the output to the desired starting frequency.
Output=aTuneStartValue;
aTune.SetNoiseBand(aTuneNoise);
aTune.SetOutputStep(aTuneStep);
aTune.SetLookbackSec((int)aTuneLookBack);
AutoTuneHelper(true);
tuning = true;
}
else
{ //cancel autotune
aTune.Cancel();
tuning = false;
AutoTuneHelper(false);
}
}
void SerialSend()
{
Serial.print("setpoint: ");Serial.print(Setpoint); Serial.print(" ");
Serial.print("input: ");Serial.print(Input); Serial.print(" ");
Serial.print("output: ");Serial.print(Output); Serial.print(" ");
if(tuning){
Serial.println("tuning mode");
} else {
Serial.print("kp: ");Serial.print(myPID.GetKp());Serial.print(" ");
Serial.print("ki: ");Serial.print(myPID.GetKi());Serial.print(" ");
Serial.print("kd: ");Serial.print(myPID.GetKd());Serial.println();
}
}
void SerialReceive()
{
if(Serial.available())
{
char b = Serial.read();
Serial.flush();
if((b=='1' && !tuning) || (b!='1' && tuning))changeAutoTune();
}
}
void DoModel()
{
//cycle the dead time
for(byte i=0;i<49;i++)
{
theta[i] = theta[i+1];
}
//compute the input
Input = (kpmodel / taup) *(theta[0]-outputStart) + Input*(1-1/taup) +
((float)random(-10,10))/100;