]> git.sur5r.net Git - freertos/blobdiff - 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
index faff612d11aa8a696511e6031dde110045951d20..ba6543835cd0a802f7f6fc37484672e5dfad0c21 100644 (file)
@@ -1,60 +1,64 @@
 /*\r
-    FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.\r
+    FreeRTOS V9.0.0rc2 - Copyright (C) 2016 Real Time Engineers Ltd.\r
     All rights reserved\r
 \r
     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
 \r
-    ***************************************************************************\r
-     *                                                                       *\r
-     *    FreeRTOS provides completely free yet professionally developed,    *\r
-     *    robust, strictly quality controlled, supported, and cross          *\r
-     *    platform software that has become a de facto standard.             *\r
-     *                                                                       *\r
-     *    Help yourself get started quickly and support the FreeRTOS         *\r
-     *    project by purchasing a FreeRTOS tutorial book, reference          *\r
-     *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
-     *                                                                       *\r
-     *    Thank you!                                                         *\r
-     *                                                                       *\r
-    ***************************************************************************\r
-\r
     This file is part of the FreeRTOS distribution.\r
 \r
     FreeRTOS is free software; you can redistribute it and/or modify it under\r
     the terms of the GNU General Public License (version 2) as published by the\r
-    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
+    Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.\r
 \r
-    >>! NOTE: The modification to the GPL is included to allow you to distribute\r
-    >>! a combined work that includes FreeRTOS without being obliged to provide\r
-    >>! the source code for proprietary components outside of the FreeRTOS\r
-    >>! kernel.\r
+    ***************************************************************************\r
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
+    >>!   obliged to provide the source code for proprietary components     !<<\r
+    >>!   outside of the FreeRTOS kernel.                                   !<<\r
+    ***************************************************************************\r
 \r
     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
-    FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following\r
     link: http://www.freertos.org/a00114.html\r
 \r
-    1 tab == 4 spaces!\r
-\r
     ***************************************************************************\r
      *                                                                       *\r
-     *    Having a problem?  Start by reading the FAQ "My application does   *\r
-     *    not run, what could be wrong?"                                     *\r
+     *    FreeRTOS provides completely free yet professionally developed,    *\r
+     *    robust, strictly quality controlled, supported, and cross          *\r
+     *    platform software that is more than just the market leader, it     *\r
+     *    is the industry's de facto standard.                               *\r
      *                                                                       *\r
-     *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
+     *    Help yourself get started quickly while simultaneously helping     *\r
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *\r
+     *    tutorial book, reference manual, or both:                          *\r
+     *    http://www.FreeRTOS.org/Documentation                              *\r
      *                                                                       *\r
     ***************************************************************************\r
 \r
-    http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
-    license and Real Time Engineers Ltd. contact details.\r
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading\r
+    the FAQ page "My application does not run, what could be wrong?".  Have you\r
+    defined configASSERT()?\r
+\r
+    http://www.FreeRTOS.org/support - In return for receiving this top quality\r
+    embedded software for free we request you assist our global community by\r
+    participating in the support forum.\r
+\r
+    http://www.FreeRTOS.org/training - Investing in training allows your team to\r
+    be as productive as possible as early as possible.  Now you can receive\r
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers\r
+    Ltd, and the world's leading authority on the world's leading RTOS.\r
 \r
     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
 \r
-    http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
-    Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
-    licenses offer ticketed support, indemnification and middleware.\r
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.\r
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.\r
+\r
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High\r
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
+    licenses offer ticketed support, indemnification and commercial middleware.\r
 \r
     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
     engineered and independently SIL3 certified version for use in safety and\r
 \r
 /*\r
  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
- * is generated by the wakeup interrupt of the real time clock (RTC).  The RTC\r
- * configuration and handling functions are defined in this file.\r
+ * is generated by the TIM2 peripheral.  The TIM2 configuration and handling\r
+ * functions are defined in this file.  Note the RTC is not used as there does\r
+ * not appear to be a way to read back the RTC count value, and therefore the\r
+ * only way of knowing exactly how long a sleep lasted is to use the very low\r
+ * resolution calendar time.\r
  *\r
  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
  */\r
 #if configCREATE_LOW_POWER_DEMO == 1\r
 \r
