hello, this is my first post here and I hope someone can help me. I am doing a project where i am supposed to create PID controller of a dc motor using rotary encoder. I got the part where I am supposed to calculate rmp but I am straggling with PID. In addition, I am trying to figure it out how to put desirable speed through serial port and still get the reading from rpm and PID reading I am new to this and still learning thanks so much for help. this is the code that I am having right now
#include <AFMotor.h>
AF_DCMotor motor(2, MOTOR12_2KHZ);
volatile int rpmcount = 0;
int rpm = 0;
unsigned long lastmillis = 0;
int pid_speed=0;
float kp=2.25;
float ki=.01;
float kd=0.005;
int prev_error=0;
double pwm_sig=0;
int error=0;
float desired_rpm=80;
int diff = 0;
void setup(){
Serial.begin(9600);
attachInterrupt(0, rpm_fan, FALLING);//interrupt cero (0) is on pin two(2).
motor.run(FORWARD);
}
void loop(){
//if (Serial.available()){
//int speed = Serial.parseInt();
// if (speed >= 0 && speed <= 255) {
//motor.setSpeed(speed);
// motor.run(FORWARD);
// Serial.print("target=\t");
// Serial.print(speed);
// }
// }
if (millis() - lastmillis == 1000){ //upade one sec
detachInterrupt(0); //Disable interrupt
rpm = (rpmcount * 3)/6; // Convert to RPM
Serial.print("RPM =\t");
Serial.print(rpm); // print the rpm value.
rpmcount = 0; // Restart RPM counter
lastmillis = millis(); // Uptade lasmillis
attachInterrupt(0, rpm_fan, FALLING); //enable interrupt
}
error=desired_rpm-rpm;
diff += error;
pid_speed = kp*error; + ki*diff;
pid_speed=(int)pid_speed;
Serial.print(pid_speed);
Serial.print(" ");
if (pid_speed> 0){
if (pid_speed<255)
motor.setSpeed(255);
else
motor.setSpeed(pid_speed);
}
if(pid_speed<0){
if(pid_speed<-255)
{
motor.setSpeed(0);
}
else
{
pid_speed=abs(pid_speed);
motor.setSpeed(255-pid_speed);
}
}
Serial.print (" ");
Serial.println(rpm);
}
void rpm_fan(){
rpmcount++;
}