Delay function in freedom sdk


(Daniel kirubakaran) #1

Is there any delay() function available in Freedom-E-SDK ? i want to use it for seconds delay.
Since i am not going to write code in arduino ide ,i am searching for that function or similar to it.


Equivalent RISC-V asm code
(Bruce Hoult) #2

If you look in freedom-e-sdk/bsp/env/freedom-e300-hifive1/init.c you’ll see uint64_t get_timer_value(). In `platform.h’ you’ll see

unsigned long get_cpu_freq(void);
unsigned long get_timer_freq(void);
uint64_t get_timer_value(void);

On the HiFive1 the timer always increments at 32 MHz. On other boards it may be different. get_timer_freq() returns how many timer counts there are in a ms.

So you can multiply the delay you want in ms by get_timer_freq(), add that to the result of get_timer_value(), and then do whatever you want until the result of get_timer_value() is greater than that.

There’s no operating system, so if you simply loop waiting then nothing else can happen (except interrupts) until your delay ends. That’s usually not very useful for delays over a few us so it’s better to put it in your main loop and do other things. Or use an RTOS, several of which have been ported.

It’ll take 18000 years for the timer to overflow so you probably don’t need to worry about that.


(Daniel kirubakaran) #3

Great ! Very useful.

:sweat_smile::sweat_smile: well that was good to hear!

Anyways thank you.


(Bruce Hoult) #4

Oops! Sorry, that timer increments at 32 kHz, not 32 MHz, and so get_timer_freq() returns the number of counts in a second, not millisecond.

Which means the 64 bit overflow time is 18 million years.


(Daniel kirubakaran) #5

Here i have made it like this for a normal seconds delay.
is that fine?

void delay(int sec){

uint64_t ticks = sec * RTC_FREQ;
mtime_wait(ticks);

}
void mtime_wait( uint64_t ticks)
{

volatile uint64_t * mtime  = (uint64_t*) (CLINT_CTRL_ADDR + CLINT_MTIME);
uint64_t now = *mtime;
  uint64_t then = now + ticks;
 
  while(*mtime<then) {
  }

}


(Daniel kirubakaran) #6

where RTC_FREQ is 32768


(Bruce Hoult) #7

Looks good. I even just tested it and it works.

A general note for such functions: if you write the loops as…

while((*mtime - now) < ticks) {}

… then it will work correctly over that 18 million year counter rollover too.

Not an issue in this case, but important if you use the 32 bit clock cycle counter which rolls over every 10 or 12 seconds on HiFive1 at the higher clock speed settings.


(Daniel kirubakaran) #8

Oh ! okay.
Thank you.:slightly_smiling_face: