2 * FreeRTOS Kernel V10.3.0
\r
3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
\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
12 * The above copyright notice and this permission notice shall be included in all
\r
13 * copies or substantial portions of the Software.
\r
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\r
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
\r
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
\r
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
\r
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
\r
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
22 * http://www.FreeRTOS.org
\r
23 * http://aws.amazon.com/freertos
\r
25 * 1 tab == 4 spaces!
\r
28 /* Standard includes. */
\r
31 /* FreeRTOS includes. */
\r
32 #include "FreeRTOS.h"
\r
35 /* ST library functions. */
\r
36 #include "stm32l1xx.h"
\r
39 * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt
\r
40 * is generated by the TIM2 peripheral. The TIM2 configuration and handling
\r
41 * functions are defined in this file. Note the RTC is not used as there does
\r
42 * not appear to be a way to read back the RTC count value, and therefore the
\r
43 * only way of knowing exactly how long a sleep lasted is to use the very low
\r
44 * resolution calendar time.
\r
46 * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is
\r
47 * generated by the standard FreeRTOS Cortex-M port layer, which uses the
\r
50 #if configCREATE_LOW_POWER_DEMO == 1
\r
52 /* The frequency at which TIM2 will run. */
\r
53 #define lpCLOCK_INPUT_FREQUENCY ( 1000UL )
\r
55 /* STM32 register used to ensure the TIM2 clock stops when the MCU is in debug
\r
57 #define DBGMCU_APB1_FZ ( * ( ( volatile unsigned long * ) 0xE0042008 ) )
\r
59 /*-----------------------------------------------------------*/
\r
62 * The tick interrupt is generated by the TIM2 timer.
\r
64 void TIM2_IRQHandler( void );
\r
66 /*-----------------------------------------------------------*/
\r
68 /* Calculate how many clock increments make up a single tick period. */
\r
69 static const uint32_t ulReloadValueForOneTick = ( ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ ) - 1 );
\r
71 /* Holds the maximum number of ticks that can be suppressed - which is
\r
72 basically how far into the future an interrupt can be generated. Set during
\r
74 static TickType_t xMaximumPossibleSuppressedTicks = 0;
\r
76 /* Flag set from the tick interrupt to allow the sleep processing to know if
\r
77 sleep mode was exited because of an tick interrupt or a different interrupt. */
\r
78 static volatile uint32_t ulTickFlag = pdFALSE;
\r
80 /*-----------------------------------------------------------*/
\r
82 /* The tick interrupt handler. This is always the same other than the part that
\r
83 clears the interrupt, which is specific to the clock being used to generate the
\r
85 void TIM2_IRQHandler( void )
\r
87 /* Clear the interrupt. */
\r
88 TIM_ClearITPendingBit( TIM2, TIM_IT_Update );
\r
90 /* The next block of code is from the standard FreeRTOS tick interrupt
\r
91 handler. The standard handler is not called directly in case future
\r
92 versions contain changes that make it no longer suitable for calling
\r
94 ( void ) portSET_INTERRUPT_MASK_FROM_ISR();
\r
96 if( xTaskIncrementTick() != pdFALSE )
\r
98 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
\r
101 /* Just completely clear the interrupt mask on exit by passing 0 because
\r
102 it is known that this interrupt will only ever execute with the lowest
\r
103 possible interrupt priority. */
\r
105 portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );
\r
107 /* In case this is the first tick since the MCU left a low power mode the
\r
108 reload value is reset to its default. */
\r
109 TIM2->ARR = ( uint16_t ) ulReloadValueForOneTick;
\r
111 /* The CPU woke because of a tick. */
\r
112 ulTickFlag = pdTRUE;
\r
114 /*-----------------------------------------------------------*/
\r
116 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly
\r
117 defined in the FreeRTOS Cortex-M3 port layer with a version that configures TIM2
\r
118 to generate the tick interrupt. */
\r
119 void vPortSetupTimerInterrupt( void )
\r
121 NVIC_InitTypeDef NVIC_InitStructure;
\r
122 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
\r
124 /* Enable the TIM2 clock. */
\r
125 RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE );
\r
127 /* Ensure clock stops in debug mode. */
\r
128 DBGMCU_APB1_FZ |= DBGMCU_APB1_FZ_DBG_TIM2_STOP;
\r
130 /* Scale the clock so longer tickless periods can be achieved. The SysTick
\r
131 is not used as even when its frequency is divided by 8 the maximum tickless
\r
132 period with a system clock of 16MHz is only 8.3 seconds. Using a prescaled
\r
133 clock on the 16-bit TIM2 allows a tickless period of nearly 66 seconds,
\r
134 albeit at low resolution. */
\r
135 TIM_TimeBaseStructure.TIM_Prescaler = ( uint16_t ) ( SystemCoreClock / lpCLOCK_INPUT_FREQUENCY );
\r
136 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
\r
137 TIM_TimeBaseStructure.TIM_Period = ( uint16_t ) ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ );
\r
138 TIM_TimeBaseStructure.TIM_ClockDivision = 0;
\r
139 TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure );
\r
141 /* Enable the TIM2 interrupt. This must execute at the lowest interrupt
\r
143 NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
\r
144 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY; /* Must be set to lowest priority. */
\r
145 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
\r
146 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
\r
147 NVIC_Init(&NVIC_InitStructure);
\r
148 TIM_ITConfig( TIM2, TIM_IT_Update, ENABLE );
\r
149 TIM_SetCounter( TIM2, 0 );
\r
150 TIM_Cmd( TIM2, ENABLE );
\r
152 /* See the comments where xMaximumPossibleSuppressedTicks is declared. */
\r
153 xMaximumPossibleSuppressedTicks = ( ( unsigned long ) USHRT_MAX ) / ulReloadValueForOneTick;
\r
155 /*-----------------------------------------------------------*/
\r
157 /* Override the default definition of vPortSuppressTicksAndSleep() that is
\r
158 weakly defined in the FreeRTOS Cortex-M3 port layer with a version that manages
\r
159 the TIM2 interrupt, as the tick is generated from TIM2 compare matches events. */
\r
160 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
\r
162 uint32_t ulCounterValue, ulCompleteTickPeriods;
\r
163 eSleepModeStatus eSleepAction;
\r
164 TickType_t xModifiableIdleTime;
\r
165 const TickType_t xRegulatorOffIdleTime = 30;
\r
167 /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */
\r
169 /* Make sure the TIM2 reload value does not overflow the counter. */
\r
170 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
\r
172 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
\r
175 /* Calculate the reload value required to wait xExpectedIdleTime tick
\r
177 ulCounterValue = ulReloadValueForOneTick * xExpectedIdleTime;
\r
179 /* Stop TIM2 momentarily. The time TIM2 is stopped for is not accounted for
\r
180 in this implementation (as it is in the generic implementation) because the
\r
181 clock is so slow it is unlikely to be stopped for a complete count period
\r
183 TIM_Cmd( TIM2, DISABLE );
\r
185 /* Enter a critical section but don't use the taskENTER_CRITICAL() method as
\r
186 that will mask interrupts that should exit sleep mode. */
\r
187 __asm volatile ( "cpsid i" );
\r
188 __asm volatile ( "dsb" );
\r
189 __asm volatile ( "isb" );
\r
191 /* The tick flag is set to false before sleeping. If it is true when sleep
\r
192 mode is exited then sleep mode was probably exited because the tick was
\r
193 suppressed for the entire xExpectedIdleTime period. */
\r
194 ulTickFlag = pdFALSE;
\r
196 /* If a context switch is pending then abandon the low power entry as
\r
197 the context switch might have been pended by an external interrupt that
\r
198 requires processing. */
\r
199 eSleepAction = eTaskConfirmSleepModeStatus();
\r
200 if( eSleepAction == eAbortSleep )
\r
202 /* Restart tick. */
\r
203 TIM_Cmd( TIM2, ENABLE );
\r
205 /* Re-enable interrupts - see comments above the cpsid instruction()
\r
207 __asm volatile ( "cpsie i" );
\r
209 else if( eSleepAction == eNoTasksWaitingTimeout )
\r
211 /* A user definable macro that allows application code to be inserted
\r
212 here. Such application code can be used to minimise power consumption
\r
213 further by turning off IO, peripheral clocks, the Flash, etc. */
\r
214 configPRE_STOP_PROCESSING();
\r
216 /* There are no running state tasks and no tasks that are blocked with a
\r
217 time out. Assuming the application does not care if the tick time slips
\r
218 with respect to calendar time then enter a deep sleep that can only be
\r
219 woken by (in this demo case) the user button being pushed on the
\r
220 STM32L discovery board. If the application does require the tick time
\r
221 to keep better track of the calender time then the RTC peripheral can be
\r
222 used to make rough adjustments. */
\r
223 PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );
\r
225 /* A user definable macro that allows application code to be inserted
\r
226 here. Such application code can be used to reverse any actions taken
\r
227 by the configPRE_STOP_PROCESSING(). In this demo
\r
228 configPOST_STOP_PROCESSING() is used to re-initialise the clocks that
\r
229 were turned off when STOP mode was entered. */
\r
230 configPOST_STOP_PROCESSING();
\r
232 /* Restart tick. */
\r
233 TIM_SetCounter( TIM2, 0 );
\r
234 TIM_Cmd( TIM2, ENABLE );
\r
236 /* Re-enable interrupts - see comments above the cpsid instruction()
\r
238 __asm volatile ( "cpsie i" );
\r
239 __asm volatile ( "dsb" );
\r
240 __asm volatile ( "isb" );
\r
244 /* Trap underflow before the next calculation. */
\r
245 configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) );
\r
247 /* Adjust the TIM2 value to take into account that the current time
\r
248 slice is already partially complete. */
\r
249 ulCounterValue -= ( uint32_t ) TIM_GetCounter( TIM2 );
\r
251 /* Trap overflow/underflow before the calculated value is written to
\r
253 configASSERT( ulCounterValue < ( uint32_t ) USHRT_MAX );
\r
254 configASSERT( ulCounterValue != 0 );
\r
256 /* Update to use the calculated overflow value. */
\r
257 TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );
\r
258 TIM_SetCounter( TIM2, 0 );
\r
260 /* Restart the TIM2. */
\r
261 TIM_Cmd( TIM2, ENABLE );
\r
263 /* Allow the application to define some pre-sleep processing. This is
\r
264 the standard configPRE_SLEEP_PROCESSING() macro as described on the
\r
265 FreeRTOS.org website. */
\r
266 xModifiableIdleTime = xExpectedIdleTime;
\r
267 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
\r
269 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()
\r
270 means the application defined code has already executed the wait/sleep
\r
272 if( xModifiableIdleTime > 0 )
\r
274 /* The sleep mode used is dependent on the expected idle time
\r
275 as the deeper the sleep the longer the wake up time. See the
\r
276 comments at the top of main_low_power.c. Note xRegulatorOffIdleTime
\r
277 is set purely for convenience of demonstration and is not intended
\r
278 to be an optimised value. */
\r
279 if( xModifiableIdleTime > xRegulatorOffIdleTime )
\r
281 /* A slightly lower power sleep mode with a longer wake up
\r
283 PWR_EnterSleepMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );
\r
287 /* A slightly higher power sleep mode with a faster wake up
\r
289 PWR_EnterSleepMode( PWR_Regulator_ON, PWR_SLEEPEntry_WFI );
\r
293 /* Allow the application to define some post sleep processing. This is
\r
294 the standard configPOST_SLEEP_PROCESSING() macro, as described on the
\r
295 FreeRTOS.org website. */
\r
296 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );
\r
298 /* Stop TIM2. Again, the time the clock is stopped for in not accounted
\r
299 for here (as it would normally be) because the clock is so slow it is
\r
300 unlikely it will be stopped for a complete count period anyway. */
\r
301 TIM_Cmd( TIM2, DISABLE );
\r
303 /* Re-enable interrupts - see comments above the cpsid instruction()
\r
305 __asm volatile ( "cpsie i" );
\r
306 __asm volatile ( "dsb" );
\r
307 __asm volatile ( "isb" );
\r
309 if( ulTickFlag != pdFALSE )
\r
311 /* Trap overflows before the next calculation. */
\r
312 configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) );
\r
314 /* The tick interrupt has already executed, although because this
\r
315 function is called with the scheduler suspended the actual tick
\r
316 processing will not occur until after this function has exited.
\r
317 Reset the reload value with whatever remains of this tick period. */
\r
318 ulCounterValue = ulReloadValueForOneTick - ( uint32_t ) TIM_GetCounter( TIM2 );
\r
320 /* Trap under/overflows before the calculated value is used. */
\r
321 configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );
\r
322 configASSERT( ulCounterValue != 0 );
\r
324 /* Use the calculated reload value. */
\r
325 TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );
\r
326 TIM_SetCounter( TIM2, 0 );
\r
328 /* The tick interrupt handler will already have pended the tick
\r
329 processing in the kernel. As the pending tick will be processed as
\r
330 soon as this function exits, the tick value maintained by the tick
\r
331 is stepped forward by one less than the time spent sleeping. The
\r
332 actual stepping of the tick appears later in this function. */
\r
333 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
\r
337 /* Something other than the tick interrupt ended the sleep. How
\r
338 many complete tick periods passed while the processor was
\r
340 ulCompleteTickPeriods = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) / ulReloadValueForOneTick;
\r
342 /* Check for over/under flows before the following calculation. */
\r
343 configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) );
\r
345 /* The reload value is set to whatever fraction of a single tick
\r
347 ulCounterValue = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) - ( ulCompleteTickPeriods * ulReloadValueForOneTick );
\r
348 configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );
\r
349 if( ulCounterValue == 0 )
\r
351 /* There is no fraction remaining. */
\r
352 ulCounterValue = ulReloadValueForOneTick;
\r
353 ulCompleteTickPeriods++;
\r
355 TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );
\r
356 TIM_SetCounter( TIM2, 0 );
\r
359 /* Restart TIM2 so it runs up to the reload value. The reload value
\r
360 will get set to the value required to generate exactly one tick period
\r
361 the next time the TIM2 interrupt executes. */
\r
362 TIM_Cmd( TIM2, ENABLE );
\r
364 /* Wind the tick forward by the number of tick periods that the CPU
\r
365 remained in a low power state. */
\r
366 vTaskStepTick( ulCompleteTickPeriods );
\r
370 #endif /* configCREATE_LOW_POWER_DEMO == 1 */
\r