]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_EFM32_Pearl_Gecko_Simplicity_Studio/Low_Power_Demo/low_power_tick_management_RTCC.c
Update to MIT licensed FreeRTOS V10.0.0 - see https://www.freertos.org/History.txt
[freertos] / FreeRTOS / Demo / CORTEX_EFM32_Pearl_Gecko_Simplicity_Studio / Low_Power_Demo / low_power_tick_management_RTCC.c
1 /*\r
2  * FreeRTOS Kernel V10.0.0\r
3  * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
4  *\r
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
6  * this software and associated documentation files (the "Software"), to deal in\r
7  * the Software without restriction, including without limitation the rights to\r
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
9  * the Software, and to permit persons to whom the Software is furnished to do so,\r
10  * subject to the following conditions:\r
11  *\r
12  * The above copyright notice and this permission notice shall be included in all\r
13  * copies or substantial portions of the Software. If you wish to use our Amazon\r
14  * FreeRTOS name, please do so in a fair use way that does not cause confusion.\r
15  *\r
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
18  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
19  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
20  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
22  *\r
23  * http://www.FreeRTOS.org\r
24  * http://aws.amazon.com/freertos\r
25  *\r
26  * 1 tab == 4 spaces!\r
27  */\r
28 \r
29 /* Standard inlcludes. */\r
30 #include <limits.h>\r
31 \r
32 /* FreeRTOS includes. */\r
33 #include "FreeRTOS.h"\r
34 #include "task.h"\r
35 \r
36 /* SiLabs library includes. */\r
37 #include "em_cmu.h"\r
38 #include "em_rtcc.h"\r
39 #include "em_rmu.h"\r
40 #include "em_int.h"\r
41 #include "em_letimer.h"\r
42 #include "sleep.h"\r
43 \r
44 /* SEE THE COMMENTS ABOVE THE DEFINITION OF configCREATE_LOW_POWER_DEMO IN\r
45 FreeRTOSConfig.h\r
46 This file contains functions that will override the default implementations\r
47 in the RTOS port layer.  Therefore only build this file if the low power demo\r
48 is being built. */\r
49 #if( configCREATE_LOW_POWER_DEMO == 1 )\r
50 \r
51 /* When lpUSE_TEST_TIMER is 1 a second timer will be used to bring the MCU out\r
52 of its low power state before the expected idle time has completed.  This is\r
53 done purely for test coverage purposes. */\r
54 #define lpUSE_TEST_TIMER        ( 0 )\r
55 \r
56 /* The RTCC channel used to generate the tick interrupt. */\r
57 #define lpRTCC_CHANNEL          ( 1 )\r
58 \r
59 /* 32768 clock divided by 1.  Don't use a prescale if errata RTCC_E201\r
60 applies. */\r
61 #define mainTIMER_FREQUENCY_HZ  ( 32768UL )\r
62 \r
63 /*\r
64  * The low power demo does not use the SysTick, so override the\r
65  * vPortSetupTickInterrupt() function with an implementation that configures\r
66  * a low power clock source.  NOTE:  This function name must not be changed as\r
67  * it is called from the RTOS portable layer.\r
68  */\r
69 void vPortSetupTimerInterrupt( void );\r
70 \r
71 /*\r
72  * Override the default definition of vPortSuppressTicksAndSleep() that is\r
73  * weakly defined in the FreeRTOS Cortex-M port layer with a version that\r
74  * manages the RTC clock, as the tick is generated from the low power RTC\r
75  * and not the SysTick as would normally be the case on a Cortex-M.\r
76  */\r
77 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime );\r
78 \r
79 /*-----------------------------------------------------------*/\r
80 \r
81 /* Calculate how many clock increments make up a single tick period. */\r
82 static const uint32_t ulReloadValueForOneTick = ( mainTIMER_FREQUENCY_HZ / configTICK_RATE_HZ );\r
83 \r
84 /* Will hold the maximum number of ticks that can be suppressed. */\r
85 static uint32_t xMaximumPossibleSuppressedTicks = 0;\r
86 \r
87 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
88 sleep mode was exited because of a timer interrupt or a different interrupt. */\r
89 static volatile uint32_t ulTickFlag = pdFALSE;\r
90 \r
91 /* As the clock is only 32KHz, it is likely a value of 1 will be enough. */\r
92 static const uint32_t ulStoppedTimerCompensation = 0UL;\r
93 \r
94 /* RTCC configuration structures. */\r
95 static const RTCC_Init_TypeDef xRTCInitStruct =\r
96 {\r
97         false,                /* Don't start counting when init complete. */\r
98         false,                /* Disable counter during debug halt. */\r
99         false,                /* Don't care. */\r
100         true,                 /* Enable counter wrap on ch. 1 CCV value. */\r
101         rtccCntPresc_1,       /* NOTE:  Do not use a pre-scale if errata RTCC_E201 applies. */\r
102         rtccCntTickPresc,     /* Count using the clock input directly. */\r
103 #if defined(_RTCC_CTRL_BUMODETSEN_MASK)\r
104         false,                /* Disable storing RTCC counter value in RTCC_CCV2 upon backup mode entry. */\r
105 #endif\r
106         false,                /* Oscillator fail detection disabled. */\r
107         rtccCntModeNormal,    /* Use RTCC in normal mode (increment by 1 on each tick) and not in calendar mode. */\r
108         false                 /* Don't care. */\r
109 };\r
110 \r
111 static const RTCC_CCChConf_TypeDef xRTCCChannel1InitStruct =\r
112 {\r
113         rtccCapComChModeCompare,    /* Use Compare mode. */\r
114         rtccCompMatchOutActionPulse,/* Don't care. */\r
115         rtccPRSCh0,                 /* PRS not used. */\r
116         rtccInEdgeNone,             /* Capture Input not used. */\r
117         rtccCompBaseCnt,            /* Compare with Base CNT register. */\r
118         0,                          /* Compare mask. */\r
119         rtccDayCompareModeMonth     /* Don't care. */\r
120 };\r
121 \r
122 /*-----------------------------------------------------------*/\r
123 \r
124 void vPortSetupTimerInterrupt( void )\r
125 {\r
126         /* Configure the RTCC to generate the RTOS tick interrupt. */\r
127 \r
128         /* The maximum number of ticks that can be suppressed depends on the clock\r
129         frequency. */\r
130         xMaximumPossibleSuppressedTicks = ULONG_MAX / ulReloadValueForOneTick;\r
131 \r
132         /* Ensure LE modules are accessible. */\r
133         CMU_ClockEnable( cmuClock_CORELE, true );\r
134 \r
135         /* Use LFXO. */\r
136         CMU_ClockSelectSet( cmuClock_LFE, cmuSelect_LFXO );\r
137 \r
138         /* Enable clock to the RTC module. */\r
139         CMU_ClockEnable( cmuClock_RTCC, true );\r
140 \r
141         /* Use channel 1 to generate the RTOS tick interrupt. */\r
142         RTCC_ChannelCCVSet( lpRTCC_CHANNEL, ulReloadValueForOneTick );\r
143 \r
144         RTCC_Init( &xRTCInitStruct );\r
145         RTCC_ChannelInit( lpRTCC_CHANNEL, &xRTCCChannel1InitStruct );\r
146         RTCC_EM4WakeupEnable( true );\r
147 \r
148         /* Disable RTCC interrupt. */\r
149         RTCC_IntDisable( _RTCC_IF_MASK );\r
150         RTCC_IntClear( _RTCC_IF_MASK );\r
151         RTCC->CNT = _RTCC_CNT_RESETVALUE;\r
152 \r
153         /* The tick interrupt must be set to the lowest priority possible. */\r
154         NVIC_SetPriority( RTCC_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY );\r
155         NVIC_ClearPendingIRQ( RTCC_IRQn );\r
156         NVIC_EnableIRQ( RTCC_IRQn );\r
157         RTCC_IntEnable( RTCC_IEN_CC1 );\r
158         RTCC_Enable( true );\r
159 \r
160         #if( lpUSE_TEST_TIMER == 1 )\r
161         {\r
162                 void prvSetupTestTimer( void );\r
163 \r
164                 /* A second timer is used to test the path where the MCU is brought out\r
165                 of a low power state by a timer other than the tick timer. */\r
166                 prvSetupTestTimer();\r
167         }\r
168         #endif\r
169 }\r
170 /*-----------------------------------------------------------*/\r
171 \r
172 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
173 {\r
174 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCountAfterSleep;\r
175 eSleepModeStatus eSleepAction;\r
176 TickType_t xModifiableIdleTime;\r
177 \r
178         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
179 \r
180         /* Make sure the RTC reload value does not overflow the counter. */\r
181         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
182         {\r
183                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
184         }\r
185 \r
186         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
187         periods. */\r
188         ulReloadValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
189         if( ulReloadValue > ulStoppedTimerCompensation )\r
190         {\r
191                 /* Compensate for the fact that the RTC is going to be stopped\r
192                 momentarily. */\r
193                 ulReloadValue -= ulStoppedTimerCompensation;\r
194         }\r
195 \r
196         /* Stop the RTC momentarily.  The time the RTC is stopped for is accounted\r
197         for as best it can be, but using the tickless mode will inevitably result\r
198         in some tiny drift of the time maintained by the kernel with respect to\r
199         calendar time. */\r
200         RTCC_Enable( false );\r
201 \r
202         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
203         that will mask interrupts that should exit sleep mode. */\r
204         INT_Disable();\r
205         __asm volatile( "dsb" );\r
206         __asm volatile( "isb" );\r
207 \r
208         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
209         mode is exited then sleep mode was probably exited because the tick was\r
210         suppressed for the entire xExpectedIdleTime period. */\r
211         ulTickFlag = pdFALSE;\r
212 \r
213         /* If a context switch is pending then abandon the low power entry as the\r
214         context switch might have been pended by an external interrupt that     requires\r
215         processing. */\r
216         eSleepAction = eTaskConfirmSleepModeStatus();\r
217         if( eSleepAction == eAbortSleep )\r
218         {\r
219                 /* Restart tick and continue counting to complete the current time\r
220                 slice. */\r
221                 RTCC_Enable( true );\r
222 \r
223                 /* Re-enable interrupts - see comments above the RTCC_Enable() call\r
224                 above. */\r
225                 INT_Enable();\r
226         }\r
227         else\r
228         {\r
229                 RTCC_ChannelCCVSet( lpRTCC_CHANNEL, ulReloadValue );\r
230 \r
231                 /* Restart the RTC. */\r
232                 RTCC_Enable( true );\r
233 \r
234                 /* Allow the application to define some pre-sleep processing. */\r
235                 xModifiableIdleTime = xExpectedIdleTime;\r
236                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
237 \r
238                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
239                 means the application defined code has already executed the WAIT\r
240                 instruction. */\r
241                 if( xModifiableIdleTime > 0 )\r
242                 {\r
243                         __asm volatile( "dsb" );\r
244                         SLEEP_Sleep();\r
245                         __asm volatile( "isb" );\r
246                 }\r
247 \r
248                 /* Allow the application to define some post sleep processing. */\r
249                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
250 \r
251                 /* Stop RTC.  Again, the time the SysTick is stopped for is accounted\r
252                 for as best it can be, but using the tickless mode will inevitably\r
253                 result in some tiny drift of the time maintained by the kernel with\r
254                 respect to calendar time. */\r
255                 RTCC_Enable( false );\r
256                 ulCountAfterSleep = RTCC_CounterGet();\r
257 \r
258                 /* Re-enable interrupts - see comments above the INT_Enable() call\r
259                 above. */\r
260                 INT_Enable();\r
261                 __asm volatile( "dsb" );\r
262                 __asm volatile( "isb" );\r
263 \r
264                 if( ulTickFlag != pdFALSE )\r
265                 {\r
266                         /* The tick interrupt has already executed, although because this\r
267                         function is called with the scheduler suspended the actual tick\r
268                         processing will not occur until after this function has exited.\r
269                         The tick interrupt handler will already have pended the tick\r
270                         processing in the kernel.  As the pending tick will be processed as\r
271                         soon as this function exits, the tick value     maintained by the tick\r
272                         is stepped forward by one less than the time spent sleeping.  The\r
273                         actual stepping of the tick appears later in this function. */\r
274                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
275 \r
276                         /* The interrupt should have reset the CCV value. */\r
277                         configASSERT( RTCC_ChannelCCVGet( lpRTCC_CHANNEL ) == ulReloadValueForOneTick );\r
278                 }\r
279                 else\r
280                 {\r
281                         /* Something other than the tick interrupt ended the sleep.  How\r
282                         many complete tick periods passed while the processor was\r
283                         sleeping? */\r
284                         ulCompleteTickPeriods = ulCountAfterSleep / ulReloadValueForOneTick;\r
285 \r
286                         /* The next interrupt is configured to occur at whatever fraction of\r
287                         the current tick period remains by setting the reload value back to\r
288                         that required for one tick, and truncating the count to remove the\r
289                         counts that are greater than the reload value. */\r
290                         RTCC_ChannelCCVSet( lpRTCC_CHANNEL, ulReloadValueForOneTick );\r
291                         ulCountAfterSleep %= ulReloadValueForOneTick;\r
292                         RTCC_CounterSet( ulCountAfterSleep );\r
293                 }\r
294 \r
295                 /* Restart the RTC so it runs up to the alarm value.  The alarm value\r
296                 will get set to the value required to generate exactly one tick period\r
297                 the next time the RTC interrupt executes. */\r
298                 RTCC_Enable( true );\r
299 \r
300                 /* Wind the tick forward by the number of tick periods that the CPU\r
301                 remained in a low power state. */\r
302                 vTaskStepTick( ulCompleteTickPeriods );\r
303         }\r
304 }\r
305 /*-----------------------------------------------------------*/\r
306 \r
307 void RTCC_IRQHandler( void )\r
308 {\r
309         ulTickFlag = pdTRUE;\r
310 \r
311         if( RTCC_ChannelCCVGet( lpRTCC_CHANNEL ) != ulReloadValueForOneTick )\r
312         {\r
313                 /* Set RTC interrupt to one RTOS tick period. */\r
314                 RTCC_Enable( false );\r
315                 RTCC_ChannelCCVSet( lpRTCC_CHANNEL, ulReloadValueForOneTick );\r
316                 RTCC_Enable( true );\r
317         }\r
318 \r
319         RTCC_IntClear( _RTCC_IF_MASK );\r
320 \r
321         /* Critical section which protect incrementing the tick*/\r
322         portDISABLE_INTERRUPTS();\r
323         {\r
324                 if( xTaskIncrementTick() != pdFALSE )\r
325                 {\r
326                         /* Pend a context switch. */\r
327                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
328                 }\r
329         }\r
330         portENABLE_INTERRUPTS();\r
331 }\r
332 /*-----------------------------------------------------------*/\r
333 \r
334 #if( lpUSE_TEST_TIMER == 1 )\r
335 \r
336         /* Juse used to ensure the second timer is executing. */\r
337         volatile uint32_t ulLETimerIncrements = 0;\r
338 \r
339         void LETIMER0_IRQHandler( void )\r
340         {\r
341                 /* This ISR is used purely to bring the MCU out of sleep mode - it has\r
342                 no other purpose. */\r
343                 ulLETimerIncrements++;\r
344                 LETIMER_IntClear( LETIMER0, LETIMER_IF_COMP0 );\r
345         }\r
346 \r
347 #endif /* lpUSE_TEST_TIMER == 1 */\r
348 /*-----------------------------------------------------------*/\r
349 \r
350 #if( lpUSE_TEST_TIMER == 1 )\r
351 \r
352         /* Set up a timer that used used to bring the MCU out of sleep mode using\r
353         an interrupt other than the tick interrupt.  This is done for code coverage\r
354         puposes only. */\r
355         void prvSetupTestTimer( void )\r
356         {\r
357         static const LETIMER_Init_TypeDef xLETimerInitStruct =\r
358         {\r
359                 true,               /* Enable timer when init complete. */\r
360                 false,              /* Stop counter during debug halt. */\r
361                 true,               /* Load COMP0 into CNT on underflow. */\r
362                 false,              /* Do not load COMP1 into COMP0 when REP0 reaches 0. */\r
363                 0,                  /* Idle value 0 for output 0. */\r
364                 0,                  /* Idle value 0 for output 1. */\r
365                 letimerUFOANone,    /* No action on underflow on output 0. */\r
366                 letimerUFOANone,    /* No action on underflow on output 1. */\r
367                 letimerRepeatFree   /* Count until stopped by SW. */\r
368         };\r
369         const uint32_t ulCompareMatch = 32768UL / 10UL;\r
370 \r
371                 CMU_ClockSelectSet( cmuClock_LFA, cmuSelect_LFXO );\r
372                 CMU_ClockEnable( cmuClock_LETIMER0, true );\r
373 \r
374                 LETIMER_CompareSet( LETIMER0, 0, ulCompareMatch );\r
375                 LETIMER_IntEnable( LETIMER0, LETIMER_IF_COMP0 );\r
376                 NVIC_EnableIRQ( LETIMER0_IRQn );\r
377                 LETIMER_Init( LETIMER0, &xLETimerInitStruct);\r
378         }\r
379 \r
380 #endif /* lpUSE_TEST_TIMER == 1 */\r
381 \r
382 \r
383 \r
384 \r
385 #endif /* ( configCREATE_LOW_POWER_DEMO == 1 ) */\r