我在我的Arduino项目中使用AccelStepper库,该库有一个构造函数,函数作为参数:
AccelStepper(void (*forward)(), void (*backward)());
在主草图中,这是使用的代码:
void forwardstep() {
AFstepper->onestep(FORWARD, stepType); //some code to move the motor
}
void backwardstep() {
AFstepper->onestep(BACKWARD, stepType); //some code to move the motor
}
AccelStepper stepper(forwardstep, backwardstep);
只要此代码在主草图中,一切都运行良好。
我创建了一个具有AccelStepper对象的类,并且forwardstep()和backwardstep()函数作为成员,但是我无法将这些函数传递给AccelStepper的构造函数: .h文件:
#define IICADDRESS 0x60
class FilterWheel : public Device
{
public:
FilterWheel();
void forwardstep();
void backwardstep();
void (*fwdstp)(); //function pointer
void (*bckwdstp)(); //function pointer
private:
//Adafruit Motor Shield object
Adafruit_MotorShield AFMS;
//Adafruit Stepper Motor object
Adafruit_StepperMotor *AFstepper;
//AccelStepper wrapper
AccelStepper stepper;
};
.cpp文件:
#include "FilterWheel.h"
//constructor
FilterWheel::FilterWheel()
{
fwdstp = &FilterWheel::forwardstep;
bckwdstp = &FilterWheel::backwardstep;
Adafruit_MotorShield AFMS (IICADDRESS);
Adafruit_StepperMotor *AFstepper = AFMS.getStepper(200, 1); //M1 M2
//AccelStepper stepper(forwardstep, backwardstep); //doesn't work
AccelStepper stepper(fwdstp, bckwdstp); //works only if fwdstp = &FilterWheel::forwardstep; and bckwdstp = &FilterWheel::backwardstep; are commented out
}
//go 1 step forward
void FilterWheel::forwardstep() {
AFstepper->onestep(FORWARD, stepType);
}
//go 1 step backward
void FilterWheel::backwardstep() {
AFstepper->onestep(BACKWARD, stepType);
}
当我尝试直接传递函数时,
AccelStepper stepper(forwardstep, backwardstep);
编译器显示以下错误:
FilterWheel.cpp:34: error: no matching function for call to 'AccelStepper::AccelStepper(<unresolved overloaded function type>, <unresolved overloaded function type>)'
AccelStepper.h:AccelStepper(void (*)(), void (*)())
AccelStepper.h:AccelStepper(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, bool)
AccelStepper.h:AccelStepper(const AccelStepper&)
Error compiling
当我将函数附加到函数指针时,
fwdstp = &FilterWheel::forwardstep;
bckwdstp = &FilterWheel::backwardstep;
AccelStepper stepper(fwdstp, bckwdstp);
编译器显示以下错误:
FilterWheel.cpp:In constructor 'FilterWheel::FilterWheel()'
FilterWheel.cpp:22: error: cannot convert 'void (FilterWheel::*)()' to 'void (*)()' in assignment
FilterWheel.cpp:23: error: cannot convert 'void (FilterWheel::*)()' to 'void (*)()' in assignment
Error compiling
我该如何解决这个问题?
答案 0 :(得分:0)
forwardstep()
和backwardstep()
是非静态成员函数,因此fwdstp = &FilterWheel::forwardstep;
是指向成员函数的指针,它不能转换为指向函数的指针,因为它需要一个要调用它的对象。
您必须使您的功能保持静态或独立。