Hi, I tried to control a DC-motor using Arduino.
I want to achieve the torque or current control for rotational angle of the DC-motor.
I achieved to obtain rotational angle of the DC-motor using a rotary encoder.
Then, I achieved to freely rotate the motor using motor driver.
However, I don't know a method that the rotational angle of the motor is converged to desired angle by PID control on Arduino.
Can I solve this problem using PID library (PID_v1.h) ?
Since I read the example of this library, I didn't understand that the PID library solves the my problem.
Please give me the advice for solution of this problem.
I show an unfinished code for PID control of the DC-motor.
Best regard.
#define inA_encoder 2 // pinA
#define inB_encoder 3 // pinB
#define in_pwm 5 //for pwm
#define inA_motor 8 // for rotate direction
#define inB_motor 9 // for rotate direction
const float ppr = 500; //pulse per resolution of encoder
const int step_size = 50;
const float kp = 10; //P-gain
const float kd = 0.5; //D-gain
const float th1d = 0.90 [rad] //desired value
volatile long count_encoder = 0; //count of encoder
long p_time = 0;
long c_time = 0;
void setup()
{
Serial.begin(9600);
pinMode(inA_encoder_1, INPUT_PULLUP);
pinMode(inB_encoder_1, INPUT_PULLUP);
pinMode(in_pwm, OUTPUT);
pinMode(inA_motor, OUTPUT);
pinMode(inB_motor, OUTPUT);
attachInterrupt(digitalPinToInterrupt(inA_encoder), Update_encoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(inB_encoder), Update_encoder, CHANGE);
p_time = millis();
}
void loop()
{
c_time = millis();
float th1 = count_encoder * 2 * 3.14 / ppr;
float dth1 = (th1 - p_th1) / (c_time-p_time);
p_time = c_time;
p_th1 = th1;
//--- PD control --------------------
tau = -kp1 * (th1 - th1d) - kd1 * dth1;
//--- Calculate pwm output -------------
int pwm = ; //pwm output
//--- Rotate direction ----------
if (tau > 0){
//--- CW -------------------------
digitalWrite(inA_motor, LOW);
digitalWrite(inB_motor, HIGH);
else {
//--- CCW -------------------------
digitalWrite(inA_motor, HIGH);
digitalWrite(inB_motor, LOW);
}
analogWrite(in_pwm, pwm);
}
}