1

I am able to move motors using AfMotor Shield Library. ( https://github.com/adafruit/Adafruit-Motor-Shield-library )

Like :

AF_DCMotor insertionMotor(1);
AF_DCMotor pumpMotor(2);

void setup()
{
  insertionMotor.setSpeed(255);
  pumpMotor.setSpeed(255);
  insertionMotor.run(RELEASE);
  pumpMotor.run(RELEASE);
  insertionMotor.run(FORWARD);
  pumpMotor.run(FORWARD);
}

But if I want to write it like this, only the motor with the template expansion that I called last works.

enum class direction {
  FRW = 0x01,
  BCKW,
};

template<int n, direction type>
class Motor : public AF_DCMotor {

public:

  Motor() : AF_DCMotor(n) {
    setSpeed(255);
    run(RELEASE);
    run(type);
  }
};
Motor<1, direction::FRW> fanMotor;
Motor<2, direction::FRW> pumpMotor;

Only the pumpmotor is running. Or if I call the fanMotor after the pumpMotor, it still works.If I remove pumpmotor and leave only fanMotor, the fanMotor also works. Is there something I overlooked?

0

1 Answer 1

2

Your code gives me a compiler error: in

run(type);

the run() method expects a uint8_t, but it is given a direction. Adding an explicit cast to uint8_t makes it compile.

Now, as a general rule, I would advice you to never touch the hardware in a constructor. The problem is, if you create a global object (like you are doing here), the constructor gets called before main(), thus before the Arduino core has had a chance to initialize the hardware. If your constructor touches any hardware register, this may conflict with the initialization the core is going to perform right at the start of main().

The usual idiom for doing any hardware initialization is to define in your object a method called begin(), and call it from setup():

template<int n, direction type>
class Motor : public AF_DCMotor {
public:
  Motor() : AF_DCMotor(n) {}

  void begin() {
    setSpeed(255);
    run(RELEASE);
    run((uint8_t) type);
  }
};
1
  • Yes you should do casting. (static_cast maybe more suitable). But it is not related about my problem. Also with these lines, the constructor gets called before main() AF_DCMotor insertionMotor(1); AF_DCMotor pumpMotor(2); Aug 14, 2022 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.