# RPM of Optical Shaft Encoders?

Hello all, I was wondering how to find the RPM of a Shaft Encoder and export it as a variable. If anyone could demonstrate, that would be greatly appreciated. Thanks in advance.

This is the general idea, but it can be far more streamlined. I’m assuming you’re using RobotC, but I’m not familiar enough with EasyC to help if that’s what you’re using.

``````
int timeNow =0,
timeLast = 0,
deltaTime = 0,
encNow = 0,
encLast = 0,
deltaEnc = 0;
float encRate = 0,
encRpm = 0;
while(true) {
timeNow = nSysTime;
deltaTime = timeNow - timeLast;
encNow = SensorValue[encoder];
deltaEnc = encNow - encLast;
if(deltaTime > 0) {
encRpm = (deltaEnc / deltaTime) * 1000.0 / 360
}
else {
encRpm = 0;
}
encLast = encNow;
timeLast = timeNow;
wait1Msec(20);
}
}

``````

Edit: Comments don’t look good in code on this forum.
I use nSysTime because I don’t need to write to the timer, I just need to read it, and I don’t need to use different timers for each time I want to use one.
The multiplying by 1000.0 converts from ticks/ms to ticks/sec, and uses a decimal, and the division by 360 converts from ticks to revolutions. I use rps (rotations per second) instead of rpm because rpm would be massive number (you multiply by 60,000 instead of 1000). You actually can leave it in revolutions per ms, or ticks per ms, by removing the corresponding conversion factor.

What does nsystime do for the program?
Is it like a different variable or…?

nSysTime is a variable that tracks how long (in milliseconds) the program has been running, including any time that it is disabled. This lets the velocity calculation continue running while the robot is disabled, so filters behave as expected and show the actual velocity of the flywheel.