Arduino直流电机代码不计算编码器刻度

时间:2018-10-10 03:24:18

标签: arduino arduino-uno

我有一些关于Arduino运行的2个直流电机的代码,这些代码使用编码器测量它们的距离。我试图编写一些控制代码,以使一个较快的轮子在其他轮子跟不上时却减速,但此刻轮子永远运转。我是编程新手,所以看不到为什么总刻度不会累积在这里。谁能帮忙,谢谢!

const int pwm1 = 9;  //initializing pin as pwm
const int in_1 = 8;
const int in_2 = 12;
const int pwm2 = 10;  //initializing pin as pwm
const int in_3 = 11;
const int in_4 = 13;
const int e1 = 2;
const int e2 = 3;
volatile int encoder1Value = 0;
volatile int encoder2Value = 0;

void encoder1() {
  encoder1Value++;
}
void encoder2() {
  encoder2Value++;
}

void setup()
{
pinMode(pwm1,OUTPUT) ;   //we have to set PWM pin as output
pinMode(in_1,OUTPUT) ;  //Logic pins are also set as output
pinMode(in_2,OUTPUT) ;
pinMode(pwm2,OUTPUT) ;   //we have to set PWM pin as output
pinMode(in_3,OUTPUT) ;  //Logic pins are also set as output
pinMode(in_4,OUTPUT) ;
pinMode(e1,INPUT) ;
pinMode(e2,INPUT) ; 
attachInterrupt(digitalPinToInterrupt(e1), encoder1, FALLING);
attachInterrupt(digitalPinToInterrupt(e2), encoder2, FALLING);
}

#define abs(X) ((X < 0) ? -1 * X : X)

void driveStraightDistance(int distance, int masterPower)
{
  //Relationship between the amount of ticks per cm 
  int tickGoal = distance;

  //This will count up the total encoder ticks despite the fact that the encoders are constantly reset.
  int totalTicks = 0;

  //Initialise slavePower as masterPower - 5 so we don't get huge error for the first few iterations. The
  //-5 value is based off a rough guess of how much the motors are different, which prevents the robot from
  //veering off course at the start of the function.
  int slavePower = masterPower - 5; 
  int error = 0;
  int kp = 5;

  //Monitor 'totalTicks', instead of the values of the encoders which are constantly reset.
  while(abs(totalTicks) < tickGoal)
  {
    //Proportional algorithm to keep the robot going straight.
    digitalWrite(in_1,LOW) ;
    digitalWrite(in_2,HIGH) ;
    analogWrite(pwm1,masterPower);

    digitalWrite(in_3,LOW) ;
    digitalWrite(in_4,HIGH) ;
    analogWrite(pwm2,slavePower) ;

    error = encoder1Value - encoder2Value;

    slavePower += error / kp;

//Add this iteration's encoder values to totalTicks.
    totalTicks+= encoder1Value;

    encoder1Value = 0;
    encoder2Value = 0;

    delay(100);


  }

  // Stop the loop once the encoders have counted up the correct number of encoder ticks.
  digitalWrite(in_1,HIGH) ;
  digitalWrite(in_2,HIGH) ;
  digitalWrite(in_3,HIGH) ;
  digitalWrite(in_4,HIGH) ; 

}

void loop()
{
  //Distances specified in centimetres

  driveStraightDistance(100,255); 

}

0 个答案:

没有答案