/ src / timer / timer.c
timer.c
 1  // timer based on Nordic's counter.
 2  // see nRF5 SDK License for license info.
 3  #include "timer.h"
 4  
 5  #include "nrf_log.h"
 6  #include "nrf_drv_clock.h"
 7  #include "nrfx_rtc.h"
 8  #include "nrfx_clock.h"
 9  
10  static const nrfx_rtc_t timer_rtc = NRFX_RTC_INSTANCE(TIMER_RTC_INSTANCE);
11  
12  static void timer_rtc_handler(nrfx_rtc_int_type_t event)
13  {
14  	if (event == NRFX_RTC_INT_OVERFLOW)
15  	{
16  		// perhaps we want to handle an overflow in some way...
17  		// for now we will just log it
18  		NRF_LOG_WARNING("RTC%d OVERFLOW", TIMER_RTC_INSTANCE);
19  	}
20  }
21  
22  void timer_initialize(void)
23  {
24  	// request the lf clock, as this doesn't seem to happen automatically.
25  	nrf_drv_clock_lfclk_request(NULL);
26  
27  	nrfx_rtc_config_t config = NRFX_RTC_DEFAULT_CONFIG;
28  	config.prescaler = RTC_FREQ_TO_PRESCALER(TIMER_TICK_FREQUENCY);
29  	APP_ERROR_CHECK(nrfx_rtc_init(&timer_rtc, &config, timer_rtc_handler));
30  
31  	// start with a fresh counter
32  	nrfx_rtc_counter_clear(&timer_rtc);
33  
34  	// we don't need the tick event.
35  	nrfx_rtc_tick_disable(&timer_rtc);
36  }
37  
38  void timer_start(void)
39  {
40  	nrfx_rtc_counter_clear(&timer_rtc);
41  	nrfx_rtc_enable(&timer_rtc);
42  }
43  
44  void timer_stop(void)
45  {
46  	nrfx_rtc_disable(&timer_rtc);
47  }
48  
49  uint32_t timer_get_ticks(void)
50  {
51  	return nrfx_rtc_counter_get(&timer_rtc);
52  }
53  
54  float timer_get_elapsed_seconds(void)
55  {
56  	uint32_t ticks = timer_get_ticks();
57  	return timer_ticks_to_seconds(ticks);
58  }