(c++)How do I multi task with motors

I’m completely new to coding v5’s and coding in general, I saw the multitasking forum, but i tried using that code with actual motors and the controller, but I can’t get it to work.
plz dont bully me for crappy coding
my code currently

#include "robot-config.h"

int lift() {

while(1) {
if(Controller1.ButtonR1.pressing()){
Lift1.spin(vex::directionType::fwd, 100,vex::velocityUnits::pct);
Lift2.spin(vex::directionType::fwd, 100,vex::velocityUnits::pct);
vex::this_thread::sleep_for( 25 );

} 

}
return(0);
}

int main(){
vex::thread t( lift );

while(true) {
    if (Controller1.Axis3.value()){
        DR1.spin(vex::directionType::fwd, Controller1.Axis3.value(), vex::velocityUnits::pct); 
        DR2.spin(vex::directionType::fwd, Controller1.Axis3.value(), vex::velocityUnits::pct);
        }
    if (Controller1.Axis2.value()) {  
        DL1.spin(vex::directionType::fwd, Controller1.Axis2.value(), vex::velocityUnits::pct);
        DL2.spin(vex::directionType::fwd, Controller1.Axis2.value(), vex::velocityUnits::pct);       
        } 
    else{
        DR1.stop(brakeType::brake);
        DR2.stop(brakeType::brake);
        DL1.stop(brakeType::brake);
        DL2.stop(brakeType::brake);
        Intake.stop(brakeType::brake);
        Lift1.stop(brakeType::brake);
        Lift2.stop(brakeType::brake);
        }
    
    }
  
  vex::this_thread::sleep_for(10);

}

What is exactly isnt working about it? Are the motors not turning, is it not compiling?Please elaborate.

@Delirious it is good that you are learning about tasks, but in general you don’t need separate tasks unless you are trying to do something asynchronous and with algorithm complex enough that needs a lot of state variables or heavy calculations.

In the majority of cases, single main task is perfectly adequate.

I could see several problems with your code. First of all, in the main task sleep_for() is outside of the while loop, which means that main task is not going to voluntarily yield any time to other tasks. Similarly, the lift task only sleeps if the condition is true, and does not sleep otherwise. Finally, your main task will stop lift motors when you are not driving.

Ideally, your control loop should look something like this:

main()
{
     while(1)
     {   
         if( liftButtonPressed )
         {
             liftMotor.spin(100);
         }
         else
         {
            liftMotor.stop();
         }

         if( abs(controller.whateverAxisGoingForward.value()) > 10  )
         {
             driveMotor.spin(controller.whateverAxisGoingForward.value());
         }
         else
         {
            driveMotor.stop();
         }

         ...

         sleep_for(10);
     }
}

Hope, this helps.

1 Like

yes actually it did, thanks