Inertial Sensor Turning Help

So, I tried to create code using the Inertial sensor where my drivetrain would turn 90 degrees to the right and it just stayed still and did nothing. Any suggestions?

Here is my code:

void RightTurn (int turn){
FLMotor.setVelocity(30,pct);
BLMotor.setVelocity(30,pct);
FRMotor.setVelocity(30,pct);
BRMotor.setVelocity(30,pct);

FLMotor.spin(forward);
BLMotor.spin(forward);
FRMotor.spin(reverse);
BRMotor.spin(reverse);
waitUntil(Inertial1.heading(degrees)>=turn);
FLMotor.stop();
BLMotor.stop();
FRMotor.stop();
BRMotor.stop();
return;
task::sleep(10);
}

Hello, one suggestion I have to fix your code is to do as a while loop. Like so:

void rightTurn(int turn, int speed) {
  while (Inertial1.rotation(deg) < turn) {
    front_L.spin(fwd, speed, pct);
    front_R.spin(fwd, -speed, pct);
    back_L.spin(fwd, speed, pct);
    back_R.spin(fwd, -speed, pct);
    task::sleep(10);
  }
  front_L.stop(hold);
  front_R.stop(hold);
  back_L.stop(hold);
  back_R.stop(hold);
}

The reason behind is that you want your motors to spin while the inertial is detecting that the angle is not what you have achieved. The reason that I used the rotation API instead of heading is that heading wraps the angle, meaning that it’s only between (0 -360). Usually, you want to be able to go into negatives so its a better choice to use rotation unless you need angle wrapping. I also added another parameter called speed so its easier for you to change the speed at what the motors spin. I hope this helps :slight_smile:

3 Likes

Thank you so much! This is very helpful!

1 Like

I have a question, how do you read the rotation because on the Inertial Sensor set up because you can’t read it on the brain (only the heading, X,Y and,Z plane, the roll, and pitch) or am I missing something?

So for this you usually want to display the data to the brain so to do this you can do it like this

Brain.Screen.printAt(1, 20, "Rotation of Robot: %f", Inertial1.rotation(deg));

and this way you can see the exact rotation that the inertial is giving. And to do this properly you should put this in your while loop that you have setup so it updates the value on the screen every 10ms. And as a side note the %f basically tells the computer that you want to display a float value there.

2 Likes

Thanks!
20 chars 20 chars

1 Like