0

Multiple motors on motor shield
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Multiple motors on motor shield

by davidc1 on Sun Jan 13, 2019 12:39 am

I am using a motor shield V2 to control four motors which all do similar things. The standard declaration for a motor is
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

So the variable myMotor is a pointer type - to something.

Can someone please tell me how to create an array of these pointers, so that I can refer to any individual motor by an index, rather than having to write separate code for each motor.

David
davidc1
 
Posts: 19
Joined: Sat Aug 25, 2012 7:54 pm

Re: Multiple motors on motor shield

by adafruit_support_bill on Sun Jan 13, 2019 8:46 am

You can just reference them from the array maintained inside the shield driver

Code: Select all | TOGGLE FULL SIZE
for (int i = 1; i <= 4; i++)
{
    AFMS.getMotor(i)->run(FORWARD);
}


Or, if you want to create an array of your own, you can do it something like:

Code: Select all | TOGGLE FULL SIZE
Adafruit_DCMotor* Motors[4] = {AFMS.getMotor(1), AFMS.getMotor(2), AFMS.getMotor(3), AFMS.getMotor(4)};

adafruit_support_bill
 
Posts: 72736
Joined: Sat Feb 07, 2009 10:11 am

Re: Multiple motors on motor shield

by davidc1 on Sun Jan 13, 2019 6:03 pm

Bill,

Thank you for your reply. I used your second option and it works well. I can refer to one of the motors like this:

Code: Select all | TOGGLE FULL SIZE
Motors[i]->setSpeed(n);



David
davidc1
 
Posts: 19
Joined: Sat Aug 25, 2012 7:54 pm

Please be positive and constructive with your questions and comments.