Code doesn't work for turning at all

this code should make the robot turn 90 degrees, does not work, makes it go straight backwards

Inertial9.setHeading(0, degrees);
  while ((Inertial9.heading(degrees)-90)<0) {
  right1.spin(reverse);
  right2.spin(reverse);
  right3.spin(reverse);
  left1.spin(forward);
  left2.spin(forward);
  left3.spin(forward);
  velocitychange(Inertial9.heading(degrees)-90);
  }

How are your motors defined in your robot config file? If your robot is going “straight backwards” in this code, you probably have some motors defined as reversed.

they are not, my function for controls and going forward works perfectly

Hmm. I’m not sure then. What is in the “velocitychange” function?

change all the motor velocities at same time

i updated the code

int ondriver_drivercontrol_0() {
  arm.setMaxTorque(100.0, percent);
  rEings.setVelocity(40.0, percent);
  arm.setVelocity(100.0, percent);
  while (true){
    controls();
  }
  return 0;
}

// "when autonomous" hat block
int onauton_autonomous_0(){
  Inertial10.setHeading(0, degrees);
  float diff = (Inertial10.heading(degrees)-90);
  while (fabs(diff) > 0.01) {
    velocitychange(fabs(diff)*90/20);
    int diff = (Inertial10.heading(degrees)-90);
    if(diff<0){
      right1.spin(reverse);
      left3.spin(forward);
      right2.spin(reverse);
      left2.spin(forward);
      right3.spin(reverse);
      left1.spin(forward);
    }
    else{
      right1.spin(forward);
      left1.spin(reverse);
      right2.spin(forward);
      left2.spin(reverse);
      right3.spin(forward);
      left3.spin(reverse);
    }
    
    diff = (Inertial10.heading(degrees)-90);
  }

You may want to attenuate velocity instead of flipping forward / reverse. Velocity is a range from -100 to +100 and direction is binary. If you tell a forward motor to spin at -50 it will spin backward. This way you don’t need to use the if / else to change direction and the motors will dynamically change direction if the value falls below zero.

void driveVelocity(float left, float right) {
      left1.spin(forward, left);
      left2.spin(forward, left);
      left3.spin(forward, left);
      right1.spin(reverse, right);
      right2.spin(reverse, right);
      right3.spin(reverse, right);
}

int onauton_autonomous_0(){
  Inertial10.setHeading(0, degrees);
  float diff = (Inertial10.heading(degrees)-90);
  while (fabs(diff) > 0.01) {
    //Whatever your logic is for course correction
    int diff = (Inertial10.heading(degrees)-90);
    driveVelocity(60-diff, 60+diff);
    diff = (Inertial10.heading(degrees)-90);
  }
}
2 Likes