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);