-/* The frequency at which TIM2 should run. */\r
+/* The frequency at which TIM2 will run. */\r
 #define lpCLOCK_INPUT_FREQUENCY        ( 1000UL )\r
 \r
-/* Constants required to pend a PendSV interrupt from the tick ISR if the\r
-preemptive scheduler is being used.  These are just standard bits and registers\r
-within the Cortex-M core itself. */\r
-#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )\r
-\r
+/* STM32 register used to ensure the TIM2 clock stops when the MCU is in debug\r
+mode. */\r
 #define DBGMCU_APB1_FZ         ( * ( ( volatile unsigned long * ) 0xE0042008 ) )\r
+\r
 /*-----------------------------------------------------------*/\r
 \r
 /*\r
- * The tick interrupt is generated by the TIM2 timer.  The default interrupt\r
- * handler cannot be used (even with the TIM2 being handled from the tick hook\r
- * function) because the default tick interrupt accesses the SysTick registers\r
- * when configUSE_TICKLESS_IDLE set to 1.  TIM2_IRQHandler() is the default name\r
- * for the TIM2 interrupt handler.\r
+ * The tick interrupt is generated by the TIM2 timer.\r
  */\r
 void TIM2_IRQHandler( void );\r
 \r
@@ -112,18 +113,12 @@ static const uint32_t ulReloadValueForOneTick = ( ( lpCLOCK_INPUT_FREQUENCY / co
 /* Holds the maximum number of ticks that can be suppressed - which is\r
 basically how far into the future an interrupt can be generated. Set during\r
 initialisation. */\r
-static portTickType xMaximumPossibleSuppressedTicks = 0;\r
+static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
 \r
 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
-sleep mode was exited because of an RTC interrupt or a different interrupt. */\r
+sleep mode was exited because of an tick interrupt or a different interrupt. */\r
 static volatile uint32_t ulTickFlag = pdFALSE;\r
 \r
-/* The RTC counter is stopped temporarily each time it is re-programmed.  The\r
-following variable offsets the RTC counter alarm value by the number of RTC\r
-counts that would typically be missed while the counter was stopped to\r
-compensate for the lost time.  _RB_ Value needs calculating correctly. */\r
-static uint32_t ulStoppedTimerCompensation = 1;//_RB_ / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );\r
-\r
 /*-----------------------------------------------------------*/\r
 \r
 /* The tick interrupt handler.  This is always the same other than the part that\r
@@ -131,10 +126,13 @@ clears the interrupt, which is specific to the clock being used to generate the
 tick. */\r
 void TIM2_IRQHandler( void )\r
 {\r
+       /* Clear the interrupt. */\r
        TIM_ClearITPendingBit( TIM2, TIM_IT_Update );\r
-       TIM_SetAutoreload( TIM2, ( uint16_t ) ulReloadValueForOneTick );\r
 \r
-       /* Protect incrementing the tick with an interrupt safe critical section. */\r
+       /* The next block of code is from the standard FreeRTOS tick interrupt\r
+       handler.  The standard handler is not called directly in case future\r
+       versions contain changes that make it no longer suitable for calling\r
+       here. */\r
        ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
        {\r
                if( xTaskIncrementTick() != pdFALSE )\r
@@ -148,39 +146,42 @@ void TIM2_IRQHandler( void )
        }\r
        portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
 \r
+       /* In case this is the first tick since the MCU left a low power mode the\r
+       reload value is reset to its default. */\r
+       TIM2->ARR = ( uint16_t ) ulReloadValueForOneTick;\r
+\r
        /* The CPU woke because of a tick. */\r
        ulTickFlag = pdTRUE;\r
 }\r
 /*-----------------------------------------------------------*/\r
 \r
 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
-defined in the FreeRTOS Cortex-M3 port layer with a version that configures the\r
-wakeup timer of the RTC to generate the tick interrupt. */\r
+defined in the FreeRTOS Cortex-M3 port layer with a version that configures TIM2\r
+to generate the tick interrupt. */\r
 void vPortSetupTimerInterrupt( void )\r
 {\r
 NVIC_InitTypeDef NVIC_InitStructure;\r
 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;\r
 \r
-       /* Enable the TIM2 clock, which is used to generate long tickless periods\r
-       when the tickless period is finite. */\r
+       /* Enable the TIM2 clock. */\r
        RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE );\r
 \r
        /* Ensure clock stops in debug mode. */\r
        DBGMCU_APB1_FZ |= DBGMCU_APB1_FZ_DBG_TIM2_STOP;\r
 \r
-       /* Scale the clock so very long tickless periods can be acheived.  The\r
-       SysTick is not used as even when its frequency is divided by 8 the maximum\r
-       tickless period with a system clock of 16MHz is only 8.3 seconds.  Using\r
-       a prescaled clock on the 16-bit TIM2 allows a tickless period of nearly\r
-       66 seconds, albeit at low resolution. */\r
+       /* Scale the clock so longer tickless periods can be achieved.  The     SysTick\r
+       is not used as even when its frequency is divided by 8 the maximum tickless\r
+       period with a system clock of 16MHz is only 8.3 seconds.  Using a prescaled\r
+       clock on the 16-bit TIM2 allows a tickless period of nearly     66 seconds,\r
+       albeit at low resolution. */\r
        TIM_TimeBaseStructure.TIM_Prescaler = ( uint16_t ) ( SystemCoreClock / lpCLOCK_INPUT_FREQUENCY );\r
        TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;\r
        TIM_TimeBaseStructure.TIM_Period = ( uint16_t ) ( lpCLOCK_INPUT_FREQUENCY / configTICK_RATE_HZ );\r
        TIM_TimeBaseStructure.TIM_ClockDivision = 0;\r
        TIM_TimeBaseInit( TIM2, &TIM_TimeBaseStructure );\r
 \r
-       /* Enable the TIM2 interrupt - used for the tick interrupt when the tickless\r
-       period is finite. */\r
+       /* Enable the TIM2 interrupt.  This must execute at the lowest interrupt\r
+       priority. */\r
        NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;\r
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY; /* Must be set to lowest priority. */\r
        NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;\r
@@ -198,12 +199,12 @@ TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
 /* Override the default definition of vPortSuppressTicksAndSleep() that is\r
 weakly defined in the FreeRTOS Cortex-M3 port layer with a version that manages\r
 the TIM2 interrupt, as the tick is generated from TIM2 compare matches events. */\r
-void vPortSuppressTicksAndSleep( portTickType xExpectedIdleTime )\r
+void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
 {\r
 uint32_t ulCounterValue, ulCompleteTickPeriods;\r
 eSleepModeStatus eSleepAction;\r
-portTickType xModifiableIdleTime;\r
-const portTickType xRegulatorOffIdleTime = 30;\r
+TickType_t xModifiableIdleTime;\r
+const TickType_t xRegulatorOffIdleTime = 30;\r
 \r
        /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
 \r
@@ -216,17 +217,11 @@ const portTickType xRegulatorOffIdleTime = 30;
        /* Calculate the reload value required to wait xExpectedIdleTime tick\r
        periods. */\r
        ulCounterValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
-       if( ulCounterValue > ulStoppedTimerCompensation )\r
-       {\r
-               /* Compensate for the fact that TIM2 is going to be stopped\r
-               momentarily. */\r
-               ulCounterValue -= ulStoppedTimerCompensation;\r
-       }\r
 \r
-       /* Stop TIM2 momentarily.  The time TIM2 is stopped for is accounted for as\r
-       best it can be, but using the tickless mode will inevitably result in some\r
-       tiny drift of the time maintained by the kernel with respect to calendar\r
-       time. */\r
+       /* Stop TIM2 momentarily.  The time TIM2 is stopped for is not accounted for\r
+       in this implementation (as it is in the generic implementation) because the\r
+       clock is so slow it is unlikely to be stopped for a complete count period\r
+       anyway. */\r
        TIM_Cmd( TIM2, DISABLE );\r
 \r
        /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
@@ -255,13 +250,25 @@ const portTickType xRegulatorOffIdleTime = 30;
        }\r
        else if( eSleepAction == eNoTasksWaitingTimeout )\r
        {\r
+               /* A user definable macro that allows application code to be inserted\r
+               here.  Such application code can be used to minimise power consumption\r
+               further by turning off IO, peripheral clocks, the Flash, etc. */\r
+               configPRE_STOP_PROCESSING();\r
+\r
                /* There are no running state tasks and no tasks that are blocked with a\r
                time out.  Assuming the application does not care if the tick time slips\r
                with respect to calendar time then enter a deep sleep that can only be\r
                woken by (in this demo case) the user button being pushed on the\r
-               STM32L discovery board. */\r
-               configPRE_STOP_PROCESSING();\r
+               STM32L discovery board.  If the application does require the tick time\r
+               to keep better track of the calender time then the RTC peripheral can be\r
+               used to make rough adjustments. */\r
                PWR_EnterSTOPMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
+\r
+               /* A user definable macro that allows application code to be inserted\r
+               here.  Such application code can be used to reverse any actions taken\r
+               by the configPRE_STOP_PROCESSING().  In this demo\r
+               configPOST_STOP_PROCESSING() is used to re-initialise the clocks that\r
+               were turned off when STOP mode was entered. */\r
                configPOST_STOP_PROCESSING();\r
 \r
                /* Restart tick. */\r
@@ -271,39 +278,53 @@ const portTickType xRegulatorOffIdleTime = 30;
                /* Re-enable interrupts - see comments above the cpsid instruction()\r
                above. */\r
                __asm volatile ( "cpsie i" );\r
+               __asm volatile ( "dsb" );\r
+               __asm volatile ( "isb" );\r
        }\r
        else\r
        {\r
+               /* Trap underflow before the next calculation. */\r
+               configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) );\r
+\r
                /* Adjust the TIM2 value to take into account that the current time\r
                slice is already partially complete. */\r
-               configASSERT( ulCounterValue >= TIM_GetCounter( TIM2 ) );\r
                ulCounterValue -= ( uint32_t ) TIM_GetCounter( TIM2 );\r
+\r
+               /* Trap overflow/underflow before the calculated value is written to\r
+               TIM2. */\r
                configASSERT( ulCounterValue < ( uint32_t ) USHRT_MAX );\r
                configASSERT( ulCounterValue != 0 );\r
+\r
+               /* Update to use the calculated overflow value. */\r
                TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
                TIM_SetCounter( TIM2, 0 );\r
 \r
                /* Restart the TIM2. */\r
                TIM_Cmd( TIM2, ENABLE );\r
 \r
-               /* Allow the application to define some pre-sleep processing. */\r
+               /* Allow the application to define some pre-sleep processing.  This is\r
+               the standard configPRE_SLEEP_PROCESSING() macro as described on the\r
+               FreeRTOS.org website. */\r
                xModifiableIdleTime = xExpectedIdleTime;\r
                configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
 \r
                /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
-               means the application defined code has already executed the WAIT\r
+               means the application defined code has already executed the wait/sleep\r
                instruction. */\r
                if( xModifiableIdleTime > 0 )\r
                {\r
                        /* The sleep mode used is dependent on the expected idle time\r
-                       as the deeper the sleep the longer the wake up time. */\r
+                       as the deeper the sleep the longer the wake up time.  See the\r
+                       comments at the top of main_low_power.c.  Note xRegulatorOffIdleTime\r
+                       is set purely for convenience of demonstration and is not intended\r
+                       to be an optimised value. */\r
                        if( xModifiableIdleTime > xRegulatorOffIdleTime )\r
                        {\r
                                /* A slightly lower power sleep mode with a longer wake up\r
                                time. */\r
                                PWR_EnterSleepMode( PWR_Regulator_LowPower, PWR_SLEEPEntry_WFI );\r
                        }\r
-                       else if( pdTRUE )\r
+                       else\r
                        {\r
                                /* A slightly higher power sleep mode with a faster wake up\r
                                time. */\r
@@ -311,13 +332,14 @@ const portTickType xRegulatorOffIdleTime = 30;
                        }\r
                }\r
 \r
-               /* Allow the application to define some post sleep processing. */\r
+               /* Allow the application to define some post sleep processing.  This is\r
+               the standard configPOST_SLEEP_PROCESSING() macro, as described on the\r
+               FreeRTOS.org website. */\r
                configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
 \r
-               /* Stop TIM2.  Again, the time the SysTick is stopped for is accounted\r
-               for as best it can be, but using the tickless mode will inevitably\r
-               result in some tiny drift of the time maintained by the kernel with\r
-               respect to calendar time. */\r
+               /* Stop TIM2.  Again, the time the clock is stopped for in not accounted\r
+               for here (as it would normally be) because the clock is so slow it is\r
+               unlikely it will be stopped for a complete count period anyway. */\r
                TIM_Cmd( TIM2, DISABLE );\r
 \r
                /* Re-enable interrupts - see comments above the cpsid instruction()\r
@@ -328,14 +350,20 @@ const portTickType xRegulatorOffIdleTime = 30;
 \r
                if( ulTickFlag != pdFALSE )\r
                {\r
+                       /* Trap overflows before the next calculation. */\r
+                       configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) );\r
+\r
                        /* The tick interrupt has already executed, although because this\r
                        function is called with the scheduler suspended the actual tick\r
                        processing will not occur until after this function has exited.\r
                        Reset the reload value with whatever remains of this tick period. */\r
