Simply, the project was to convert a DC motor into a Servo Motor.
The ideas is to take the feedback from the motor through a potentiometer, then apply PID algorithm.
An external circuit for calibrating the PID parameters was planned, but it failed.
So, everything in the algorithms and calibration was done through Serial Commands with the code.
Unfortunately, I don't have the video for the trials.. but it was very close to this one:
The Arduino code aimed to calculate the factors for Kp, Ki and Kd to map the right value to the power the DC motor and stop it at the right angle.
The mapping and calculations were done on the setup I built.
I would add the code later into a git repo.
I would add comments. too 👀
The code:
=============================================const int in1 = 9;const int in2 = 8;const int enA = 11;float out;float derivative = 0;float lastError = 0;float integral = 0;int maxm = 190;int targetR = 90;void setup(){pinMode(in1,OUTPUT);pinMode(in2,OUTPUT);pinMode(enA,OUTPUT);Serial.begin(9600);}void loop(){while(Serial.available() > 0){targetR = Serial.parseInt();}float Kp = 3;float Ki = 0.01;float Kd = 10;int target = map(targetR, 0, 180, 200, 800);int currentR = analogRead(A0);int error = target - currentR; // 0:1024if(error >= 0){out = map(error, 200, 800, 0, maxm);integral += error;derivative = error - lastError;out = (error * Kp) + (derivative * Kd) + (integral * Ki);if(out > maxm){out = maxm;}if(out < 50){out = 0;}digitalWrite(in1,HIGH);digitalWrite(in2,LOW);analogWrite(enA,out);lastError = error;}if(error < 0){out = map(error, 200, 800, 0, maxm);derivative = error - lastError;out = (error * (-Kp)) + (derivative * (-Kd)) + (integral * (-Ki));;if(out > maxm){out = maxm;}if(out < 50){out = 0;}digitalWrite(in1,LOW);digitalWrite(in2,HIGH);analogWrite(enA,out);lastError = error;}Serial.print("Error = ");Serial.print(error);Serial.print(" Out = ");Serial.println(out);}=============================================
Enjoy :)