]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_STM32L152_Discovery_IAR/STM32L_low_power_tick_management.c
Update to MIT licensed FreeRTOS V10.0.0 - see https://www.freertos.org/History.txt
[freertos] / FreeRTOS / Demo / CORTEX_STM32L152_Discovery_IAR / STM32L_low_power_tick_management.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 includes. */\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 /* ST library functions. */\r
37 #include "stm32l1xx.h"\r
38 \r
39 /*\r
40  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
41  * is generated by the TIM2 peripheral.  The TIM2 configuration and handling\r
42  * functions are defined in this file.  Note the RTC is not used as there does\r
43  * not appear to be a way to read back the RTC count value, and therefore the\r
44  * only way of knowing exactly how long a sleep lasted is to use the very low\r
45  * resolution calendar time.\r
46  *\r
47  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
48  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
49  * SysTick timer.\r
50  */\r
51 #if configCREATE_LOW_POWER_DEMO == 1\r
52 \r
53 /* The frequency at which TIM2 will run. */\r
54 #define lpCLOCK_INPUT_FREQUENCY         ( 1000UL )\r
55 \r
56 /* STM32 register used to ensure the TIM2 clock stops when the MCU is in debug\r
57 mode. */\r
58 #define DBGMCU_APB1_FZ  ( * ( ( volatile unsigned long * ) 0xE0042008 ) )\r
59 \r
60 /*-----------------------------------------------------------*/\r
61 \r
62 /*\r
63  * The tick interrupt is generated by the TIM2 timer.\r
64  */\r
65 void TIM2_IRQHandler( void );\r
66 \r
67 /*-----------------------------------------------------------*/\r
68 \r
69 /* Calculate how many clock increments make up a single tick period. */\r
70 static const uint32_t ulReloadValueForOneTick = ( ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ ) - 1 );\r
71 \r
72 /* Holds the maximum number of ticks that can be suppressed - which is\r
73 basically how far into the future an interrupt can be generated. Set during\r
74 initialisation. */\r
75 static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
76 \r
77 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
78 sleep mode was exited because of an tick interrupt or a different interrupt. */\r
79 static volatile uint32_t ulTickFlag = pdFALSE;\r
80 \r
81 /*-----------------------------------------------------------*/\r
82 \r
83 /* The tick interrupt handler.  This is always the same other than the part that\r
84 clears the interrupt, which is specific to the clock being used to generate the\r
85 tick. */\r
86 void TIM2_IRQHandler( void )\r
87 {\r
88         /* Clear the interrupt. */\r
89         TIM_ClearITPendingBit( TIM2, TIM_IT_Update );\r
90 \r
91         /* The next block of code is from the standard FreeRTOS tick interrupt\r
92         handler.  The standard handler is not called directly in case future\r
93         versions contain changes that make it no longer suitable for calling\r
94         here. */\r
95         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
96         {\r
97                 if( xTaskIncrementTick() != pdFALSE )\r
98                 {\r
99                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
100                 }\r
101 \r
102                 /* Just completely clear the interrupt mask on exit by passing 0 because\r
103                 it is known that this interrupt will only ever execute with the lowest\r
104                 possible interrupt priority. */\r
105         }\r
106         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
107 \r
108         /* In case this is the first tick since the MCU left a low power mode the\r
109         reload value is reset to its default. */\r
110         TIM2->ARR = ( uint16_t ) ulReloadValueForOneTick;\r
111 \r
112         /* The CPU woke because of a tick. */\r
113         ulTickFlag = pdTRUE;\r
114 }\r
115 /*-----------------------------------------------------------*/\r
116 \r
117 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
118 defined in the FreeRTOS Cortex-M3 port layer with a version that configures TIM2\r
119 to generate the tick interrupt. */\r
120 void vPortSetupTimerInterrupt( void )\r
121 {\r
122 NVIC_InitTypeDef NVIC_InitStructure;\r
123 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;\r
124 \r
125         /* Enable the TIM2 clock. */\r
126         RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE );\r
127 \r
128         /* Ensure clock stops in debug mode. */\r
129         DBGMCU_APB1_FZ |= DBGMCU_APB1_FZ_DBG_TIM2_STOP;\r
130 \r
131         /* Scale the clock so longer tickless periods can be achieved.  The     SysTick\r
132         is not used as even when its frequency is divided by 8 the maximum tickless\r
133         period with a system clock of 16MHz is only 8.3 seconds.  Using a prescaled\r
134         clock on the 16-bit TIM2 allows a tickless period of nearly     66 seconds,\r
135         albeit at low resolution. */\r
136         TIM_TimeBaseStructure.TIM_Prescaler = ( uint16_t ) ( SystemCoreClock / lpCLOCK_INPUT_FREQUENCY );\r
137         TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;\r
138         TIM_TimeBaseStructure.TIM_Period = ( uint16_t ) ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ );\r
139         TIM_TimeBaseStructure.TIM_ClockDivision = 0;\r
140         TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure );\r
141 \r
142         /* Enable the TIM2 interrupt.  This must execute at the lowest interrupt\r
143         priority. */\r
144         NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;\r
145         NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY; /* Must be set to lowest priority. */\r
146         NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;\r
147         NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;\r
148         NVIC_Init(&NVIC_InitStructure);\r
149         TIM_ITConfig( TIM2, TIM_IT_Update, ENABLE );\r
150         TIM_SetCounter( TIM2, 0 );\r
151         TIM_Cmd( TIM2, ENABLE );\r
152 \r
153         /* See the comments where xMaximumPossibleSuppressedTicks is declared. */\r
154         xMaximumPossibleSuppressedTicks = ( ( unsigned long ) USHRT_MAX ) / ulReloadValueForOneTick;\r
155 }\r
156 /*-----------------------------------------------------------*/\r
157 \r
158 /* Override the default definition of vPortSuppressTicksAndSleep() that is\r
159 weakly defined in the FreeRTOS Cortex-M3 port layer with a version that manages\r
160 the TIM2 interrupt, as the tick is generated from TIM2 compare matches events. */\r
161 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
162 {\r
163 uint32_t ulCounterValue, ulCompleteTickPeriods;\r
164 eSleepModeStatus eSleepAction;\r
165 TickType_t xModifiableIdleTime;\r
166 const TickType_t xRegulatorOffIdleTime = 30;\r
167 \r
168         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
169 \r
170         /* Make sure the TIM2 reload value does not overflow the counter. */\r
171         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
172         {\r
173                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
174         }\r
175 \r
176         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
177         periods. */\r
178         ulCounterValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
179 \r
180         /* Stop TIM2 momentarily.  The time TIM2 is stopped for is not accounted for\r
181         in this implementation (as it is in the generic implementation) because the\r
182         clock is so slow it is unlikely to be stopped for a complete count period\r
183         anyway. */\r
184         TIM_Cmd( TIM2, DISABLE );\r
185 \r
186         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
187         that will mask interrupts that should exit sleep mode. */\r
188         __asm volatile ( "cpsid i" );\r
189         __asm volatile ( "dsb" );\r
190         __asm volatile ( "isb" );\r
191 \r
192         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
193         mode is exited then sleep mode was probably exited because the tick was\r
194         suppressed for the entire xExpectedIdleTime period. */\r
195         ulTickFlag = pdFALSE;\r
196 \r
197         /* If a context switch is pending then abandon the low power entry as\r
198         the context switch might have been pended by an external interrupt that\r
199         requires processing. */\r
200         eSleepAction = eTaskConfirmSleepModeStatus();\r
201         if( eSleepAction == eAbortSleep )\r
202         {\r
203                 /* Restart tick. */\r
204                 TIM_Cmd( TIM2, ENABLE );\r
205 \r
206                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
207                 above. */\r
208                 __asm volatile ( "cpsie i" );\r
209         }\r
210         else if( eSleepAction == eNoTasksWaitingTimeout )\r
211         {\r
212                 /* A user definable macro that allows application code to be inserted\r
213                 here.  Such application code can be used to minimise power consumption\r
214                 further by turning off IO, peripheral clocks, the Flash, etc. */\r
215                 configPRE_STOP_PROCESSING();\r
216 \r
217                 /* There are no running state tasks and no tasks that are blocked with a\r
218                 time out.  Assuming the application does not care if the tick time slips\r
219                 with respect to calendar time then enter a deep sleep that can only be\r
220                 woken by (in this demo case) the user button being pushed on the\r
221                 STM32L discovery board.  If the application does require the tick time\r
222                 to keep better track of the calender time then the RTC peripheral can be\r
223                 used to make rough adjustments. */\r
224                 PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
225 \r
226                 /* A user definable macro that allows application code to be inserted\r
227                 here.  Such application code can be used to reverse any actions taken\r
228                 by the configPRE_STOP_PROCESSING().  In this demo\r
229                 configPOST_STOP_PROCESSING() is used to re-initialise the clocks that\r
230                 were turned off when STOP mode was entered. */\r
231                 configPOST_STOP_PROCESSING();\r
232 \r
233                 /* Restart tick. */\r
234                 TIM_SetCounter( TIM2, 0 );\r
235                 TIM_Cmd( TIM2, ENABLE );\r
236 \r
237                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
238                 above. */\r
239                 __asm volatile ( "cpsie i" );\r
240                 __asm volatile ( "dsb" );\r
241                 __asm volatile ( "isb" );\r
242         }\r
243         else\r
244         {\r
245                 /* Trap underflow before the next calculation. */\r
246                 configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) );\r
247 \r
248                 /* Adjust the TIM2 value to take into account that the current time\r
249                 slice is already partially complete. */\r
250                 ulCounterValue -= ( uint32_t ) TIM_GetCounter( TIM2 );\r
251 \r
252                 /* Trap overflow/underflow before the calculated value is written to\r
253                 TIM2. */\r
254                 configASSERT( ulCounterValue < ( uint32_t ) USHRT_MAX );\r
255                 configASSERT( ulCounterValue != 0 );\r
256 \r
257                 /* Update to use the calculated overflow value. */\r
258                 TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
259                 TIM_SetCounter( TIM2, 0 );\r
260 \r
261                 /* Restart the TIM2. */\r
262                 TIM_Cmd( TIM2, ENABLE );\r
263 \r
264                 /* Allow the application to define some pre-sleep processing.  This is\r
265                 the standard configPRE_SLEEP_PROCESSING() macro as described on the\r
266                 FreeRTOS.org website. */\r
267                 xModifiableIdleTime = xExpectedIdleTime;\r
268                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
269 \r
270                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
271                 means the application defined code has already executed the wait/sleep\r
272                 instruction. */\r
273                 if( xModifiableIdleTime > 0 )\r
274                 {\r
275                         /* The sleep mode used is dependent on the expected idle time\r
276                         as the deeper the sleep the longer the wake up time.  See the\r
277                         comments at the top of main_low_power.c.  Note xRegulatorOffIdleTime\r
278                         is set purely for convenience of demonstration and is not intended\r
279                         to be an optimised value. */\r
280                         if( xModifiableIdleTime > xRegulatorOffIdleTime )\r
281                         {\r
282                                 /* A slightly lower power sleep mode with a longer wake up\r
283                                 time. */\r
284                                 PWR_EnterSleepMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
285                         }\r
286                         else\r
287                         {\r
288                                 /* A slightly higher power sleep mode with a faster wake up\r
289                                 time. */\r
290                                 PWR_EnterSleepMode( PWR_Regulator_ON, PWR_SLEEPEntry_WFI );\r
291                         }\r
292                 }\r
293 \r
294                 /* Allow the application to define some post sleep processing.  This is\r
295                 the standard configPOST_SLEEP_PROCESSING() macro, as described on the\r
296                 FreeRTOS.org website. */\r
297                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
298 \r
299                 /* Stop TIM2.  Again, the time the clock is stopped for in not accounted\r
300                 for here (as it would normally be) because the clock is so slow it is\r
301                 unlikely it will be stopped for a complete count period anyway. */\r
302                 TIM_Cmd( TIM2, DISABLE );\r
303 \r
304                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
305                 above. */\r
306                 __asm volatile ( "cpsie i" );\r
307                 __asm volatile ( "dsb" );\r
308                 __asm volatile ( "isb" );\r
309 \r
310                 if( ulTickFlag != pdFALSE )\r
311                 {\r
312                         /* Trap overflows before the next calculation. */\r
313                         configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) );\r
314 \r
315                         /* The tick interrupt has already executed, although because this\r
316                         function is called with the scheduler suspended the actual tick\r
317                         processing will not occur until after this function has exited.\r
318                         Reset the reload value with whatever remains of this tick period. */\r
319                         ulCounterValue = ulReloadValueForOneTick - ( uint32_t ) TIM_GetCounter( TIM2 );\r
320 \r
321                         /* Trap under/overflows before the calculated value is used. */\r
322                         configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
323                         configASSERT( ulCounterValue != 0 );\r
324 \r
325                         /* Use the calculated reload value. */\r
326                         TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
327                         TIM_SetCounter( TIM2, 0 );\r
328 \r
329                         /* The tick interrupt handler will already have pended the tick\r
330                         processing in the kernel.  As the pending tick will be processed as\r
331                         soon as this function exits, the tick value     maintained by the tick\r
332                         is stepped forward by one less than the time spent sleeping.  The\r
333                         actual stepping of the tick appears later in this function. */\r
334                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
335                 }\r
336                 else\r
337                 {\r
338                         /* Something other than the tick interrupt ended the sleep.  How\r
339                         many complete tick periods passed while the processor was\r
340                         sleeping? */\r
341                         ulCompleteTickPeriods = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) / ulReloadValueForOneTick;\r
342 \r
343                         /* Check for over/under flows before the following calculation. */\r
344                         configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) );\r
345 \r
346                         /* The reload value is set to whatever fraction of a single tick\r
347                         period remains. */\r
348                         ulCounterValue = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) - ( ulCompleteTickPeriods * ulReloadValueForOneTick );\r
349                         configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
350                         if( ulCounterValue == 0 )\r
351                         {\r
352                                 /* There is no fraction remaining. */\r
353                                 ulCounterValue = ulReloadValueForOneTick;\r
354                                 ulCompleteTickPeriods++;\r
355                         }\r
356                         TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
357                         TIM_SetCounter( TIM2, 0 );\r
358                 }\r
359 \r
360                 /* Restart TIM2 so it runs up to the reload value.  The reload value\r
361                 will get set to the value required to generate exactly one tick period\r
362                 the next time the TIM2 interrupt executes. */\r
363                 TIM_Cmd( TIM2, ENABLE );\r
364 \r
365                 /* Wind the tick forward by the number of tick periods that the CPU\r
366                 remained in a low power state. */\r
367                 vTaskStepTick( ulCompleteTickPeriods );\r
368         }\r
369 }\r
370 \r
371 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
372 \r