Wait function

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
LIC
Member
Member
Posts: 44
Joined: Mon Jun 04, 2018 8:10 am
Libera.chat IRC: lic

Wait function

Post 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
MichaelPetch
Member
Member
Posts: 798
Joined: Fri Aug 26, 2016 1:41 pm
Libera.chat IRC: mpetch

Re: Wait function

Post 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);
LIC
Member
Member
Posts: 44
Joined: Mon Jun 04, 2018 8:10 am
Libera.chat IRC: lic

Re: Wait function

Post 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!
Post Reply