cancel
Showing results for 
Search instead for 
Did you mean: 

WHILE LOOP PROBLEM FOR MICRO SECONDS WITH TIMER ??

Ramazan Gülcan
Associate III
Posted on June 16, 2018 at 22:25

Hi friends,

The while loop does not work in the following function. Why could it be?

For STM32F407VG;

void US_BEKLE(uint16_t us)

{

uint16_t baslangic = (uint16_t)__HAL_TIM_GET_COUNTER(&htim1);

while(((uint16_t)__HAL_TIM_GET_COUNTER(&htim1)) - baslangic < us);

}

htim1.Instance = TIM1;

htim1.Init.Prescaler = 167;

htim1.Init.CounterMode = TIM_COUNTERMODE_UP;

htim1.Init.Period = 65000;

htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

htim1.Init.RepetitionCounter = 0;

#microsecond-timer #while-loop
13 REPLIES 13
Posted on June 17, 2018 at 14:19

What compiler are you using?

unsigned numbers will not be negative.

uint16_t start, current;

uint16_t delta;

delta = (current - start); // will always be positive and represent accurately the number of cycles between the two points up to 65535 cycles.

If something like this doesn't work something is tragically wrong with the compiler.

uint16_t start = 

TIM1->CNT;

volatile uint16_t current;

do

{

  current = TIM1->CNT;

} while((current - start) < us);

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on June 17, 2018 at 14:25

I use atollic.

I think I should not be negative.

But the problem is resolved in this way.

Posted on June 17, 2018 at 14:44

current-start = delta

0004-FFFC = 0008 ; wrap case

FFFB-FFFC = FFFF ; maximal case

0008-0004 = 0004 ; nominal case
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on June 17, 2018 at 15:35

I need to cast all of the subtraction in uint16_t format.

it also works as follows

while( (uint16_t) ((uint16_t)__HAL_TIM_GET_COUNTER(&htim1) - baslangic ) < us);