I've made a motor position controller with Arduino. Motor is driven by L289N driver and a potentiometer is connected to its shaft. Another potentiometer is used to control the setpoint. I'm using the PID library to make the controller.
The system sort of works. Positioning works but there is lots of oscillation.
I tried Ziegler-Nichols method to tune the PID as well as trial and error but could not get any acceptable results. I can get rid of oscillations only if I put both Ki and Kd to zero. But oscillation appears as soon as I increase Ki. I tried Ki = 0.001 and there still was oscillation.
I don't know if the problem is in my code, hardware or even a bug in the PID library.
Here's my code:
#include <PID_v1.h>
const int feedbackPin = A0; //Pin of feedback potentiometer
const int torquePin = 9; //PWM pin to motor driver
const int forwardsPin = 8; //Forwards enable pin to motor driver
const int backwardsPin = 7; //Backwards enable pin to motor driver
//PID tunings
const double Kp = 2;
const double Ki = 0.0001;
const double Kd = 0;
double setPoint;
double input;
double error;
double output;
double torque;
//Input
int i1, i2, i3, i4, i5;
PID myPID(&error, &torque, 0, Kp, Ki, Kd, REVERSE);
void setup() {
input = analogRead(feedbackPin);
setPoint = analogRead(A1);
error = abs(setPoint - input);
pinMode(forwardsPin, OUTPUT);
pinMode(backwardsPin, OUTPUT);
pinMode(3, OUTPUT);
myPID.SetSampleTime(10);
myPID.SetMode(AUTOMATIC);
}
void loop() {
//Read setpoint
setPoint = analogRead(A1);
if (setPoint < 25){
setPoint = 25;
}
else if (setPoint > 1000){
setPoint = 1000;
}
//Read input
input = analogRead(feedbackPin);
//Calculate error
error = abs(setPoint - input);
//Compute PID
if(myPID.Compute()){
//Write enable pins
if (setPoint - input > 0){
digitalWrite(forwardsPin, HIGH);
digitalWrite(backwardsPin, LOW);
}
else if (setPoint - input < 0){
digitalWrite(forwardsPin, LOW);
digitalWrite(backwardsPin, HIGH);
}
analogWrite(torquePin, torque);
}
}