-                       configASSERT( ulReloadValueForOneTick >= ( uint32_t ) TIM_GetCounter( TIM2 ) );\r
                        ulCounterValue = ulReloadValueForOneTick - ( uint32_t ) TIM_GetCounter( TIM2 );\r
+\r
+                       /* Trap under/overflows before the calculated value is used. */\r
                        configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
                        configASSERT( ulCounterValue != 0 );\r
+\r
+                       /* Use the calculated reload value. */\r
                        TIM_SetAutoreload( TIM2, ( uint16_t ) ulCounterValue );\r
                        TIM_SetCounter( TIM2, 0 );\r
 \r
@@ -353,9 +381,11 @@ const portTickType xRegulatorOffIdleTime = 30;
                        sleeping? */\r
                        ulCompleteTickPeriods = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) / ulReloadValueForOneTick;\r
 \r
+                       /* Check for over/under flows before the following calculation. */\r
+                       configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) );\r
+\r
                        /* The reload value is set to whatever fraction of a single tick\r
                        period remains. */\r
-                       configASSERT( ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) >= ( ulCompleteTickPeriods * ulReloadValueForOneTick ) );\r
                        ulCounterValue = ( ( uint32_t ) TIM_GetCounter( TIM2 ) ) - ( ulCompleteTickPeriods * ulReloadValueForOneTick );\r
                        configASSERT( ulCounterValue <= ( uint32_t ) USHRT_MAX );\r
                        if( ulCounterValue == 0 )\r
@@ -379,7 +409,5 @@ const portTickType xRegulatorOffIdleTime = 30;
        }\r
 }\r
 \r
-\r
-\r
 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
 \r