Hands-On Workshop: Create Low-Power Applications with MQX™ and MQX™ Lite RTOS FTF-SDS-F0040

Maclain Lobdell | Freescale Software Product Manager Vincent Leynaert | Freescale FAE APR.2014

TM

External Use Hands-On Workshop: Create Low-Power Applications with MQX™ and MQX™ Lite RTOS

FTF-SDS-F0040 4 Hour Class

Learn how to take advantage of the power management capabilities of MQX and MQX Lite RTOS. See how to create feature-rich applications without killing battery life. Attendees will get hands-on experience with system power mode transitions, driver state transitions and slowing or stopping the system tick timer for power savings.

TM External Use 1 Session Introduction

• Power efficiency is an increasingly important part of embedded product design. Power consumption budgets are tightening even though performance expectations are ever increasing. • You can create power efficient applications while using an RTOS for sophisticated designs.

TM External Use 2 Session Objectives

• After completing this session you will be able to: − Understand how power management capabilities can be used in RTOS- based applications − Understand how to perform system power mode transitions, frequency scaling, driver state transitions, and slow or stop the RTOS system tick timer for power savings

TM External Use 3 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 4 Implementing the techniques discussed in this class, we were able to reduce energy consumption by 98%

18 98% 14 Reduction in Energy Consumption (In our example applications 10 in a 5-min window)

6

2 0.3 No Optimization Sleep while Idle Stop Mode Tick Disabled

Units in joules (watt*second)

TM External Use 5 Download at: www.freescale.com/mqx Freescale MQX™ Software Solutions

Commercial-grade MCU Product Features software platform at no cost • MQX™ Real Time with optional support packages Kernel − Deterministic multi-tasking preemptive scheduler Enabling the development of − Extensive inter-task synchronization, connected and intelligent message passing, and much more applications of the future • MQX™ Real Time Communication Suite Now with optional IPv6 add-on package − Broad networking protocol support Customer Application (TCP,UDP, ICMP, HTTP, DHCP, FTP, Telnet, …) − Fully re-entrant, responsive, designed for embedded systems • MQX™ Stacks Specific − Embedded FAT file system compatible (TCP/IP, USB) Application Middleware with FAT-12, FAT-16, or FAT-32 file Libraries Operating systems (DSP, Math, Software and Hardware Evaluation & Dev Tools Encryption) System • MQX™ USB Host/Device Stack BSP, Drivers & Bootloader − USB 1.0/2.0; low-/full-/high-speed HAL • Board Support Packages MCU Hardware − Pre-configured MQX Kernel, stacks, and peripheral drivers for Freescale HW

TM External Use 6 Why use an RTOS?

• Create Deterministic and Connected Designs − Lower latency versus super loop software architecture − Multiple communications interfaces are much easier to manage with an RTOS − Integrated middleware and upper layer protocols such as TCP/IP, USB, Flash Systems, Web Servers, Wi-Fi support, CAN protocols, SSL, SNMP

• Ease of Development − Board Support Packages (BSPs) available with peripheral drivers − Spend time developing application code, not maintaining a system

• Portability and Scalability − Standard for high portability of application code to other MCUs − Configurable features to scale across products − Enable only features needed for low overhead

• Maintainability and Stability − Add new features without affecting system timing and higher priority functions

TM External Use 7 High-Level RTOS Landscape Linux QNX VxWorks WinCE MQX SMX

Nucleus RTX -Based Integrity RTXC RTOS/OS ThreadX CMX eCOS FreeRTOS uCOS-II

