我试图控制电机扭矩。我试图通过对电机电流实施PID控制来实现,从而实现PWM。更高的PWM意味着更高的扭矩 我是arduino-uno的新手,因此需要编码方面的帮助。我已经编写了相同的代码,但有点不确定它的正确性。我仍然不确定' Integral'的价值。但是要使用的变量。 任何帮助深表感谢 提前致谢
#include "RunningAverage.h"
int m1 = 13;
int m2 = 12;
int me = 9;
int t = millis()+5000;
RunningAverage myRA(80);
int stat=0;
int pwmn=100;
int counter=0;
int kP;
int kI=0;
int kD=0;
int SetPt;
int Last;
int Actual;
int Error;
int Integral;
float P;
float I;
float D;
int Drive;
int ScaleFactor;
void motorRight(){
digitalWrite(m1,HIGH);
digitalWrite(m2, LOW);
}
void motorLeft(){
digitalWrite(m2,HIGH);
digitalWrite(m1, LOW);
}
void motorOff(){
digitalWrite(m2, LOW);
digitalWrite(m1, LOW);
}
void motorBrake(){
digitalWrite(m2, HIGH);
digitalWrite(m1, HIGH);
delay(10);
motorOff();
}
void setup() {
// put your setup code here, to run once:
pinMode(m1,OUTPUT);
pinMode(m2,OUTPUT);
pinMode(me,OUTPUT);
analogWrite(me,pwmn);
Serial.begin(115200);
motorRight();
}
void loop() {
// put your main code here, to run repeatedly:
myRA.addValue(analogRead(A1));
Serial.print(myRA.getAverage());
Serial.println(",500,600");
Actual = myRA.getAverage();
Error = SetPt - Actual;
P = Error*kP; // calc proportional term
I = Integral*kI; // integral term
D = (Last-Actual)*kD; // derivative term
Drive = P + I + D; // Total drive = P+I+D
Drive = Drive*ScaleFactor; // scale Drive to be in the range 0-255
//Serial.println(pwmn);
if(counter>10){
if(pwmn<250){
pwmn++;
}
counter=0;
}
counter++;
if (abs(Drive)>255) {
Drive=255;
}
analogWrite (me,Drive); // send PWM command to motor board
Last = Actual; // save current value for next time
// analogWrite(me,pwmn);
delay(50);
}'
答案 0 :(得分:-1)
你是对的,积分计算是错误的。积分(来自整合)意味着加起来。你想要的是
I = I + kI*Error;
您还应该将积分项(I)限制为某个最大值和最小值,以避免&#34;结束&#34;错误。这种情况发生在伺服无法达到目标时,因为I项是它可能失控的误差之和。