Skip to main content
Omiks3
Associate
January 20, 2021
Solved

Encoder code acting strangely on

  • January 20, 2021
  • 2 replies
  • 1425 views

So I've got some very basic code for a STM32 to read an encoder using timer 1 in encoder mode.

This first routine works fine counting up and down as expected, printing CW (Clockwise) while counting up and CCW (Counter Clockwise) while counting down... The direction of the counter is read by the TIM_CR1_DIR bit with 1 for down.

cnt = TIM1->CNT;
// if counter counting down encoder is turning CW because i switched the wires
if (!(TIM1->CR1 & TIM_CR1_DIR) && cnt != prevCnt)
{
 printf("CCW, count = %d\n", 100 - cnt);
 prevCnt = cnt;
 pCnt = 0;
}
else if ((TIM1->CR1 & TIM_CR1_DIR) && cnt != prevCnt)
{
 printf("CW, count = %d\n", 100 - cnt);
 prevCnt = cnt;
 pCnt = 0;
}
HAL_Delay(50);

I thought I could clean it up a bit by taking out some of the redundant lines so I wrote this... But this routine acts really unpredictably sometimes it will print CCW while counting up and visa versa, or it will print CW while turning CCW. I'm fairly new to programming so I'd love to hear what I'm doing wrong.

Thanks!

cnt = TIM1->CNT;
if (cnt != prevCnt) {
 // if counter counting down encoder is turning CW because i switched the wires 
 if (TIM1->CNT & TIM_CR1_DIR)
 printf("CW, count = %d\n", 100 - cnt);
 else
 printf("CCW, count = %d\n", 100 - cnt);
 
 pCnt = 0;
 prevCnt = cnt;
 }
 else if (pCnt < 1)
 printf("No Change!, count = %d\n", cnt);
 
 pCnt++;
 HAL_Delay(50);

This topic has been closed for replies.
Best answer by waclawek.jan

> if (TIM1->CNT & TIM_CR1_DIR)

You probably meant

if (TIM1->CR1 & TIM_CR1_DIR)

JW

2 replies

TDK
Super User
January 20, 2021

Encoders, much like buttons, can be electrically noisy. I would ignore the DIR bit and compare TIM1->CNT to its previous value to determine the direction of rotation since the last time you checked it.

Your two code snippets are equivalent as far as I can see, except for the "no change" printout and the pCnt variable stuff.

"If you feel a post has answered your question, please click ""Accept as Solution""."
waclawek.jan
waclawek.janBest answer
Super User
January 20, 2021

> if (TIM1->CNT & TIM_CR1_DIR)

You probably meant

if (TIM1->CR1 & TIM_CR1_DIR)

JW

Omiks3
Omiks3Author
Associate
January 20, 2021

Thank you!

That makes sense why it was acting erratically, when bit 4 in TIM1->CNT was changing it was triggering a direction change in my code.