Page 1 of 1

Wait function

Posted: Sat Apr 27, 2019 8:14 am
by LIC
Hi, I would like to write a wait function for my OS.
Just a simple one that adds a delay with a loop. I tried like this :

Code: Select all


// library.c

extern void wait_ms(uint32_t ms)
{
	const uint32_t BEG = ms + timer_get_tick();
	while (BEG < timer_get_tick());
}

// timer.c

static volatile uint32_t tick = 0;

extern volatile uint32_t timer_get_tick(void)
{
	return tick;
}

but it does not work, it does not even enter the while loop (I tested with a printf). I think this might be related to GCC optimization (correct me if I am wrong).

How can I change to make this function work?
Regards

Re: Wait function

Posted: Sat Apr 27, 2019 8:47 am
by MichaelPetch
Your logic is wrong. You set BEG in the future (by taking that original timer_get_tick() value and adding MS to it. Maybe you meant something like:

Code: Select all

   const uint32_t END = ms + timer_get_tick();
   while (timer_get_tick() < END);

Re: Wait function

Posted: Sat Apr 27, 2019 8:52 am
by LIC
Yes, that is exactly what I meant, now it works :)
I thought this was a compiler optimization problem but my code was just wrong, thank you!