]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_STM32L152_Discovery_IAR/STM32L_low_power_tick_management.c
2a89df8f54a96c424d11d01fad056730f21cf09c
[freertos] / FreeRTOS / Demo / CORTEX_STM32L152_Discovery_IAR / STM32L_low_power_tick_management.c
1 /*\r
2     FreeRTOS V8.0.0:rc1 - Copyright (C) 2014 Real Time Engineers Ltd.\r
3     All rights reserved\r
4 \r
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     ***************************************************************************\r
8      *                                                                       *\r
9      *    FreeRTOS provides completely free yet professionally developed,    *\r
10      *    robust, strictly quality controlled, supported, and cross          *\r
11      *    platform software that has become a de facto standard.             *\r
12      *                                                                       *\r
13      *    Help yourself get started quickly and support the FreeRTOS         *\r
14      *    project by purchasing a FreeRTOS tutorial book, reference          *\r
15      *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
16      *                                                                       *\r
17      *    Thank you!                                                         *\r
18      *                                                                       *\r
19     ***************************************************************************\r
20 \r
21     This file is part of the FreeRTOS distribution.\r
22 \r
23     FreeRTOS is free software; you can redistribute it and/or modify it under\r
24     the terms of the GNU General Public License (version 2) as published by the\r
25     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
26 \r
27     >>! NOTE: The modification to the GPL is included to allow you to distribute\r
28     >>! a combined work that includes FreeRTOS without being obliged to provide\r
29     >>! the source code for proprietary components outside of the FreeRTOS\r
30     >>! kernel.\r
31 \r
32     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
33     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
34     FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
35     link: http://www.freertos.org/a00114.html\r
36 \r
37     1 tab == 4 spaces!\r
38 \r
39     ***************************************************************************\r
40      *                                                                       *\r
41      *    Having a problem?  Start by reading the FAQ "My application does   *\r
42      *    not run, what could be wrong?"                                     *\r
43      *                                                                       *\r
44      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
45      *                                                                       *\r
46     ***************************************************************************\r
47 \r
48     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
49     license and Real Time Engineers Ltd. contact details.\r
50 \r
51     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
52     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
53     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
54 \r
55     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
56     Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
57     licenses offer ticketed support, indemnification and middleware.\r
58 \r
59     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
60     engineered and independently SIL3 certified version for use in safety and\r
61     mission critical applications that require provable dependability.\r
62 \r
63     1 tab == 4 spaces!\r
64 */\r
65 \r
66 /* Standard includes. */\r
67 #include <limits.h>\r
68 \r
69 /* FreeRTOS includes. */\r
70 #include "FreeRTOS.h"\r
71 #include "task.h"\r
72 \r
73 /* ST library functions. */\r
74 #include "stm32l1xx.h"\r
75 \r
76 /*\r
77  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
78  * is generated by the TIM2 peripheral.  The TIM2 configuration and handling\r
79  * functions are defined in this file.  Note the RTC is not used as there does\r
80  * not appear to be a way to read back the RTC count value, and therefore the\r
81  * only way of knowing exactly how long a sleep lasted is to use the very low\r
82  * resolution calendar time.\r
83  *\r
84  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
85  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
86  * SysTick timer.\r
87  */\r
88 #if configCREATE_LOW_POWER_DEMO == 1\r
89 \r
90 /* The frequency at which TIM2 will run. */\r
91 #define lpCLOCK_INPUT_FREQUENCY         ( 1000UL )\r
92 \r
93 /* STM32 register used to ensure the TIM2 clock stops when the MCU is in debug\r
94 mode. */\r
95 #define DBGMCU_APB1_FZ  ( * ( ( volatile unsigned long * ) 0xE0042008 ) )\r
96 \r
97 /*-----------------------------------------------------------*/\r
98 \r
99 /*\r
100  * The tick interrupt is generated by the TIM2 timer.\r
101  */\r
102 void TIM2_IRQHandler( void );\r
103 \r
104 /*-----------------------------------------------------------*/\r
105 \r
106 /* Calculate how many clock increments make up a single tick period. */\r
107 static const uint32_t ulReloadValueForOneTick = ( ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ ) - 1 );\r
108 \r
109 /* Holds the maximum number of ticks that can be suppressed - which is\r
110 basically how far into the future an interrupt can be generated. Set during\r
111 initialisation. */\r
112 static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
113 \r
114 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
115 sleep mode was exited because of an tick interrupt or a different interrupt. */\r
116 static volatile uint32_t ulTickFlag = pdFALSE;\r
117 \r
118 /*-----------------------------------------------------------*/\r
119 \r
120 /* The tick interrupt handler.  This is always the same other than the part that\r
121 clears the interrupt, which is specific to the clock being used to generate the\r
122 tick. */\r
123 void TIM2_IRQHandler( void )\r
124 {\r
125         /* Clear the interrupt. */\r
126         TIM_ClearITPendingBit( TIM2, TIM_IT_Update );\r
127 \r
128         /* The next block of code is from the standard FreeRTOS tick interrupt\r
129         handler.  The standard handler is not called directly in case future\r
130         versions contain changes that make it no longer suitable for calling\r
131         here. */\r
132         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
133         {\r
134                 if( xTaskIncrementTick() != pdFALSE )\r
135                 {\r
136                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
137                 }\r
138 \r
139                 /* Just completely clear the interrupt mask on exit by passing 0 because\r
140                 it is known that this interrupt will only ever execute with the lowest\r
141                 possible interrupt priority. */\r
142         }\r
143         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
144 \r
145         /* In case this is the first tick since the MCU left a low power mode the\r
146         reload value is reset to its default. */\r
147         TIM2->ARR = ( uint16_t ) ulReloadValueForOneTick;\r
148 \r
149         /* The CPU woke because of a tick. */\r
150         ulTickFlag = pdTRUE;\r
151 }\r
152 /*-----------------------------------------------------------*/\r
153 \r
154 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
155 defined in the FreeRTOS Cortex-M3 port layer with a version that configures TIM2\r
156 to generate the tick interrupt. */\r
157 void vPortSetupTimerInterrupt( void )\r
158 {\r
159 NVIC_InitTypeDef NVIC_InitStructure;\r
160 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;\r
161 \r
162         /* Enable the TIM2 clock. */\r
163         RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE );\r
164 \r
165         /* Ensure clock stops in debug mode. */\r
166         DBGMCU_APB1_FZ |= DBGMCU_APB1_FZ_DBG_TIM2_STOP;\r
167 \r
168         /* Scale the clock so longer tickless periods can be achieved.  The     SysTick\r
169         is not used as even when its frequency is divided by 8 the maximum tickless\r
170         period with a system clock of 16MHz is only 8.3 seconds.  Using a prescaled\r
171         clock on the 16-bit TIM2 allows a tickless period of nearly     66 seconds,\r
172         albeit at low resolution. */\r
173         TIM_TimeBaseStructure.TIM_Prescaler = ( uint16_t ) ( SystemCoreClock / lpCLOCK_INPUT_FREQUENCY );\r
174         TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;\r
175         TIM_TimeBaseStructure.TIM_Period = ( uint16_t ) ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ );\r
176         TIM_TimeBaseStructure.TIM_ClockDivision = 0;\r
177         TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure );\r
178 \r
179         /* Enable the TIM2 interrupt.  This must execute at the lowest interrupt\r
180         priority. */\r
181         NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;\r
182         NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY; /* Must be set to lowest priority. */\r
183         NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;\r
184         NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;\r
185         NVIC_Init(&NVIC_InitStructure);\r
186         TIM_ITConfig( TIM2, TIM_IT_Update, ENABLE );\r
187         TIM_SetCounter( TIM2, 0 );\r
188         TIM_Cmd( TIM2, ENABLE );\r
189 \r
190         /* See the comments where xMaximumPossibleSuppressedTicks is declared. */\r
191         xMaximumPossibleSuppressedTicks = ( ( unsigned long ) USHRT_MAX ) / ulReloadValueForOneTick;\r
192 }\r
193 /*-----------------------------------------------------------*/\r
194 \r
195 /* Override the default definition of vPortSuppressTicksAndSleep() that is\r
196 weakly defined in the FreeRTOS Cortex-M3 port layer with a version that manages\r
197 the TIM2 interrupt, as the tick is generated from TIM2 compare matches events. */\r
198 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
199 {\r
200 uint32_t ulCounterValue, ulCompleteTickPeriods;\r
201 eSleepModeStatus eSleepAction;\r
202 TickType_t xModifiableIdleTime;\r
203 const TickType_t xRegulatorOffIdleTime = 30;\r
204 \r
205         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
206 \r
207         /* Make sure the TIM2 reload value does not overflow the counter. */\r
208         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
209         {\r
210                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
211         }\r
212 \r
213         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
214         periods. */\r
215         ulCounterValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
216 \r
217         /* Stop TIM2 momentarily.  The time TIM2 is stopped for is not accounted for\r
218         in this implementation (as it is in the generic implementation) because the\r
219         clock is so slow it is unlikely to be stopped for a complete count period\r
220         anyway. */\r
221         TIM_Cmd( TIM2, DISABLE );\r
222 \r
223         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
224         that will mask interrupts that should exit sleep mode. */\r
225         __asm volatile ( "cpsid i" );\r
226         __asm volatile ( "dsb" );\r
227         __asm volatile ( "isb" );\r
228 \r
229         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
230         mode is exited then sleep mode was probably exited because the tick was\r
231         suppressed for the entire xExpectedIdleTime period. */\r
232         ulTickFlag = pdFALSE;\r
233 \r
234         /* If a context switch is pending then abandon the low power entry as\r
235         the context switch might have been pended by an external interrupt that\r
236         requires processing. */\r
237         eSleepAction = eTaskConfirmSleepModeStatus();\r
238         if( eSleepAction == eAbortSleep )\r
239         {\r
240                 /* Restart tick. */\r
241                 TIM_Cmd( TIM2, ENABLE );\r
242 \r
243                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
244                 above. */\r
245                 __asm volatile ( "cpsie i" );\r
246         }\r
247         else if( eSleepAction == eNoTasksWaitingTimeout )\r
248         {\r
249                 /* A user definable macro that allows application code to be inserted\r
250                 here.  Such application code can be used to minimise power consumption\r
251                 further by turning off IO, peripheral clocks, the Flash, etc. */\r
252                 configPRE_STOP_PROCESSING();\r
253 \r
254                 /* There are no running state tasks and no tasks that are blocked with a\r
255                 time out.  Assuming the application does not care if the tick time slips\r
256                 with respect to calendar time then enter a deep sleep that can only be\r
257                 woken by (in this demo case) the user button being pushed on the\r
258                 STM32L discovery board.  If the application does require the tick time\r
259                 to keep better track of the calender time then the RTC peripheral can be\r
260                 used to make rough adjustments. */\r
261                 PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
262 \r
263                 /* A user definable macro that allows application code to be inserted\r
264                 here.  Such application code can be used to reverse any actions taken\r
265                 by the configPRE_STOP_PROCESSING().  In this demo\r
266                 configPOST_STOP_PROCESSING() is used to re-initialise the clocks that\r
267                 were turned off when STOP mode was entered. */\r
268                 configPOST_STOP_PROCESSING();\r
269 \r
270                 /* Restart tick. */\r
271                 TIM_SetCounter( TIM2, 0 );\r
272                 TIM_Cmd( TIM2, ENABLE );\r
273 \r
274                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
275                 above. */\r
276                 __asm volatile ( "cpsie i" );\r
277         }\r
278         else\r
279         {\r
280                 /* Trap underflow before the next calculation. */\r
281                 configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) );\r
282 \r
283                 /* Adjust the TIM2 value to take into account that the current time\r
284                 slice is already partially complete. */\r
285                 ulCounterValue -= ( uint32_t ) TIM_GetCounter( TIM2 );\r
286 \r
287                 /* Trap overflow/underflow before the calculated value is written to\r
288                 TIM2. */\r
289                 configASSERT( ulCounterValue < ( uint32_t ) USHRT_MAX );\r
290                 configASSERT( ulCounterValue != 0 );\r
291 \r
292                 /* Update to use the calculated overflow value. */\r
293                 TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
294                 TIM_SetCounter( TIM2, 0 );\r
295 \r
296                 /* Restart the TIM2. */\r
297                 TIM_Cmd( TIM2, ENABLE );\r
298 \r
299                 /* Allow the application to define some pre-sleep processing.  This is\r
300                 the standard configPRE_SLEEP_PROCESSING() macro as described on the\r
301                 FreeRTOS.org website. */\r
302                 xModifiableIdleTime = xExpectedIdleTime;\r
303                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
304 \r
305                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
306                 means the application defined code has already executed the wait/sleep\r
307                 instruction. */\r
308                 if( xModifiableIdleTime > 0 )\r
309                 {\r
310                         /* The sleep mode used is dependent on the expected idle time\r
311                         as the deeper the sleep the longer the wake up time.  See the\r
312                         comments at the top of main_low_power.c.  Note xRegulatorOffIdleTime\r
313                         is set purely for convenience of demonstration and is not intended\r
314                         to be an optimised value. */\r
315                         if( xModifiableIdleTime > xRegulatorOffIdleTime )\r
316                         {\r
317                                 /* A slightly lower power sleep mode with a longer wake up\r
318                                 time. */\r
319                                 PWR_EnterSleepMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
320                         }\r
321                         else\r
322                         {\r
323                                 /* A slightly higher power sleep mode with a faster wake up\r
324                                 time. */\r
325                                 PWR_EnterSleepMode( PWR_Regulator_ON, PWR_SLEEPEntry_WFI );\r
326                         }\r
327                 }\r
328 \r
329                 /* Allow the application to define some post sleep processing.  This is\r
330                 the standard configPOST_SLEEP_PROCESSING() macro, as described on the\r
331                 FreeRTOS.org website. */\r
332                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
333 \r
334                 /* Stop TIM2.  Again, the time the clock is stopped for in not accounted\r
335                 for here (as it would normally be) because the clock is so slow it is\r
336                 unlikely it will be stopped for a complete count period anyway. */\r
337                 TIM_Cmd( TIM2, DISABLE );\r
338 \r
339                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
340                 above. */\r
341                 __asm volatile ( "cpsie i" );\r
342                 __asm volatile ( "dsb" );\r
343                 __asm volatile ( "isb" );\r
344 \r
345                 if( ulTickFlag != pdFALSE )\r
346                 {\r
347                         /* Trap overflows before the next calculation. */\r
348                         configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) );\r
349 \r
350                         /* The tick interrupt has already executed, although because this\r
351                         function is called with the scheduler suspended the actual tick\r
352                         processing will not occur until after this function has exited.\r
353                         Reset the reload value with whatever remains of this tick period. */\r
354                         ulCounterValue = ulReloadValueForOneTick - ( uint32_t ) TIM_GetCounter( TIM2 );\r
355 \r
356                         /* Trap under/overflows before the calculated value is used. */\r
357                         configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
358                         configASSERT( ulCounterValue != 0 );\r
359 \r
360                         /* Use the calculated reload value. */\r
361                         TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
362                         TIM_SetCounter( TIM2, 0 );\r
363 \r
364                         /* The tick interrupt handler will already have pended the tick\r
365                         processing in the kernel.  As the pending tick will be processed as\r
366                         soon as this function exits, the tick value     maintained by the tick\r
367                         is stepped forward by one less than the time spent sleeping.  The\r
368                         actual stepping of the tick appears later in this function. */\r
369                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
370                 }\r
371                 else\r
372                 {\r
373                         /* Something other than the tick interrupt ended the sleep.  How\r
374                         many complete tick periods passed while the processor was\r
375                         sleeping? */\r
376                         ulCompleteTickPeriods = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) / ulReloadValueForOneTick;\r
377 \r
378                         /* Check for over/under flows before the following calculation. */\r
379                         configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) );\r
380 \r
381                         /* The reload value is set to whatever fraction of a single tick\r
382                         period remains. */\r
383                         ulCounterValue = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) - ( ulCompleteTickPeriods * ulReloadValueForOneTick );\r
384                         configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
385                         if( ulCounterValue == 0 )\r
386                         {\r
387                                 /* There is no fraction remaining. */\r
388                                 ulCounterValue = ulReloadValueForOneTick;\r
389                                 ulCompleteTickPeriods++;\r
390                         }\r
391                         TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
392                         TIM_SetCounter( TIM2, 0 );\r
393                 }\r
394 \r
395                 /* Restart TIM2 so it runs up to the reload value.  The reload value\r
396                 will get set to the value required to generate exactly one tick period\r
397                 the next time the TIM2 interrupt executes. */\r
398                 TIM_Cmd( TIM2, ENABLE );\r
399 \r
400                 /* Wind the tick forward by the number of tick periods that the CPU\r
401                 remained in a low power state. */\r
402                 vTaskStepTick( ulCompleteTickPeriods );\r
403         }\r
404 }\r
405 \r
406 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
407 \r