简体   繁体   中英

Parameters in a function C++

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
}

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);

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM