I’d like to start out by saying that Giving out code doesn’t help you in the long run, understanding the code is what will help you, people that help with parts of code are helping you understand how it works, but people who just give the code with no explanation don’t.
What you are looking for (a PID controller) can be simplified to a less accurate but easier for beginners to program that is just a P loop (one piece of the PID), and if you are looking for a great place to start I would start with just a P loop.
A P loop, which means a proportional loop, is made when you set the motor power to be the difference between the position the motor is at and the position where you want the motor to be at (or the error).
My first P loop program I made a function to call whenever you want to use the loop where you put in the distance you want to go
void drive(float dist) {
}
that function just has a while loop that loops while the absolute value of the error is greater than whatever accuracy works for you (or whatever accuracy gives you the most amount of accuracy without making the while loop never stop)
void drive(float dist) {
while (dist-abs(motor.position(degrees))>5){
}
}
(Abs is a command that takes the absolute value)
Then In that loop I set the motor power to be the error
void drive(float dist) {
while (dist-abs(motor.position(degrees))>5){
motor.spin(fwd, dist-motor.position(degrees), pct);
}
}
(Abs is a command that takes the absolute value, fwd means forward, and pct means percent )
I tested this, and it didn’t quite give the desired results, the optimal motor power was not quite proportional to the error, so I multiplied it by a constant (Kp)
double Kp = 0.75;
void drive(float dist) {
while (dist-abs(motor.position(degrees))>5){
motor.spin (fwd, ( dist - motor.position(degrees)) * Kp, pct);
}
}
(Abs is a command that takes the absolute value, fwd means forward, and pct means percent )
When Kp is calibrated, the robot should give the desired result, a more accurate auton than just wait commands.
To call the function just do drive(what ever distance you want in degrees);
This is not the exact code I made, I am just typing this from memory so it might be a bit off, and if you want to add more motors make the error equal the average motor position. I also later made the distance equal inches instead of degrees by using the circumference of the wheel
When I wanted more accuracy, I learned how to make a PID and improve this code, but this worked for the first couple competitions.
I hope this helps, and good luck with programming!
(Edit: you can just add the D and I to this loop, but what I ended up doing was implementing multithreading to make it run with other stuff, but if you are newer to coding I wouldnt suggest that)