Hello!
I am trying to make a "steer-by-wire" system using 2 potentiometers and a DC-motor. Im having trouble getting it to work after implementing PID (or PI). (It worked pretty good with only the "P" part).
It works kinda okay sometimes for a split secound or two, and then it just becomes "unresponsive". Do you know what could be wrong?
Thanks in advance!
Here is my code:
int enablePin = 9;
int motorLeft = 5;
int motorRight = 6;
int sensorPosition; // Input position of potentiometer
int motorPosition; // Position of potentiometer connected to motor
int motorValue; // Output value that the PID calculates.
int timeNow, timeThen, dT;
float P_error, I_error, D_error, lastError;
double Pexp = 3;
double Iexp = 0.01;
double Dexp = 0;
void setup() {
analogWrite(enablePin, 255);
Serial.begin(9600);
}
void loop() {
sensorPosition = analogRead(A0);
motorPosition = analogRead(A1);
P_error = sensorPosition - motorPosition;
motorValue = calcPID(P_error);
if (motorValue < 0) {
analogWrite(motorLeft, constrain((-motorValue), 0, 255));
} else if (motorValue > 0) {
analogWrite(motorRight, constrain(motorValue, 0, 255));
}
delay(100);
}
int calcPID(int P_error) {
timeNow = millis();
dT = (timeNow - timeThen);
I_error += P_error * dT;
//D_error = (P_error - lastError)/dT;
int motorValue = (Pexp * P_error) + (Iexp * I_error) + (Dexp * D_error);
lastError = P_error;
timeThen = timeNow;
return motorValue;
}
