0

I am working on creating a PID controller for controlling a motor. I investigated using the PID library but i believe it doesn't suit my needs, as i need to control a motor in two directions using the same controller.

I currently have the PI part working, but I am struggling with the D part. I am unable to store the current error to last error, which can then be used to calculate the next D value. Instead my d value appears to reflect the error, rather than the change in the current error compared to last error. My code is shown below, any advice would be appreciated.

**note, I know that typically delta_T is included in the Integral and Derivative portion of the controller, however I prefer to incorporate it into the control constants Ki and Kd to avoid coding complications.

  Distance = analogRead (irSense); //read the sensor, assigns value to Distance
//Serial.println(Distance) ;
double lastError; 
int control;         //initialize control variable , set up PID parameters
int setpoint = 350;  //Neutral position, zero point, desired input
int error = Distance - setpoint;  //error function
double d = (error - lastError);  //derivative function

double kp = 0.9;         //Proportional constant
double ki = 0.000001;       //Intergral constant
double kd = .0001;          //Derivitve constant

i += error; //intergral Set
control = error * kp + i * ki + d * kd; //PID control funtion

lastError = error;

Serial.println (d);
Jonas
  • 121,568
  • 97
  • 310
  • 388

1 Answers1

0

It sounds as if lastError is always zero. Maybe print it as debugging info at the start of your code.

If your posted code is inside of a function, you might need the static keyword:

static double lastError;

In order to retain the value from call to call. Otherwise, it might be reinitialized to zero and give you the result you see. If lastError is global,

For Derivative(error), some use derivative(measured_value) to avoid sensitivity to changes to setpoint.

I would change your code to:

static double lastDistance;
...
double d = Distance-lastDistance
...
Dave X
  • 4,831
  • 4
  • 31
  • 42