How to assign motors mid-code?

I am creating a program that requires me to assign ports to a motor, with the port numbers loaded from the SD card. It appears that I am unable to redeclare the motors mid-code. Any suggestions?

Example:
motor ArmMotor(PORT1, gearSetting::ratio36_1, false);

int main() {
ArmMotor = motor(PORT5, gearSetting::ratio36_1, false);
}

Result: Does not change motor connection from PORT1 to PORT5.

Thanks in advance.

See this thread - it’s about doing something similar in PROS but is also applicable to VEXcode.

The gist is, rather than maintaining a bunch of motor objects, you maintain a bunch of pointers to motor objects. Then when you want to ‘change ports’ you initialize a new motor object on the new port and point the pointer at the new object rather than the old object.

It doesn’t have to be that complicated. The code below works. It all depends if the motor object goes out of scope or not.

#include "vex.h"

using namespace vex;

// A global instance of vex::brain used for printing to the V5 brain screen
vex::brain       Brain;

// define your global instances of motors and other devices here
vex::motor       m1(PORT1, ratio18_1 );
vex::controller  c;

int main() {
    int count = 0;
   
    while(1) {
      if( c.ButtonA.pressing() ) {
        while( c.ButtonA.pressing() )
          this_thread::sleep_for(10);

        m1.stop();

        // swap to other motor
        if( m1.index() == PORT1 )
          m1 = vex::motor( PORT2, ratio18_1 );
        else
          m1 = vex::motor( PORT1, ratio18_1 );
      }

      if( c.ButtonX.pressing() ) {
        m1.spin(fwd);        
      }
      else {
        m1.stop();
      }

      Brain.Screen.printAt( 10, 50, "Motor index %d", m1.index() );
      Brain.Screen.printAt( 10, 70, "Motor speed %.2f", m1.velocity( rpm ) );
      // Allow other tasks to run
      this_thread::sleep_for(10);
    }
}
4 Likes