# Determine motor speed using encoder

Question asked by Daniel Boström on Feb 5, 2018
Latest reply on Feb 7, 2018 by Daniel Boström

I am tasked with finding out the speed of a motor using a quadrature encoder interface. As a first step I thought I'd make it as easy as possible and try to determine the time it takes for the encoder counter to count up once. Since I don't have the motor and encoder yet I have tried to simulate the encoder output using a timer (TIM1) on my STM32F303K8 Nucleo (I am running everything on this board atm). I have checked this community and googled other places and found an approaches which I have tried with limited success. I am using the max system clock at 72MHz and the code is generated by STM32CubeMX. This is what I have tried:

Use one timer to simulate encoder output and feed the output to the input of another timer set up as an encoder interface. Then have a third timer trigger an interrupt at a given time interval and check if the encoder has incremented the counter.

TIM1 (Simulated encoder output): 200Hz

TIM1 (CH1, CH3) output looks like this (verified with oscilloscope):

TIM2 (Timer update interrupt with 1us interval): 1MHz

TIM3 (Encoder interface):

Using X4 encoding I expect that the TIM3 counter will be incremented once every 1250us (see picture above). However the times I get using this approach is 61-62us less. This is the ten sampled values I get (there is something in my implementation that gives a value twice as big the first time):

2378, 1189, 1189, 1189, 1188, 1188, 1189, 1189, 1189, 1188

I noticed if I change the speed of TIM2 to half, (Prescaler above is set to 1 instead of 0) and get interrupts every 2us instead then it looks much better:

2500, 1250, 1250, 1250, 1250, 1250, 1250, 1250, 1248, 1250

Any ideas why it looks better when I slow down TIM2 to 500KHz? How does one determine the correct prescaler/counter period for the different timers? I am confused, I can see that the results change when i change prescaler etc. but I don't understand how it is all related, now I've just used trial and error. If you need more information let me know.

If there are better approaches to achiving what I want I am all ears. I've seen something about configuring timers in master-slave relationship to solve this but I haven't figured that out yet.