i need help with how to tune the parameters of PID . And can anyone verify if my code is correct. im trying to do the position control of a dc motor with pot acting as a feedback using arduino and PID.
thanks for your help in advance.
//PID constants
double kp = 2;
double ki =5;
double kd = 1;
unsigned long currentTime, previousTime;
double elapsedTime;
double error;
double lastError;
double input, output, setPoint;
double cumError, rateError;
int enB = 5;
int pin1 = 7;
int pin2 = 6;
int pot=A0;
int CurrentValue;
int DesiredValue;
void setup()
{
pinMode(enB, OUTPUT);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
input = analogRead(A0);
output = computePID(input);
delay(100);
analogWrite(enB, output);
CurrentValue = analogRead(A0);
DesiredValue=600;
setPoint=DesiredValue;
if(DesiredValue>CurrentValue)//left
{
digitalWrite(pin1, LOW);
digitalWrite(pin2, HIGH);
analogWrite(enB,255);
}
if (DesiredValue< CurrentValue) //right
{
digitalWrite(pin1,HIGH);
digitalWrite(pin2, LOW);
analogWrite(enB,255);
}
if(abs(DesiredValue-CurrentValue)<20)
{
CurrentValue = analogRead(A0);
analogWrite(enB,255);
digitalWrite(pin1, LOW);
digitalWrite(pin2, LOW);
}
}
double computePID(double inp){
currentTime = millis(); //get current time
Serial.print(millis());
Serial.println(currentTime);
elapsedTime = (double)(currentTime - previousTime);
error = setPoint - inp;
cumError += error * elapsedTime;
rateError = (error - lastError)/elapsedTime;
double out = kp*error + ki*cumError + kd*rateError; //PID output
Serial.print(out);
lastError = error;
previousTime = currentTime;
return out;
}