(Memory Footprint) (Memory MQX Lite Full Featured -Based RTOS Each “process” CMX-Tiny has own memory space. More Multi-media and sophisticated Basic Featured More features. More applications. Thread-Based RTOS integrated protocol

Potential Size stacks and middleware. Bare Metal Basic features. Some Low to high footprint. (No OS) protocol stacks and middleware. Low to medium footprint.

Features, Performance, Sophistication

TM External Use 8 Proven: 20+ years in the marketplace

• Used in millions and millions of products in medical, industrial, and defense markets from Fortune 500 companies. • Freescale holds a broad license to MQX across its portfolio.

ARC acquired Precise with MQX Introducing Freescale MQX • Acquired MQX license across Embedded Access Inc. (EAI) Freescale’s portfolio from ARC. Precise Founded • Licensed Provider of MQX • MQX Began • Roots from Precise & ARC • Strategic Freescale Partner 2005 2006

1989 Time 2000 Time 2004 Time 2008 2009 2010 2011 2012 2013

TM External Use 9 Freescale MQX Growing in Popularity!

#1 Freescale MQX 3rd Most Popular MCU RTOS in #2 2013 UBM Survey #3

Freescale MQX 65K+ Downloads 19K+ Unique Users

TM External Use 10 What's New in MQX RTOS 4.1

New Board Support Package − TWR-K21F120M (Kinetis K21 Tower System Module) New Features and Updates − Enhanced tools support for CodeWarrior, IAR, Keil, ARM® DS-5™, and GNU tools for ARM® − Vybrid BSP Updates ƒ Drivers added or extended: eDMA. DSP codec, FTM Quadrature decoder, DCU, NAND flash file system driver, SAI, eSAI, ASRC, UART w/ eDMA, and FlashX w/ QuadSPI. − Extended DMA support in Kinetis and Vybrid BSPs ƒ SPI, SAI, & eSAI drivers w/ eDMA; eSDHC w/ ADMA − Other Enhancements ƒ Updated LWADC, RTC, Hardware Timer w/ Low Power Timer (LPT), Kinetis Flash Swap, NAND Flash File System (FFS) added. − Software compatibility improvement ƒ MQX custom types replaced w/ standard C99 types

ARM DS-5

TM External Use 11 PLATFORM MQX 4.1 MQX 4.1 Board Support Packages VBYRID TWR‐VF65GS10 (M4&A5) √ AUTOEVB (M4&A5) √ • 24 Complimentary BSPs covering all Kinetis K, KINETIS Vybrid, and select ColdFire and Power Families TWR‐K20D50M √ TWR‐K20D72M √ • Numerous additional BSPs for legacy devices TWR‐K21D50M √ available free of charge in earlier MQX versions TWR‐K21F120M √ TWR‐K40X256 √ • Other BSPs available for purchase for other TWR‐K40D100M √ architectures TWR‐K53N512 √ TWR‐K60D100M √ • MQX Lite also available for all Kinetis K, L, & TWR‐K60F120M √ some E Series in Processor Expert TWR‐K60N512 √ TWR‐K64F120M * KWIKSTICK (K40) √ TWR‐K70120M √ COLDFIRE V1‐V4 TWR‐MCF51JF √ TWR‐MCF52259 √ TWR‐MCF54418 √ POWER ARCHITECTURE TWR‐PXD10 √ * MQX 4.1-based standalone release TWR‐PXS20 √ (separate installer than main release) TWR‐PXS30 √ TWR‐PXN20 √

TM External Use 12 Freescale MQX Lite RTOS Launched in 2012

MQX RTOS MQX Lite RTOS

Delivery Mechanism Traditional installer with full Processor Expert (PEx) Kernel source for Kernel, services and and services component, BSPs configurable software generated by PEx

I/O Drivers MQX POSIX compatible drivers PEx drivers only with option for using PEx drivers

Configurability User selects needed services Reduced services available; from full or lightweight versions lightweight options only

Example Footprint <10 Kbytes FLASH <8 Kbytes FLASH (3 tasks, sem, event) Kinetis K Series, ColdFire Kinetis L and K Series Processors, Vybrid ARM® Controller Solutions, Power Architecture solutions, Digital Signal Controllers

TM External Use 13 Freescale MQX Level 2 Support Accelerating MQX RTOS-based development projects

What are the benefits of MQX Level 2 Support? • Direct senior level support access • Specified response times • Support for software customizations • Troubleshooting support on custom hardware • Early access to software releases and bug fixes • Private support portal, telephone, & web conferencing support When to consider upgrading to MQX Level 2 Support? • Before next MQX RTOS-based development project starts • Tight resources or schedule, or just to insure project efficiency How to get MQX Level 2 Support? • Packages available for purchase at www.freescale.com/mqx/support • See website for complete details

TM External Use 14 Freescale MQX Support and Engineering Services

Level 1 Support Level 2 Support Engineering Services Plan Overview Basic Standard Premium Approx. once a Approx. once a Releases Available Quarter Quarter Early1 Access to MQX Online Community / Online Training Yes Yes Yes Service Requests (SW running on FSL Eval HW only) Yes Yes Yes Report bugs for fix in quarterly releases Yes Yes Yes BSP customization support ‐ Yes Yes Private Support Portal ‐ Yes Yes Software development Access to Early Beta Releases 1 ‐‐Yes services. On‐site Hot Fixes 2 ‐ Yes Yes support/training. Cost based on project Initial Response Time 3 ‐ 2 business days 1 business day definition. Max Hours of Support Engineer's Time 4 ‐ 20 hours 100 hours Web Conferencing to debug issue 5 ‐ 4 hours 10 hours Phone Support 5 ‐ Yes Yes Hands‐on Support of Customer‐Provided Hardware (shipped to Freescale Support) ‐‐Yes Support Plan Term ‐ 6 Months 12 Months Price Free $3,000 $12,000 Part Number ‐ DL‐MQXLVL2‐SDL‐MQXLVL2‐P

1 Early access to beta releases weeks/months before quarterly releases are typically available 2 Access to bug fixes on issues you report immediately when available 3 Amount of time to receive acknowledge of support request 4 Any time support engineer spends including time preparing bug fixes. 5 Hours counted in Support Engineers Time

TM External Use 15 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 16 Debugging through Low Power States • Some low power modes keep debug engine Fully Functional, static or shut off.

• Kinetis debug interface had been designed to support graceful reconnect of the debug connection when low power state is exited (using handshake bits in MDM_AP debug register)

• The IDE and debug probe tool may or may not support graceful reconnect . You should check with supplier of the tool if the supports of low power mode of Kinetis is effective or not

TM External Use 17 Example : CodeWarrior Support for debugging through Low Power Modes • Using OpenSDA/USB multilink (P&E micro) in LLS and VLLSx, debugger loses connection with target and a reconnect action is needed to continue with debug session once the target has recovered from these states • Control for reconnect behavior can be defined either on the first pop-up windows when a connection is lost either in: − Remote System View Æ Properties of the connection used Æ Advanced

• NOTE: behavior is saved per connection, but you can re-use connections in multiple projects

TM External Use 18 (active mode) Energy profiling - Tool off the shelf

Example : IAR I-scope • 12-bit A/D converter for current • Current Measurements − Uses a sensitive differential amplifier − Measures differential across a shunt resistor − max voltage = 100mV • Example: for ~40mA max use a 2.4 ohm shunt (this gives plenty of headroom)

TM External Use 19 (active/passive mode) Energy profiling

The range of current between the very low power states and RUN mode is large There is a factor x1000 between a standby mode = from hundreds of nA or a couple uA compare to Active mode = in the range of few mA

Using a shunt resistor also may not be convenient since there might no be ideal value for shunt It might be then of better option to use a current probe or dedicated hardware (Note : a tool like IAR scope have a resolution of 200uA)

TM External Use 20 (active/passive) Energy profiling with dedicated hardware

• Low current and Dynamic Measure • Auto-scale adjustment • Large Scale : 100 nA – 100mA • Precision 10nA • No-hardware calibration

Designed and published with courtesy of

D U T

Multiple shunts (3 shunts used)

TM External Use 21 Energy profiling using tool off the shelf & dedicated hardware Lauterbach allow multiple voltage/current probing while debugging [3..0] voltage inputs (0..5 V, 1 MOhm) I[2..0] current inputs (requires shunt resistance) 12 bit resolution (625 KHz sampling rate for one channel)

3 shunts used

TM External Use 22 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 23 Low Power Capabilities and application concern

What would be my concern as application designer : • What is still active while going into standby mode ? • What could be my wake event source ? • Are wake up to be regular scheduled or asynchronous ? • Do I spend more time in sleep than in active mode ? • How often do I wake-up ? • Does the RAM is preserved or not ? • How fast do I need to wake-up ?

Kinetis has flexible power modes − Kinetis has 10+ Run, Wait & Stop modes − This allow to select and customize power usage at best with application requirements

TM External Use 24 Kinetis Power Modes

Kinetis Extended Recovery “Typical” RAM Mode Peripherals activity Power Modes Time Idd Range Registers Wake-up event 278uA/MHz Run -

867uA @ 4MHz VLPR - CPU /peripheral clock maximum freq restricted Active

- Wait 7.5mA @ 50MHz Allows peripherals to function, while CPU goes to sleep reducing power consumption - VLPW 509uA @ 4MHz

5.2us 310uA Stop ADC, LPT, RTC, LCD, HSCMP, DAC preserved 5.2us 3.5uA and pin functional VLPS (Smart Peripherals for Kinetis L)

LLS 6us 2.1uA

VLLS3 7035us 1.5uA

Standby mode LLWU controls wakeup sources 70us 1.4uA VLLS2 4K including LPT, RTC, LCD, HSCMP, DAC and select pin interrupts. 130us+EE 678nA VLLS1 restore

VLLS0 367nA/176nA 32 bytes

TM External Use 25 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 26 MQX Low Power Manager

Starting with version 3.8, MQX integrates a Low Power Management (LPM) driver to take advantage of MCU low power capabilities.

TM External Use 27 MQX Low Power Manager

• The LPM driver included with Kinetis MQX BSPs has the following capabilities − Transitioning MCU power mode − Preparing other peripheral drivers for changing power modes − Changing clock configuration (Frequency Scaling) • LPM functionality is currently available for Kinetis platforms only • It must be enabled in user_config.h using the MQX_ENABLE_LOW_POWER configuration option.

TM External Use 28 MQX Low Power Manager Capabilities Transitioning MCU power modes • The LPM typically utilizes 4 operation modes, which are mapped to power modes of the MCU. This is defined at compile time. • In the K21 BSP, the LPM operation modes are mapped like this by default

• The operation mode mapping can be modified in init_lpm.

TM External Use 29 MQX Low Power Manager Capabilities Preparing other peripheral drivers for changing power modes

• The LPM provides a mechanism for other drivers in the BSP to register with the LPM to get notifications when the LPM changes the clock settings or power mode. • Add your application specific steps such as disabling/enabling peripherals, shutting down peripheral clocks, changing baud rates, reconfiguring pin functionality, etc, to callback functions registered with the LPM.

TM External Use 30 MQX Low Power Manager Capabilities Changing clock configuration (Frequency Scaling)

• LPM serves as a wrapper around another MQX component, the Clock Manager. • The Clock Manager can be configured manually or by Processor Expert to set up clock configurations used by the application.

clock config 0 clock 48 12 MHz MHz config 1 PEE PEE

2 MHz BLPI

clock config 2

TM External Use 31 MQX Low Power Manager Capabilities Additional Features

• Enabling/Disabling Idle Sleep Feature − Automatic transition into low power mode in idle task

• Waking up the Core from Low Power Mode after an − Kinetis MCUs feature the capability to automatically go back into certain low power modes when exiting an ISR that woke up the CPU. − The LPM can signal the CPU not to return to low power mode again after the ISR finishes. This is done by calling the function _lpm_wakeup_core() from the ISR that you want to use as the wakeup source.

TM External Use 32 MQX Low Power Manager Driver Details

• Applications call _lpm_set_operation_mode() or _lpm_set_clock_configuration() to change the LPM state.

• Most of the source code for the LPM can be found in \mqx\source\io\lpm

• Example application using the LPM can be found in \ mqx\examples\lowpower

• For more information see Chapter 21 Low Power Manager in the Freescale MQX™ I/O Drivers – User Guide

TM External Use 33 MQX Low Power Manager New in MQX 4.1: VLLSx Support

• VLLSx modes offer maximum power savings, but requires the system to go through a reset when exiting VLLSx modes and going back to a run mode. • The LPM is capable of putting the system into VLLSx mode and handling wake ups from the Low Leakage Wake-up Unit. • The LPM reports the wakeup source

TM External Use 34 Hands-on

• Running low power demo • Enabling the low power demo for UART wake-up • Enabling the low power demo for SW3 wake-up

TM External Use 35 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 36 What is the RTOS tick?

• Periodic timer interrupt used to keep track of time • Typically, it is 5ms, 10ms, 100ms periods • The priority of the interrupt is higher than tasks. Preempt tasks • Operating system time unit • Reflects the minimal time resolution

5ms

TM External Use 37 What is the RTOS tick?

• To allow for delays, timeouts, and measurements (MQX measures time in ticks, instead of in seconds and milliseconds) • MQX keeps the time internally as a 64-bit count of the number of tick interrupts • Features depending on the tick − Time delay − Timeout while waiting for events, semaphores, and so on − Software timers − Time-slice scheduling

TM External Use 38 The Tick can be disabled

• Context switches (jumping between tasks) can occur at any time. No need to wait for system tick. − Example: event gets set which immediately triggers the scheduler to switch to a task waiting on that event

• Scheduling occurs if any one of the following occurs: − the active task yields control − the active task calls a blocking MQX function − an interrupt occurs − a timeslice expires Only one that requires the tick − a higher priority task becomes ready

TM External Use 39 RTOS System Tick

What impact does the tick have on power consumption? • Run Modes: Minimal • Low Power Modes: Could wake up the system which has benefits and drawbacks What impact does the tick have on system efficiency? • Minimal, but it does preempt tasks and uses CPU cycles to update the time

TM External Use 40 SysTick Timer – Default MQX Tick

SysTick • ARMv7-M SysTick Timer – default MQX Modes Running? RTOS tick RUN, VLPR Yes • SysTick provides a simple, 24-bit clear- WAIT, VLPW Yes on-write, decrementing, wrap-on-zero STOP, VLPS No * counter. LLS No VLLSx No • Used for RTOS tick timer which fires at a

* Unless debugger attached. If debugger programmable rate and invokes a SysTick attached it will continue to run. routine.

• On Kinetis, it is clocked by the Cortex M4 FCLK (also clocks NVIC). Same frequency as system clock.

• Limited adjustability – cannot slow it down very much.

TM External Use 41 SysTick Timer – Default MQX Tick

Can the tick be shut off manually? Yes − SYST_CSR &= ~SysTick_CSR_TICKINT_MASK; /*disable systick */

Note: #define MQX_USE_TICK 0 /*this will not disable the tick, it will remove the time API functions.*/ − If there is no tick, then you can’t use the time delay, timeouts, and software timers. You have to use hardware timer interrupts or other interrupts to synchronize tasks.

Where is the tick service routine? − Init_bsp.c − void _bsp_systimer_callback(pointer dummy)

TM External Use 42 Low Power Timer – Can also be used for Tick

LPT • Low Power Timer (LPT), available in all low Modes Running? power modes RUN, VLPR Yes WAIT, VLPW Yes • Freescale Kinetis MCUs include a Low STOP, VLPS Yes Power Timer. LLS Yes VLLSx Yes • 16-bit time counter or pulse counter with compare

• Optional interrupt can generate asynchronous wake-up from any low- power mode

• Configurable clock source and 4-bit prescaler – can clock slower than SysTick

• Can use as system tick or a wake-up timer

TM External Use 43 Systick as the RTOS Tick

Advantages • Systick is automatically disabled in several low power modes • Using the Systick as RTOS Tick, frees up the LPT for other use Disadvantages • Less flexibility in tick period, than LPT • If entering low power mode with the tick disabled, you cannot rely on time calculated by the system tick, until the time is re-synced on wakeup

• The Systick is useful as the RTOS tick if: − The application can go to sleep with no ticks running

TM External Use 44 Low Power Timer (LPT) as the RTOS Tick

Advantages • LPT tick can wake you up from all low power modes • You can set the period longer than SysTick Disadvantages • LPT tick can wake you up from all low power modes

• The LPT is useful as the RTOS tick if: − The application has periodic tasks depending on the tick. Using the LPT as the system tick, lets the application keep the tick running in all low power modes. − The application can elongate the tick period for more time in low power mode.

TM External Use 45 Waking up for an Interrupt, going right back to sleep

• Kinetis MCUs return to low Interrupt power mode after servicing an interrupt if the sleep on exit bit is set. (Wait or Stop modes) Run MCU Power Mode

Low Power

TM External Use 46 Staying awake after an interrupt

• Even if the sleep-on-exit features is enabled, the MQX low power manager function call used within an ISR to keep the system from returning to sleep on exit from an interrupt. • Useful if an interrupt is used to wake up from low power mode.

/* Do not return to sleep after isr again */ _lpm_wakeup_core ();

• This clears the sleep on exit bit SCB_SCR &= (~ (SCB_SCR_SLEEPONEXIT_MASK));

TM External Use 47 The Tick Wakeup Problem

Tick Interrupt

5ms

Tried to go into low power mode for 100 ms, but had to wake up every 5 ms to service the tick

Run

Low Power

TM External Use 48 Tick Wake-up Problem Solutions

• Easiest solution − Use a mode/timer combo that disables the tick automatically. ƒ Unlimited Tick-less period ƒ Requires waking up from an interrupt / wake-up source ƒ Time gets out of sync / Can’t rely on ticks for task timing during tick off-time. • Other solution − Slow the tick down (extend tick period) ƒ Longer tick-less period when you are in low power mode ƒ Can still use ticks for scheduling tasks while in low power modes ƒ Time granularity reduced for tick-dependent features (Note: not interrupt servicing or time)

TM External Use 49 Affect of Slower Ticks – Reduced Granularity

• Example – Task A tries to wait for 10ms. _time_delay(10ms) /* block task for 10 ms */

Case 1 – 5ms tick Blocked for ~10ms! A

B 0 5 10 15 20 25 30 35 40

Case 2 – 15 ms tick Blocked for ~15ms… A

B 0 15 30 Note: Tick accuracy is 0-1 tick

TM External Use 50 Typical Kinetis MQX Stop Mode Tick-less SysTick as tick timer

With SysTick timer on Kinetis, ticks are automatically shut off in stop mode.

5ms

Wake up from an interrupt or wake-up source. Tried to go into low power mode for 25 ms Stayed asleep until it was time to get up!

TM External Use 51 Re-syncing MQX time with RTC

• When the tick is disabled, the time gets out of sync.

• Easily re-synced using the real time clock (RTC) or another clock source (network time, etc.)

TM External Use 52 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 53 Example Application Profiles

• Always active • Frequently active with short idle periods • Bursts of activity with long idle periods • What is yours?

Choices to make when architecting your application

• When do you want to go to into low power modes? − When in the idle task? (Automatic) − From an application task? (Manual) • How fast do you need to wake up? • What do you want the wake up trigger(s) to be? • Do you have periodic tasks that need to always run? • How precise does your tick timing need to be?

TM External Use 54 Example Application 1

Frequently active with short idle periods Sleep Wait Mode while idle • Low Power Features Used Ticks continue to run. − Sleep while idle Puts MCU into low power between ticks. Normal Sleep while idle Operation • When no task needs to run, the idle task will put the Run Mode MCU in low power mode. Typically Wait mode.

Run Mode Run Mode

Task A Task A Wait Mode Task B Task B Automatic – Idle Task handled in the idle task

TM External Use 55 Example Application 2 Wait Bursts of activity with long idle periods Sleep while idle • Low Power Features Used

− Sleep while idle Run − Low power mode entry from application task Normal Operation VLPS Low power mode entry or Standby LLS • When nothing to do for an Fast RTOS extended time, go to sleep Wake-up System Tick with no ticks running Turned off

Wakeup Event Example Applications Handheld device – If no user input or • Timer, RTC, or GPIO data received after ~10 seconds Controller - sleep for long periods of time between tasks

TM External Use 56 Wait Example Application 3 Sleep Bursts of activity with long idle periods while idle • Low Power Features Used − Sleep while idle Run − Low power mode entry from Mode application task Normal − Low power mode entry into Operation VLLSx (very low leakage stop) – now supported in MQX 4.1 LLS

Standby Low power mode entry • When nothing to do for an Fast extended time, go to sleep with Wake-up no ticks running. • After more time with nothing RTOS going on, go to the lowest power System Tick mode. Slower Shelf Turned off Wake-up Wakeup Event VLLSx • Timer, RTC, or GPIO • Wakeup slower due to system Note: wake-up times from reset when exiting VLLSx low power modes can be optimized by using the FLL as the system clock source

TM External Use 57 Example Application 4 VLPR (4 MHz)

RUN (50 MHz) POLL LLS

STBY CALC Fast Wake-up RTOS System Tick Turned off Slower Wake-up SHELF VLLS1 CALC CALC

POLL POLL POLL POLL STBY SHELF

TM External Use 58 Hands-on

• Running a few of the application examples created for this class • Demonstrates the following features − Sleep while idle − Entering low power mode when no user input – with fast wakeup − Entering very low power mode with slower wakeup − Re-syncing MQX time after tick shut off

TM External Use 59 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer (Cont’d) − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 60 Changing the TICK Time in MQX

• There are two ways to change the TICK timer. 1. Changing the SysTick within the BSP 2. Use the LPTMR as the TICK

TM External Use 61 Changing the SysTick within the BSP

• BSP timer is clocked by system tick. • It is possible to edit BSP_ALARM_FREQUENCY in order to have smaller ticks.

Remember: we cannot guarantee the correct behavior if you modify original settings. Only change this value if you know what you are doing.

TM External Use 62 Changing the SysTick within the BSP

• By default, it is defined to get 200 ticks per second. In order to change this value it is necessary to go to the BSP project and change the value of the next macro:

#ifndef BSP_ALARM_FREQUENCY #define BSP_ALARM_FREQUENCY (200) #endif

• This macro sets the number of ticks per second. • This macro can be found in .h file. \ mqx\source\bsp\

TM External Use 63 Changing the SysTick within the BSP

• Delays are calculated in the following way: _ × __ sperticksmsREQ _TICKSN = 1000 ms

N_TICKS = Number of ticks REQ_ms = Number of milliseconds requested ticks_per_s = Number of ticks per second

TM External Use 64 Changing the SysTick within the BSP

• Example: If BSP_ALARM_FREQUENCY is set as default (100) and you request a 55ms delay you will have: 55 ms ×100 ticks _ TICKSN = = 5.5 ticks 1000 ms

This value will be truncated to 5 ticks. If it is requested any delay from 0 to 9 ms then it is necessary to have 0 ticks. But you will have some latency delay.

TM External Use 65 Using the LPTMR as the TICK in two steps

STEP 1: At the beginning of the task used for initialization call this function: _lpt_install_kernel();

• With these parameters: • Timer to initialize • Period in microseconds • Input clock sources mask • Interrupt priority • Unmask the timer after installation • Example: _lpt_install_kernel(0,5000,LPT_FLAG_CLOCK_SOURCE_LPO,2,TRUE);

TM External Use 66 Using the LPTMR as the TICK in three steps

STEP 2: After disabling the SysTick from the core: SYST_CSR &= ~SysTick_CSR_TICKINT_MASK;

TM External Use 67 Hands-on

• Enabling the Low Power Timer as RTOS TICK

TM External Use 68 Agenda

• Quick Review of MQX Software Solutions • Tools for Analyzing MCU Power • Kinetis MCU Low Power Features • MQX RTOS Power Management Features − Hands On • Optimizing Applications for Low Power − Optimizing/Disabling the System Tick Timer − Architecting State Transitions − Hands On • MQX Lite RTOS Power Management Features − Hands On

TM External Use 69 MQX Lite Low Power Features

• MQX Lite in CW 10.5 − Supports clock mode changes and sleeping while idle

Processor Expert Low Power Features • Logical device drivers in conjunction with processor component implement low power features of a target microcontroller.

• Each LDD component defines two methods related to the low power capability − SetOperationMode() − GetDriverState().

TM External Use 70 Processor Expert Cpu_SetOperationMode

TM External Use 71 Usage of Low Power API in Logical Device Drivers

TM External Use 72 Changing the System Tick in MQX Lite

Go to ProcessorExpert components -> MQXLite -> SystemTimer1 -> Properties and change 1. Counter from SYST_CVR to LPTMR0_CNR 2. Counter direction from Down to Up 3. Regenerate code recompile 4. That’s all.

TM External Use 73 Hands-on Demo

• MQX Lite Example – Entering/Exiting Low Power

TM External Use 74 Key Take-Aways and References

TM External Use 75 75 Session Summary

• You can create low power applications while using an RTOS. • MQX RTOS for Kinetis MCUs has tick-less modes. • MQX & MQX Lite RTOS Power Management capabilities allow you to take control of your applications to save energy and prolong battery life.

TM External Use 76 References

• AN4503 Power Management for Kinetis and ColdFire+ MCU

• AN4447 Freescale MQX Low-Power Management

• AN4470 Using Low Power modes on Kinetis family

TM External Use 77 Become an MQX RTOS Pro!

• Download the Latest Releases • Check out the Learn to use MQX page • Watch the Online Training Videos • See the 80+ Examples & Demos • Read the 12+ Application Notes • View the Getting Started Guides • Attend more in-person Training Events • Collaborate in the MQX Community Best way • Start creating applications! Start with an example. to learn

TM External Use 78 Freescale MQX™ Software Solutions www.freescale.com/mqx

TM External Use 79 TM

www.Freescale.com

© 2014 Freescale Semiconductor, Inc. | External Use