Function for getting rpm from encoder


i need the following:

i need a program which gives me a feedback of a sudden changing of the rpms (the “real” rpms are not important, just the fact, that the rpms are suddenly decreasing).

i thought about something like that:

reset encoder → counting the ticks and assigning variable_1 → waiting 100ms → counting again and assigning variable_2 this actual value - variable_1, then resetting the encoder. then doing the same thing in a loop, always comparing the values of variable_2 for a significant changing.
as a first step i tried to print the value of variable_2, for 3 seconds in a loop, but i only get a zero on the lcd (see the code below).

is my idea wrong in general? or “just” my code? or both? sorry, i´m a complet newbie, but i try hard, so please help (and correct!) me…


#include <pololu/orangutan.h>

unsigned int variable_1;
unsigned int variable_2;

int main()

variable_2 = encoders_get_counts_and_reset_m2() - variable_1;



You seem to be pretty close. I suggest you try something simpler to start with: just try to measure and print out the RPM, and see if the number you are getting makes sense.

Step 1) Write a program that just prints the raw encoder counts to the LCD. Rotate the motor output shaft by hand and verify that the counts increase when you turn it one way and decrease when you turn it the other way. This will let you know that you have your encoder connected properly and it works.

Step 2) Read the encoder counts, delay for 100 ms, read the counts again, and then subtract the two readings and multiply by the appropriate conversion factor to get an answer in units of RPM.

What motor are you using?

- Ben

hi ben,

thanks for answering this theme also;-)

the encoder is wired correctly, i got correct values before. just the code i wrote doesnt work. isn´t my code exactly what you told me to try?

As I said, it looks close, but since you say it doesn’t work, it can’t be exactly what I’m suggesting. That’s why I very specifically suggested you start with a simpler program that just prints out the raw encoder counts. I can then help you modify that working program to something that will display the RPM.

Also, you are never clearing the LCD, which might make it print out some confusing results. You should probably use clear() instead of lcd_goto_xy().

- Ben

Another thing you might want to try is to make your variables signed ints instead of unsigned. The encoder counts can be negative, so your calculations might produce some strange effects if you try to use unsigned ints.

- Kevin