# Calculate Velocity

Hi, I recently try to use optical shaft encoder to calculate the velocity of motor but I just can;t get it to work. First, when I use function SensorValue], does it return degree that motor turns or something else? Else, what is a good way to calculate the velocity using optical shaft encoder?

``````#pragma config(I2C_Usage, I2C1, i2cSensors)
#pragma config(Sensor, I2C_2,  ,               sensorQuadEncoderOnI2CPort,    , AutoAssign )
#pragma config(Motor,  port5,           launch1,       tmotorVex393HighSpeed_MC29, openLoop, reversed, encoderPort, dgtl1)
#pragma config(Motor,  port6,           launch2,       tmotorVex393HighSpeed_MC29, openLoop, encoderPort, I2C_2)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//
int speed;
int prevEncL;
{
motor[port5] = 90;
motor[port6] = 90;
while(true){
waitInMilliseconds(20);
prevEncL = SensorValue[encoderL];
speed = SensorValue[encoderL] - prevEncL;
}

}
``````

the SensorValue for an encoder returns the degrees that the encoder has spun, so depending on where you placed it in the gearing it may or may not be the degrees the motor has spun.

The issue with your code is that you have the order a bit mixed up, and are also missing somethings. Here is the basic way to do it, I will use a wait of 1/20th second between rounds.

``````
while(true)
{
current = SensorValue[encode];
//Take the difference in the sensor value since the last reading, convert from degrees to rotations, convert 1/20 second to minutes
speed = (current - last) / 360 * 20 *60; //You can simplify the math if you want
last = current;
wait1msec(50);
}

``````