AccelStepper作为子类

时间:2018-07-01 03:20:04

标签: c++ class arduino teensy

我很难使步进电机运动。我将其范围缩小到一个代码问题,因为一个easydriver默认代码示例可以使电动机正常运行:

#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(AccelStepper::DRIVER, 3, 2);                                                                           

int pos = 3600;

void setup()
{ 
  stepper.setMaxSpeed(3000);
  stepper.setAcceleration(1000);
}

void loop()
{
  if (stepper.distanceToGo() == 0)
  {
    delay(500);
    pos = -pos;
    stepper.moveTo(pos);\
  }
  stepper.run();
}

但是,如果我使用此代码,它将失败。我认为这与我尝试将AccelStepper用作Motor的子类有关。奇怪的是,下面的代码可以编译并毫无错误地上传到微控制器,但电动机不会转动。我也得到串行输出。

#include <Arduino.h>
#include <AccelStepper.h>

class Motor{
    protected:
        AccelStepper accelStepperObject;
    public:
        Motor(int, int, int, int, int);
        void travelToAngle(int angleTarget);
};

Motor::Motor(
        int maxSpeed,
        int sleepPin,
        int enablePin,
        int stepPin,
        int dirPin
        )
    : accelStepperObject(AccelStepper::DRIVER, stepPin, dirPin)
{
    //set mcu pins
    pinMode(sleepPin, OUTPUT);
    digitalWrite(sleepPin, LOW);
    pinMode(enablePin, OUTPUT);
    digitalWrite(enablePin, HIGH);
    //configure accelstepper object
    this->accelStepperObject.setMaxSpeed( maxSpeed );
    this->accelStepperObject.setAcceleration( 1000 );
    Serial.println("f");
}

void Motor::travelToAngle(int angleTarget){
    //code that would usually convert angle to steps omitted here for simplicity
    Serial.println("a");
    this->accelStepperObject.runToNewPosition(angleTarget);//something messes up here
    Serial.println("b");                                                                                                                                                                                                                                       
};

void setup() {
    Serial.begin(9600);
    delay(4000);//give UART time to sync up
    Motor theta(
            3000,//maxSpeed
            19,//sleepPin
            20,//enablePin
            3,//stepPin
            2//dirPin
            );
    Serial.println("c");
    theta.travelToAngle(100);
    Serial.println("d");
    theta.travelToAngle(0);
    Serial.println("e");
}

void loop() {
}

标准输出:

f
c
a
b
d
a
b
e

0 个答案:

没有答案