]> git.gir.st - tmk_keyboard.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/us_ticker.c
Merge commit '1fe4406f374291ab2e86e95a97341fd9c475fcb8'
[tmk_keyboard.git] / tmk_core / tool / mbed / mbed-sdk / libraries / mbed / targets / hal / TARGET_NORDIC / TARGET_MCU_NRF51822 / us_ticker.c
1 /* mbed Microcontroller Library
2 * Copyright (c) 2013 Nordic Semiconductor
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include <stddef.h>
17 #include <stdbool.h>
18 #include "us_ticker_api.h"
19 #include "cmsis.h"
20 #include "PeripheralNames.h"
21 #include "nrf_delay.h"
22
23 /*
24 * Note: The micro-second timer API on the nRF51 platform is implemented using
25 * the RTC counter run at 32kHz (sourced from an external oscillator). This is
26 * a trade-off between precision and power. Running a normal 32-bit MCU counter
27 * at high frequency causes the average power consumption to rise to a few
28 * hundred micro-amps, which is prohibitive for typical low-power BLE
29 * applications.
30 * A 32kHz clock doesn't offer the precision needed for keeping u-second time,
31 * but we're assuming that this will not be a problem for the average user.
32 */
33
34 #define MAX_RTC_COUNTER_VAL 0x00FFFFFF /**< Maximum value of the RTC counter. */
35 #define RTC_CLOCK_FREQ (uint32_t)(32768)
36 #define RTC1_IRQ_PRI 3 /**< Priority of the RTC1 interrupt (used
37 * for checking for timeouts and executing
38 * timeout handlers). This must be the same
39 * as APP_IRQ_PRIORITY_LOW; taken from the
40 * Nordic SDK. */
41 #define MAX_RTC_TASKS_DELAY 47 /**< Maximum delay until an RTC task is executed. */
42
43 #define FUZZY_RTC_TICKS 2 /* RTC COMPARE occurs when a CC register is N and the RTC
44 * COUNTER value transitions from N-1 to N. If we're trying to
45 * setup a callback for a time which will arrive very shortly,
46 * there are limits to how short the callback interval may be for us
47 * to rely upon the RTC Compare trigger. If the COUNTER is N,
48 * writing N+2 to a CC register is guaranteed to trigger a COMPARE
49 * event at N+2. */
50
51 #define RTC_UNITS_TO_MICROSECONDS(RTC_UNITS) (((RTC_UNITS) * (uint64_t)1000000) / RTC_CLOCK_FREQ)
52 #define MICROSECONDS_TO_RTC_UNITS(MICROS) ((((uint64_t)(MICROS) * RTC_CLOCK_FREQ) + 999999) / 1000000)
53
54 static bool us_ticker_inited = false;
55 static volatile uint32_t overflowCount; /**< The number of times the 24-bit RTC counter has overflowed. */
56 static volatile bool us_ticker_callbackPending = false;
57 static uint32_t us_ticker_callbackTimestamp;
58
59 static inline void rtc1_enableCompareInterrupt(void)
60 {
61 NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk;
62 NRF_RTC1->INTENSET = RTC_INTENSET_COMPARE0_Msk;
63 }
64
65 static inline void rtc1_disableCompareInterrupt(void)
66 {
67 NRF_RTC1->INTENCLR = RTC_INTENSET_COMPARE0_Msk;
68 NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk;
69 }
70
71 static inline void rtc1_enableOverflowInterrupt(void)
72 {
73 NRF_RTC1->EVTENCLR = RTC_EVTEN_OVRFLW_Msk;
74 NRF_RTC1->INTENSET = RTC_INTENSET_OVRFLW_Msk;
75 }
76
77 static inline void rtc1_disableOverflowInterrupt(void)
78 {
79 NRF_RTC1->INTENCLR = RTC_INTENSET_OVRFLW_Msk;
80 NRF_RTC1->EVTENCLR = RTC_EVTEN_OVRFLW_Msk;
81 }
82
83 static inline void invokeCallback(void)
84 {
85 us_ticker_callbackPending = false;
86 rtc1_disableCompareInterrupt();
87 us_ticker_irq_handler();
88 }
89
90 /**
91 * @brief Function for starting the RTC1 timer. The RTC timer is expected to
92 * keep running--some interrupts may be disabled temporarily.
93 */
94 static void rtc1_start()
95 {
96 NRF_RTC1->PRESCALER = 0; /* for no pre-scaling. */
97
98 rtc1_enableOverflowInterrupt();
99
100 NVIC_SetPriority(RTC1_IRQn, RTC1_IRQ_PRI);
101 NVIC_ClearPendingIRQ(RTC1_IRQn);
102 NVIC_EnableIRQ(RTC1_IRQn);
103
104 NRF_RTC1->TASKS_START = 1;
105 nrf_delay_us(MAX_RTC_TASKS_DELAY);
106 }
107
108 /**
109 * @brief Function for stopping the RTC1 timer. We don't expect to call this.
110 */
111 void rtc1_stop(void)
112 {
113 NVIC_DisableIRQ(RTC1_IRQn);
114 rtc1_disableCompareInterrupt();
115 rtc1_disableOverflowInterrupt();
116
117 NRF_RTC1->TASKS_STOP = 1;
118 nrf_delay_us(MAX_RTC_TASKS_DELAY);
119
120 NRF_RTC1->TASKS_CLEAR = 1;
121 nrf_delay_us(MAX_RTC_TASKS_DELAY);
122 }
123
124 /**
125 * @brief Function for returning the current value of the RTC1 counter.
126 *
127 * @return Current RTC1 counter as a 64-bit value with 56-bit precision (even
128 * though the underlying counter is 24-bit)
129 */
130 static inline uint64_t rtc1_getCounter64(void)
131 {
132 if (NRF_RTC1->EVENTS_OVRFLW) {
133 overflowCount++;
134 NRF_RTC1->EVENTS_OVRFLW = 0;
135 NRF_RTC1->EVTENCLR = RTC_EVTEN_OVRFLW_Msk;
136 }
137 return ((uint64_t)overflowCount << 24) | NRF_RTC1->COUNTER;
138 }
139
140 /**
141 * @brief Function for returning the current value of the RTC1 counter.
142 *
143 * @return Current RTC1 counter as a 32-bit value (even though the underlying counter is 24-bit)
144 */
145 static inline uint32_t rtc1_getCounter(void)
146 {
147 return rtc1_getCounter64();
148 }
149
150 /**
151 * @brief Function for handling the RTC1 interrupt.
152 *
153 * @details Checks for timeouts, and executes timeout handlers for expired timers.
154 */
155 void RTC1_IRQHandler(void)
156 {
157 if (NRF_RTC1->EVENTS_OVRFLW) {
158 overflowCount++;
159 NRF_RTC1->EVENTS_OVRFLW = 0;
160 NRF_RTC1->EVTENCLR = RTC_EVTEN_OVRFLW_Msk;
161 }
162 if (NRF_RTC1->EVENTS_COMPARE[0] && us_ticker_callbackPending && ((int)(us_ticker_callbackTimestamp - rtc1_getCounter()) <= 0)) {
163 NRF_RTC1->EVENTS_COMPARE[0] = 0;
164 NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk;
165 invokeCallback();
166 }
167 }
168
169 void us_ticker_init(void)
170 {
171 if (us_ticker_inited) {
172 return;
173 }
174
175 rtc1_start();
176 us_ticker_inited = true;
177 }
178
179 uint32_t us_ticker_read()
180 {
181 if (!us_ticker_inited) {
182 us_ticker_init();
183 }
184
185 /* Return a pseudo microsecond counter value. This is only as precise as the
186 * 32khz low-freq clock source, but could be adequate.*/
187 return RTC_UNITS_TO_MICROSECONDS(rtc1_getCounter64());
188 }
189
190 /**
191 * Setup the us_ticker callback interrupt to go at the given timestamp.
192 *
193 * @Note: Only one callback is pending at any time.
194 *
195 * @Note: If a callback is pending, and this function is called again, the new
196 * callback-time overrides the existing callback setting. It is the caller's
197 * responsibility to ensure that this function is called to setup a callback for
198 * the earliest timeout.
199 *
200 * @Note: If this function is used to setup an interrupt which is immediately
201 * pending--such as for 'now' or a time in the past,--then the callback is
202 * invoked a few ticks later.
203 */
204 void us_ticker_set_interrupt(timestamp_t timestamp)
205 {
206 if (!us_ticker_inited) {
207 us_ticker_init();
208 }
209
210 /*
211 * The argument to this function is a 32-bit microsecond timestamp for when
212 * a callback should be invoked. On the nRF51, we use an RTC timer running
213 * at 32kHz to implement a low-power us-ticker. This results in a problem
214 * based on the fact that 1000000 is not a multiple of 32768.
215 *
216 * Going from a micro-second based timestamp to a 32kHz based RTC-time is a
217 * linear mapping; but this mapping doesn't preserve wraparounds--i.e. when
218 * the 32-bit micro-second timestamp wraps around unfortunately the
219 * underlying RTC counter doesn't. The result is that timestamp expiry
220 * checks on micro-second timestamps don't yield the same result when
221 * applied on the corresponding RTC timestamp values.
222 *
223 * One solution is to translate the incoming 32-bit timestamp into a virtual
224 * 64-bit timestamp based on the knowledge of system-uptime, and then use
225 * this wraparound-free 64-bit value to do a linear mapping to RTC time.
226 * System uptime on an nRF is maintained using the 24-bit RTC counter. We
227 * track the overflow count to extend the 24-bit hardware counter by an
228 * additional 32 bits. RTC_UNITS_TO_MICROSECONDS() converts this into
229 * microsecond units (in 64-bits).
230 */
231 const uint64_t currentTime64 = RTC_UNITS_TO_MICROSECONDS(rtc1_getCounter64());
232 uint64_t timestamp64 = (currentTime64 & ~(uint64_t)0xFFFFFFFFULL) + timestamp;
233 if (((uint32_t)currentTime64 > 0x80000000) && (timestamp < 0x80000000)) {
234 timestamp64 += (uint64_t)0x100000000ULL;
235 }
236 uint32_t newCallbackTime = MICROSECONDS_TO_RTC_UNITS(timestamp64);
237
238 /* Check for repeat setup of an existing callback. This is actually not
239 * important; the following code should work even without this check. */
240 if (us_ticker_callbackPending && (newCallbackTime == us_ticker_callbackTimestamp)) {
241 return;
242 }
243
244 /* Check for callbacks which are immediately (or will *very* shortly become) pending.
245 * Even if they are immediately pending, they are scheduled to trigger a few
246 * ticks later. This keeps things simple by invoking the callback from an
247 * independent interrupt context. */
248 if ((int)(newCallbackTime - rtc1_getCounter()) <= (int)FUZZY_RTC_TICKS) {
249 newCallbackTime = rtc1_getCounter() + FUZZY_RTC_TICKS;
250 }
251
252 NRF_RTC1->CC[0] = newCallbackTime & MAX_RTC_COUNTER_VAL;
253 us_ticker_callbackTimestamp = newCallbackTime;
254 if (!us_ticker_callbackPending) {
255 us_ticker_callbackPending = true;
256 rtc1_enableCompareInterrupt();
257 }
258 }
259
260 void us_ticker_disable_interrupt(void)
261 {
262 if (us_ticker_callbackPending) {
263 rtc1_disableCompareInterrupt();
264 us_ticker_callbackPending = false;
265 }
266 }
267
268 void us_ticker_clear_interrupt(void)
269 {
270 NRF_RTC1->EVENTS_OVRFLW = 0;
271 NRF_RTC1->EVENTS_COMPARE[0] = 0;
272 }
Imprint / Impressum