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