Does anyone know how to have a drivetrain move with encoder values using a PID?

I have written a PID for accurate driving and turning, but don’t know how to actually have the drivetrain drive until the encoder values in degrees are reached. Would anyone have an example code of how to do this in autonomous? Thanks so much in advance.

Create functions that use your pid.

Call them something like “Driveto( )”. Give it some args like distance, as well as timeout, threshold, max voltage, and possibly feedforward/bias.

Lets start with just distance, threshold, and timeout.

void Driveto(argstuff) {

//assign variables here
//start a timer and possibly reset or capture starting sensor values as needed.
while(true) {
//do pid stuff

//output pid stuff to motors//

if (time>timeout) {break;}
if (abs(error)<threshold && abs(speed)<someDifferentThreshold) {break;}
if (other things like collision detection or something else happens that you determine can go wrong in testing) {break;}

wait(20,msec);
}
}

Edit: If anyone has follow-up questions just reply and @me. You can work with teachers and programming tutorials to learn how to do all the stuff I //assumed you could do.

1 Like

@AperatureLabs So how would you call the function to drive to a certain distance in autonomous?

in the auton code you just call one function after the next, sequentially.


driveStraight(-20,2,5);
intake.rotateto(forward, 200, degrees); //or whatever the commands are.
driveStraight(20,2,5);
aimNshoot(3); //aimbot and automatic shooting function that references the flywheel velocity and camera pid to help shoot.
turnPid(-45,2, 5);//this turns to an absolute direction so the aimbot turning any won’t have an affect.
intake.spin(forward);
driveStraight(150, 2, 5);
//intake more;
turnPid(numbers); //turn and…
aimNshoot(); //idk, maybe args in this too, like timeout, or the ability to turn off aiming, or set vision sensor thresholds for certain things if you are feeling spicy.

then maybe get more discs or go to your other roller, idc. Have fun.

EDIT: If you want, you can toss in some logic using sensors. If you have discs (distance sensor or limit switch), then do one thing, if you don’t do another thing.

Also end auton in the best position you can. Midcourt with discs? Sure. In the corner ready to snag the opposing roller? You betcha. Whatever you want. Just don’t waste the opportunity.

2 Likes

@AperatureLabs Alright thanks so much I really appreciate it!