Reputation: 105
I'm using the Adafruit Motor Shield library v1 and making something with 4 motors in it and want to create a void function to call those motors to move
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
void motor1run() {
motor1.run(FORWARD);
}
void motor2run() {
motor2.run(FORWARD);
}
Instead of using different functions like I did above, Is there any way I could make the function take an int parameter x and using that run the xth motor?
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
void motorrun(x) {
//runs the xth motor
}
Upvotes: 2
Views: 173
Reputation: 5748
You can also create an array for your objects:
// create AF_DCMotor array of size = 2. Assign object elements
AF_DCMotor motors[] = { AF_DCMotor(1), AF_DCMotor(2) };
void motorrun (int i) {
motors[i].run(FORWARD);
}
// trigger motors[0] to run
motorrun(0);
// trigger motors[1] to run
motorrun(1);
Hope this help!
Upvotes: 3
Reputation: 2738
So this is where you'd want to pass a pointer to the motor you're trying to run into the function.
void motorrun(AF_DCMotor *motor) {
motor->run(FORWARD);
}
motorrun(&motor1);
motorrun(&motor2);
Upvotes: 3