In RobotC:
-First setup the sensors. There is a configuration tool in RobotC to setup the sensors and motors. It has tabs to configure what is connected to each port of the Cortex.
-In code, RobotC only returns the distance traveled by the encoder. The easiest way to get speed from distance is to find the derivative (dx/dt). The easiest way to do this is to keep dt constant (by using a Wait1Msec(20); for 20ms loop time) and calculate dx by comparing the value of the sensor now to the value of the sensor cached last iteration.
-By calculating the number of ticks per meter (you would need to know the radius of the wheel, gear ratio between wheel and encoder, and number of lines in the encoder to calculate this) and knowing dt you can calculate the velocity. I would just keep velocity in ticks/iteration and calculate the setpoint based on your desired speed in the units you wish (This reduces processor load while the code is running)
-You would then use a feedback controller to adjust the motor power based on the calculated velocity. The most complete way to do this is via a PID controller, although you can get decent performance (with a longer settling time) by just using the integral term. In this case, you would do something like this:
Code:
//Outside of the function, as a global (this cannot be reset each iteration)
int integrator = 0;
//Inside the function, running every 20ms
int velocity_set = 3000;//Speed you are trying to achieve - 3000 is just an example, you would need to calculate this in ticks/iteration
float ki = 1;//This parameter needs to be calibrated
int velocity_error = velocity_set - velocity_cur;
int power_output = velocity_error * ki
integrator += power_output;
//Limit the integrator to the valid range of +-127 to reduce windup, I'll let you figure this out
motor[1] = integrator;
If you have an encoder on both sides, I would recommend separate feedback controllers for each side. They should share the same setpoint and ki, but use different sensor velocities and integrators.
This entire post explains the methodology of the code, and the code example above is not complete enough to use as-is. If you would like more specific code/syntax help, feel free to ask.