I am trying to use a rotation sensor on a linear puncher so that when I push a button, the motor will spin until the rotation sensor reads 0 degrees. I have looked on youtube for videos on how to program a rotation sensor but I couldn’t find any help.I do not understand the Vex API so any references to it will need an explanation. Can anyone help?
Few comments…
-
hitting a precise degree is very hard to do due to inertia.
-
you need to think like ‘stop motor if degrees is equal to or less/greater than some value’
-
using 0 degrees is usually a problem due to anything less than 0 wrapping back to 359 degrees… which breaks your logic
-
you might consider turning a set number of degrees and not tracking ACTUAL degrees
-
you might consider resetting the degrees back to zero (or some other number) before you begin the move
-
you might consider a limit switch (bumper) on your mechanism… and using that to determine when it’s moved far enough
I have only used the inertial sensor before and this code is untested but this is what I’ve come up with
#include "vex.h"
using namespace vex;
void SpinToZero(){
int InitalRot = Rotation.angle(); // Saves the inital rotation value
int TurnDegs = 360 - InitalRot; // Finds how many degrees to rotate
int SpinSpeed = 50; // Just set to 50 to avoid potential errors, this is changed
Rotation.setPosition(0, degrees); // Sets the virtual position to 0
while(Rotation.angle() < TurnDegs){ // Keeps turning until reached desired value, in this case 0
SpinSpeed = (40 * (Rotation.angle() / TurnDegs)) + 10; // Spins slower as it gets closer
MotorLeft.spin(forward, SpinSpeed, percent); // Make sure this has it spin clockwise
MotorRight.spin(reverse, SpinSpeed, percent);
}
int EndRot = InitalRot + TurnDegs; // Finds the ending degree
if(EndRot > 360) // Checks if EndRot is over 360
EndRot -= 360;
Rotation.setPosition(EndRot, degrees); // Sets virtual rotation to where it is now
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
SpinToZero(); // Should spin the bot to 0
}
This also only turns to the right, so if you are at 10 degrees and use it, the bot will turn 350 degrees to get there.
Where would the code go in a competition template?
The SpinToZero function would go at the top of your code outside main but before the variables, the rule is that it needs to be after anything that it uses and anything that uses it needed to be after. From there you should be able to call it where you need to