coding encoder

Our team is trying to use the encoders for our base to make the autonomous coding process easier. We’ve already attached two encoders to our base, but we have little knowledge on how to code them. We’ve done some research online, but it would be really helpful if we could see some example codes for the encoders. We are using robotc for our coding program.

I am going to assume you are using RobotC:

Basic code for encoders (not PID) can be approached in these two ways



while(SensorValue[EncoderName] < *targetvalue you want to go for*)
{
motor[name] = *speed you want* ; 
}
__________________________________________________________  OR 

startMotor(port, speed);
untilEncoderCounts(targetvalue, port);  



PID would look something like this: 

float kP = 0.3 (or number that you tune); 
float kI = 0.05 (or number you tune); 
float kD = 0.1 (or number you tune); 
int target;

task PID()
{
int error; 
int integral; 
int derivative; 
int lasterror; 
int speed;
while(true)
{
error = target- SensorValue[port];

if(abs(error) < 50) // or your integral limit
{
integral += error; 
}
else
{
integral = 0;
}

derivative = error - lasterror;
lasterror = error;
speed = (error*kP) + (integral *kI) + (derivative *kD);

motor[port] = speed; 
}
wait1Msec(25); //refresh (can be 20 as well)

}

Ofc there are things such as advanced motion control (motion profile), position tracking etc etc… that are beyond PID but I would highly recommend using it if you are able to as it is arguably one of the best control loops for VEX