Teaching Embedded System Design And Optimization With

Transcription

Teaching Embedded SystemDesign and Optimization with theARM Cortex-M0 MicrocontrollersDr. Alexander G. DeanDept. of ECENorth Carolina State UniversityRaleigh, M University ProgramCopyright ARM Ltd 20141

Course Approach Hands-on MCU development experience Programming in C with free toolchain from Keil Simple, inexpensive hardware Easy system expansion with Arduino-compatible hardware Relevant, useful material based on 13 years of experience Interaction with industry through on-site design reviews of real embedded systemsTeaching large (50 – 120 students) undergraduate and graduateembedded system coursesPrerequisites Introductory course: introduction to computer organization, Cprogramming Advanced course: introductory course. Other courses also helpfulARM University ProgramCopyright ARM Ltd 20142

Course Materials Easy adoption for your own course Flexibility with modular design All source files provided (pptx, docx, vsd, c, h ) Course modules typically include PowerPoint slides/lecture notes Demonstration code for use in lecture and outside of class Homework questions and solutions Lab exercise(s) with step-by-step procedure and questions Programming project(s) with solution Status Introductory course materials available now Advanced course materials available early summer Developing a textbook to support both coursesARM University ProgramCopyright ARM Ltd 20143

ARM University ProgramCopyright ARM Ltd 20144

Worldwide Adoption Video introductionNearly 100 adoptions since launch last summer North & South America, Europe, Asia, Africa “We were delighted to be one of the first institutions to receive the ARMUniversity Program's Lab-in-a-Box on Embedded Systems. It has immediatelyproven itself to me as an excellent resource for our research and teachingactivities.” Dr. Boris Adryan, University of Cambridge, UK. "Freescale is delighted to be building on our longstanding relationship withARM by providing access to our solutions to universities and electronicengineering students around the world. The Lab-in-a-Box is just one wayFreescale and ARM collaboratively reach out to our engineers of the futureand help us create a new wave of innovative embedded technologies that willdrive our increasingly connected world.“ Andy Mastronardi, Director, University Programs, FreescaleARM University ProgramCopyright ARM Ltd 20145

Cortex Processor Cores Cortex-A: application profile High performance, multiprocessing Cortex-R: real-time profile Predictable performance Cortex-M: microcontroller profile - optimized for embedded applications Implementation Short pipelineFast interrupt responseLow cost, low powerFast GPIO access Instruction set Good code density (16-bit Thumb 2 instructions)Bit and byte operationsOptional single-cycle multiply instruction, hardware divide, saturated mathOptional DSP & SIMD instructionsOptional floating point unitARM University ProgramCopyright ARM Ltd 20146

Target Board – Freescale Freedom KL25Z 32-bit ARM Cortex-M0 processor Freescale Kinetis MKL25Z128VLK4microcontroller Extremely low power use48 MHz max processor clock freq.128 KB Flash ROM, 16 KB RAMWide range of peripherals, includingUSB on-the-go FRDM-KL25Z board 13 (USD)Peripherals: 3-axis accelerometer, RGBLED, capacitive touch slider Expansion ports are compatible withArduino shield ecosystem – endlessopportunities, low-cost hardwarembed.org enabled - online softwaredevelopment toolchain, reusable code ARM University ProgramCopyright ARM Ltd 2014Images courtesy of Freescale7

Hardware Ecosystem Arduino shields Wide variety Low cost High volume Xtrinsic sensor boardfrom element 14Images courtesy of Freescale, Adafruit, Element 14, Parallax, Seeed StudioARM University ProgramCopyright ARM Ltd 20148

And Even More ShieldsImage courtesy of Seeed StudioARM University ProgramCopyright ARM Ltd 20149

SOFTWARE DEVELOPMENTTOOLSARM University ProgramCopyright ARM Ltd 201410

Software Development Suite: MDK-ARM Low cost tools for ARM7, ARM9, Cortex-M and Cortex-R4 MCUs Extensive support for many devices Core and peripheral simulation Flash support Integrated development environment with ARM compiler Full (pro) version available for teaching, free32 KB size-limited version available also Debugger with full access to program, core and peripherals Real-time trace on devices based on Cortex-M3 and M4 Real-Time Library KEIL RTX RTOS Source Code TCP networking suite, Flash File System, CAN Driver Library, USB Device Interface Debug HardwareEvaluation boardsSeparate support channelSee www.keil.comARM University ProgramCopyright ARM Ltd 201411

CURRICULUM OVERVIEWARM University ProgramCopyright ARM Ltd 201412

Curriculum Overview Introductory Course: Building an Embedded System with aMicrocontroller Microcontroller conceptsSoftware design basicsARM Cortex-M0 architecture and interrupt systemC as implemented in assembly languagePeripherals and interfacing Advanced Course: Embedded System Design, Analysis andOptimization Creating responsive multithreaded systemsOptimizing code speedOptimizing system power and energyOptimizing memory requirementsDetails in appendixARM University ProgramCopyright ARM Ltd 201413

Introductory Course ModulesSoftware Design BasicsEmb. SWConcurrencyCMSISEngineeringCortex-M0 Processor CoreC as Implementedin Assembly Lang.InterruptsHW & SW forRobustnessGP I/OSerialComm.Analog I/ODMAUsing ArduinoShieldsARM University ProgramCopyright ARM Ltd 201414Timers

Introduction to Embedded Systems What is an Embedded System? Why add a computer to the larger system?Differences between Embedded and general-purposecomputersMicrocontrollers andmicroprocessors Embedded system Functions Attributes Constraints EconomicsARM University ProgramCopyright ARM Ltd 201415

Embedded MCU vs. General-Purpose CPU Both have a CPU core to executeinstructionsMicrocontroller has peripherals forconcurrent embedded interfacingand control AnalogNon-logic levelsignalsTiming, communicationsReliability and safetyEmbedded systems haveconcurrent, reactive behaviors Must respond to sequences andcombinations of events Real-time systems have deadlines onresponses Typically must perform multipleseparate activities concurrentlyARM University ProgramCopyright ARM Ltd 201416

Concurrent Hardware & Software ime Embedded systems rely on both MCU hardware peripherals andsoftware to get everything done on timeARM University ProgramCopyright ARM Ltd 201417

Advanced Course Modules (1/2)Concurrency Conceptsand InterruptsCooperativeTask SchedulingPreemptiveTask SchedulingDesign, Analysis& Optimization ofReal-Time SystemsC as Implementedin Assembly Lang.Execution-TimeProfilingExaminingObject CodeSource Code andToolchain TuningHigh-LevelOptimizationsCMSIS-DSP andCortex-M0 FeaturesARM University ProgramCopyright ARM Ltd 201418

Advanced Course Modules (2/2)Power & EnergyModeling & AnalysisC ProgramMemory Use ConceptsKL25ZMCUTools for AnalyzingMemory UseCortex M0 CoreFreedomBoardOptimizing Powerand/or Energy withSleep and DVFSARM University ProgramCopyright ARM Ltd 2014ROM SizeOptimizationRAM SizeOptimization19

COURSE MODULE DETAILSARM University ProgramCopyright ARM Ltd 201420

INTRODUCTORY COURSEARM University ProgramCopyright ARM Ltd 201421

Software Development, Processor & InterruptsModulePresentationsIntroduction toEmbedded SystemsSW Design Basics:Concurrency, SWEng. & CMSIS APIsCortex-M0 Processor CorePresentationHomeworkand ationSolutionsC Code asImplemented inAssemblyLanguageInterruptsPresentationC/Asm Demo 1Code,Demo 2 CodeSolutions,source projectPresentationInterrupt DemoCode, NotesSolutions,spreadsheetARM University ProgramCopyright ARM Ltd ProjectText Processing in Integer Square RootAssemblyApproximationLanguage Assignment Lab Exercise Starter code Code SolutionExaminingToolchain Output Lab Exercise CodeMeasuringInterrupt Timing Lab ExerciseHuman ResponseTimer Assignment Solution22

Using PeripheralsGeneral PurposeDigital InterfacingPresentationAnalog InterfacingPresentationGPIO Demo Code(includes BasicLight Switch, RGBLED Flasher,Speaker tonegenerator, Text LCDwith parallel bus)Analog InterfacingDemo CodeSolutions,SpreadsheetBasic UserSlide WhistleInterface with LCD Assignmentand switches Solution Lab Exercise CodeSolutions,spreadsheetADC: Voltmeter Lab Exercise CodeComparator:Voltage Monitor Lab Exercise CodeDAC: SignalGenerator Lab Exercise CodeSignal Generatorwith PrecisionTiming andBuffering Lab Exercise Code SolutionInterfacing withArduino AnalogDevicesTimersARM University ProgramCopyright ARM Ltd 2014PresentationTimer Demo CodeSolutions,spreadsheetInfrared ProximitySensor Assignment SolutionClock with PulsingLED Assignment SolutionUsing PWM tocontrol motor Speed Assignment Solution23

Using PeripheralsSerialCommunicationPresentationI2C andAccelerometerSolutionsUARTPerformanceAnalysis Lab Exercise CodeSolutionsTesting anembeddedsystem’srobustness Lab Exercise CodeEvaluatingMemory CopySpeeds Lab Exercise CodeCreating a ConsoleInterface with aUARTImproving SystemRobustness withHardware andSoftwarePresentationUsing DirectMemory Access toImprovePerformancePresentationARM University ProgramCopyright ARM Ltd 2014Interfacing withArduino SerialDevicesWatchdog TimerStack OverflowDetectionMemory CopySolutions& ISR ReplacementUART: Creating aSpeedometer with aGPS Receiver Assignment SolutionInterfacing with anSD memory cardusing SPI Assignment SolutionMaking a systemrobust Assignment SolutionDMA: Upgradingfrom ISRs to DMA Assignment Solution24

ADVANCED COURSEARM University ProgramCopyright ARM Ltd 201425

Building Multithreaded SystemsModulePresentationsIntroduction toAdvanced TopicsManagingConcurrency withCooperative andPreemptive ations withRTOS SupportPresentationData race conditionswith preemptionSolutionsDesign, Analysis, andOptimization of RealTime SystemsAdvanced Debuggingwith Cortex-M0 &MDKPresentationResponse timeevaluationSolutionsPresentationMicrotrace bufferKernel-awaredebugging with MDKARM University ProgramCopyright ARM Ltd 2014PresentationDemonstrationCodeHomeworkand TX ponsiveness Assignment Code SolutionUsing RTOSMechanisms Assignment Code SolutionUpgrading theWaveform Generatorto use an RTOS Assignment SolutionNonpreemptiveSchedulerInstrumenting RTX andverifying task timing Assignment SolutionUsing the MTB Assignment Code26

Performance Analysis and ofiling ProgramExecution TimePresentationProfiling SphericalGeometryCalculationsExamining ObjectCode without GettingLostSpeed Optimizationwith Toolchain TuningPresentationSample programSolutionsPresentationTuning the toolchainSolutionsSpeed Optimizationwith ProgramTransformationsDSP Acceleration withCortex-M0 and theCMSIS-DSP LibraryPresentationOptimizing Real-time audiofilteringSolutionsARM University ProgramCopyright ARM Ltd 2014Homeworkand gProjectProfiling Lab Lab Exercise CodeTilt-compensatedcompass profiling Assignment SolutionEvaluating CompilerOptimizations Lab Exercise CodeToolchain tuning forthe TC compass Assignment SolutionCode optimization forthe TC compass Assignment SolutionUsing the CMSIS-DSPlibrary for an ultrasonicrangefinder Assignment Solution27

Power and Energy Analysis and OptimizationModulePresentationsPower and EnergyAnalysisPresentationKL25Z Features forLow Power and EnergyPresentationEvaluating Power inActive and SleepModesSolutionsOptimizing Power orEnergy UsePresentationAnalyzing andoptimizing datalogger energy useSolutionsARM University ProgramCopyright ARM Ltd 2014DemonstrationCodeHomeworkand gProjectFreedom BoardPower Analysis Lab Lab Exercise CodeFreedom BoardEnergy Analysis Lab Exercise CodeEvaluating KL25ZLow-Power StandbyModes Lab Exercise CodeKL25Z Voltage andFrequency Scaling Lab Exercise CodeThis Side Up:Optimizing anorientation logger forlower energy use Assignment Solution28

Memory Analysis and ofiling and ReducingROM and RAMMemoryRequirementsPresentationGraphics renderingsize profiling andoptimizationARM University ProgramCopyright ARM Ltd 2014Homeworkand gProjectEvaluating theimpact of thecompileroptimizations andtoolchain optionsReducing RAM andROM for amultithreaded system Assignment Solution29

INTRODUCTORY COURSEARM University ProgramCopyright ARM Ltd 201430

Introduction to Embedded Systems Design Embedded System Fundamentals ConcurrencySoftware Engineering for Embedded SystemsCMSISImproving System Robustness with Hardware and SoftwareProcessor Cortex-M0 Processor Core C Code as Implemented in Assembly Language Interrupts Using Peripherals General Purpose Digital InterfacingAnalog InterfacingTimersSerial CommunicationDirect Memory AccessARM University ProgramCopyright ARM Ltd 201431

Introduction to Embedded Systems What is an Embedded System? Why add a computer to the larger system?Differences between Embedded and general-purposecomputersMicrocontrollers andmicroprocessors Embedded system Functions Attributes Constraints EconomicsARM University ProgramCopyright ARM Ltd 201432

Software Design Basics Concurrency in software andhardware Time Peripherals Software tasksTask scheduling and response time Prioritization Preemption Software engineering Development models Design before coding Graphical representations: statecharts, flowcharts,sequence diagramsEssential UMLPeer reviewTesting conceptsARM University ProgramCopyright ARM Ltd 2014StaticRecSwLCDDecCheckDynamic Run-to-CompletionRecDecCheckDynamic PreemptiveDecCheck33

Cortex Microcontroller Software Interface Standard Vendor-independenthardwareabstractionlayer for Cortex-MStandardizesinterfaces to Processor corePeripheralsDebug access portRTOSProvides Optimized libraries of DSP functions infixed and floatingpointPeripheral systemview descriptionARM University ProgramCopyright ARM Ltd 201434

Cortex-M0 CPU Core Processor core registersMemory space, contents andaddressingARMv6-M Thumb instruction setoverviewARM University ProgramCopyright ARM Ltd 201435

C as Implemented in Assembly Language We program in C for convenience,LoweraddressActivation recordfor currentfunctionbut should understand theassembly code implementing it Activation recordfor caller functionCode efficiencyEase of analysisAn overview of what C getscompiled to(Free stack space)HigheraddressActivation recordfor caller’s callerfunctionActivation recordfor caller’s caller’scaller functionLocal storageReturn addressArgumentsLocal storageReturn addressArgumentsLocal storageReturn addressArgumentsLocal storageReturn addressArgumentsC start-up moduleRegister useActivation recordsSubroutinesData types &classesUsing pointersControl flowARM University ProgramCopyright ARM Ltd 201436 - Stack ptr

Exceptions and Interrupts Exception and Interrupt Concepts Vector tableStack useProcessing sequenceEntering an Exception HandlerExiting an Exception HandlerCortex-M0 Interrupts NVIC interrupt controller, exceptionmask, prioritization Using Port Module and ExternalInterrupts Timing AnalysisProgram Design with Interrupts Sharing Data Safely Between ISRsand Other Threads Data atomicity and race conditionsVolatile dataARM University ProgramCopyright ARM Ltd 201437

General-Purpose I/OData Busbit n GPIO Basic ConceptsPort CircuitryControl RegistersAccessing Hardware Registers in CClocking and MuxingAddressBusAddressDecoderPDDR selectDPSOR selectPCOR selectPTOR selectPin orPad onpackageQI/O ClockPDIR selectSwitchesOutputs SetRst Port DataTgl OutputD RegisterInputs QPDOR select Circuit Interfacing Port DataDirectionRegisterDPort DataInputRegisterPin ControlRegisterMUX fieldQLEDsSpeakerBoth Interfacing with a Text LCDARM University ProgramCopyright ARM Ltd 201438

Demo, Lab and Project Demo Basic Light Switch RGB LED Flasher Speaker tone generator Lab Interfacing with a generic text LCDand switches Can target Arduino LCD switchshield instead Project Slide whistle sound effect generatorARM University ProgramCopyright ARM Ltd 201439

Analog Interfacing111111Analog and digital domains Quantization and transfer functions SamplingReference voltage DAC Analog to digital converter know 10011x, try 100111 know 1001xx, try 100110 Digital to analog converter Analog comparatorknow 100xxx, try 100100KL25Z Peripheralsknow 10xxxx, try 101000 100110100100know 1xxxxx, try 110000 DACComparatorADC – flash, successive approximationAnalogInputT1T2Start ofConversionT3T4T5T6know xxxxxx, try 100000ConvertersVoltage Test voltage(DAC output)TimeClock configurationInput channel multiplexerConversion triggersSpecial features: averaging, low power,repeat, automatic compareARM University ProgramCopyright ARM Ltd 201440100000know 100110. Done. 000000

Demos, Labs and Projects Demo Measure voltage with ADC Detect low voltage with comparator Waveform generator with DAC Labs ADC – Supply voltage monitor Comparator – Low voltage alarm DAC – Waveform generator Project Infrared proximity sensor using ADC anddigital outputObject present, reflectsIR back to receiverARM University ProgramCopyright ARM Ltd 201441

Timers Concepts Elapsed time measurementEvent countingPeriodic interruptsInput captureOutput comparePulse-width modulationSoftware data queuesKL25Z Timers Periodic Interrupt TimerTimer/PWM ModuleLow-Power TimerSys TickARM University ProgramCopyright ARM Ltd 2014InterruptRead/write timer start value (TSV)from PIT LDVALnStart ValueReloadClockPresettableBinary CounterRead current timer value (TVL)from PIT CVALn42Interrupt

Demo, Lab and Project Demo Count interrupts, adjust PWM signalbased on board tilt as measured byaccelerometer Lab Signal generator with precision timingand buffering Projects Time-of-day clock with pulsing LED Using PWM to control a motor’sspeedARM University ProgramCopyright ARM Ltd 201443

Serial Communications Concepts Processing binary and text messagesget stringKL25 I2C peripheralARM University ProgramCopyright ARM Ltd 2014buf SDDBT, VWVHW, or YXXDREnqueue all chars. frombufSentenceBodyAny char. except *Enqueue charChecksum1Any char.Save as checksum1Checksum2Any char.Save as checksum2tx isrTbit*10.5send stringTbit*9.5ConceptsAny char. except *, \r or \nAppend char to buf.Inc. counterTalker SentenceType*Enqueue charI2C communications Tbit*8.5KL25 SPI peripheralTbit*7.5ConceptsTbit*6.5/r or /nTbit*5.5KL25 I2C peripheral Append char to buf.*, \r or \n,non-text, orcounter 6Tbit*4.5ConceptsTbit*3.5StartTbit*2.5Data SamplingTime atReceiverTbit*1.5Software: polling, interrupts andbufferingSPI communications ToolsUART communications DatabitsTimeZero Serial communicationsrx isrSerialInterface44

Demo, Lab and Projects Demo I2C communication with onboard accelerometer Console interface with a UART Lab UART performance and timing analysis Projects UART: Creating a speedometer with a GPS receiver SPI: Interfacing with an SD memory cardARM University ProgramCopyright ARM Ltd 201445

Improving System RobustnessStart WDTRestart WDTWDTValueWDT times out,resets systemTime Low voltage detectorRestart WDTSF RegsGlobal DataHeap Watchdog timerB Stack Defensive programming Stack depth analysisA StackMonitor RAMThread A Testing and test coverageARM University ProgramCopyright ARM Ltd 2014InstructionsThread B46

Direct Memory Access Basic Concepts DMA peripheral Selecting trigger sources DMA Peripherals in Cortex-M0 DMA Applications Data TransferReplacing ISRsARM University ProgramCopyright ARM Ltd 201447

Demo, Lab and Project Demo Memory copy Waveform playback to DAC withoutISR Lab Evaluate memory copy speed withdifferent DMA configurations Project Remote data acquisition system withserial control and analog data inputARM University ProgramCopyright ARM Ltd 201448

ADVANCED COURSEARM University ProgramCopyright ARM Ltd 201449

Advanced Design, Analysis and Optimization Advanced Scheduling and Design Cooperative and Preemptive SchedulersDesigning Multithreaded SystemsSharing Data Safely with RTOS SupportTiming Analysis of Real-Time SystemsAdvanced Debugging with Cortex-M0 Analysis and Optimizations Code Execution Speed AnalysisOptimization Power and Energy Analysis and ModelingOptimization Memory Requirements AnalysisOptimizationARM University ProgramCopyright ARM Ltd 201450

Cooperative and Preemptive Schedulers Task scheduling and response time Prioritization and preemption Non-preemptive scheduling Task states and scheduling rulesScheduler implementationRTX API and exampleLimitations Response timePrioritizationSoftware structurePreemptive scheduling Task states and scheduling rulesScheduler implementation and context switching mechanicsRTX API and exampleLimitations Data sharingMemory useARM University ProgramCopyright ARM Ltd 201451

Designing Multithreaded Systems What is in an RTOS? Bounded response timesPreemptionTime managementSynchronizationTask creation & controlSignaling eventsSharing data safely Concepts Data atomicityReaders and writersKeil RTXReal-Time Operating SystemRace conditions Mechanisms Synchronization objectsScheduler lockInterrupt maskingARM University ProgramCopyright ARM Ltd 201452

Creating Real-Time Systems Periodic task model Releases, periods and deadlinesWorst-case execution time(analytical and empirical)P10MetricsPriority-based scheduling Priority assignment Fixed priority (RM, DM) Response time analysis Utilization bound schedulability test P2P2P3 Response time Schedulability P1P1P2 Simplifying assumptions P11P323456 7Time89 10 11 12 Ri Ri Ci C jj hp ( i ) T j (U Max m 21/ mDynamic priority (EDF) Response time analysisUtilization bound schedulability testARM University ProgramCopyright ARM Ltd 201453) 1

Handling More Complex RT Systems Supporting aperiodic tasks an Ri Ci Bi C jj hp ( i ) T j Non-zero context switch times Dependencies between tasksH Dealing with priority inversion31LR4HMM52RLL Dealing with WCET ACET Supporting different deadlinesARM University ProgramCopyright ARM Ltd 201454

Lab and Projects Lab – Response Time Comparison Non-preemptive, non-prioritized Non-preemptive, prioritized Preemptive, prioritized Projects Worst-case execution time analysisfor the Cortex-M0 Instrumenting RTX and verifying tasktimingImage courtesy SparkfunARM University ProgramCopyright ARM Ltd 201455

Advanced Debugging with Cortex-M0 CoreSight Micro Trace Buffer Data Watchpoints Hardware breakpoints Kernel-aware debugging in Keil MDKARM University ProgramCopyright ARM Ltd 201456

Code Execution Speed Analysis Overview Timing Methods Timer peripheral Scope with twiddle bits Profiling Methods Program counter sampling Hardware trace support Object Code Inspection How to keep from getting lostARM University ProgramCopyright ARM Ltd 201457

Code Execution Speed Optimization Rationale and Trade-offs Design-time vs. Compile-time Optimizations Maintainability and Portability vs. Fast Code The Evils of Premature Optimization Trust but Verify (the Compiler) Using the Compiler to the Fullest What should the compiler be able to do? Helping and persuading the compiler Precalculation Algorithms, Data Organization and Data Structures Math Fixed point and integer math Reduced precision floating-point math Polynomial approximationsARM University ProgramCopyright ARM Ltd 201458

Cortex-M Optimizations CMSIS-DSP Library Primarily supports vectors and matrices for DSPVersions optimized for Cortex-M0, M0 , M3, or M4Data types Floating pointFixed point: q7, q15, q31, q63Wide range of functions available Basic math, fast math, complex math Filters, transforms, matrix functions Motor control, Statistical functions Support functions Interpolation functionsCortex-M0 -specific coding practicesARM University ProgramCopyright ARM Ltd 201459

Demo and Project Demos Profiling and optimizing sphericalgeometry code Project Profiling and optimizing a tilt-compensatedcompassARM University ProgramCopyright ARM Ltd 201460

Power and Energy Analysis Modeling fundamentals Basic models Static & dynamic power Optimizing for power vs. energyPower systems Voltage regulators and switching Modeling system power Measuring current and power KL25Z processorFreedom boardSampling V and I Measuring energy Sampling V and I and integratingUsing an ultracapacitorARM University ProgramCopyright ARM Ltd 2014Capacitor Voltage convertersSwitches (diodes and transistors)V1V2ΔtTime61

Demos and Labs Demos Power measurementUltracapacitor-basedenergy measurementModeRunWaitStopStop 3Stop 1Stop 0MCU Current (µA) at VDD 3VNormal LLVLLVLP500025037001353451.94.41.40.770.38MCU? Labs Freedom board power analysis –where does the power go?Energy analysis – how long will theultracap power the board?ARM University ProgramCopyright ARM Ltd 201462Power

Power and Energy Optimization Optimizations for the MCU Standby and low-power modesClock gatingVoltage scaling and conversionFrequency scalingVoltage scalingClock frequency scalingVoltage and frequency scalingActive & sleep modesIntegrating power and energymanagement into 60.40.200102030MCU Clock Frequency (MHz)1.61.41.21.00.80.60.40.20.0 Non-real-time systems Real-time systemsARM University ProgramCopyright ARM Ltd 201440Average PowerPower (mW)System optimization challengesOptimizations for peripheralsAverage Power (mW) 6350

Analysis of Memory Requirements Memory is free up to a point afterwhich it becomes expensive Reducing memory requirements mayenable Use of a less expensive MCU Implementation of a moresophisticated algorithm More diagnostic code More fault logging Determining Memory Requirements Program memory use Static, automatic and dynamic dataCode memoryUnderstanding the linker map fileARM University ProgramCopyright ARM Ltd 201464

Optimization of Memory Requirements Optimizing Data Memory Language support for read-only data Toolchain support Memory modelsData sizesPacked data structures and bitfields Improving stack memory size estimation Shrinking activation records Using stack-friendly functionsARM University ProgramCopyright ARM Ltd 201465

Task 3 Max StOptimization of Memory Requirements Optimizing Code Memory Function outliningMemory modelsNon-preemptiveDynamicTask 2 Max Stack Language support Toolchain configurationPreemptive DynamicOptimized library variants Reducing or eliminating preemptionTask 1 Max Stackmemory estimatesTask 4 Max Stack Improving the accuracy of stackTask 3 Max StackOptimization for MultitaskingSystemsTask 2 Max Stack Task 1 Max Stack Improving similar or identical code Combining tasks to reduce stackcountTask 1 StaticsTask 1 Statics Preemption threshold schedulingTask 2 StaticsTask 2 StaticsTask 3 StaticsTask 3 StaticsTask 4 StaticsTask 4 StaticsARM University ProgramCopyright ARM Ltd 201466

EXAMPLE PROJECTSARM University ProgramCopyright ARM Ltd 201467

INFRARED PROXIMITYSENSORARM University ProgramCopyright ARM Ltd 201468

ConceptsNo object present, noIR reflected back to receiverObject present, reflectsIR back to receiver Detect object by shining infrared light and measuring impact on ambientlight level Components Infrared LED – emits IR light Infrared phototransistor – conducts more current as IR increasesARM University ProgramCopyright ARM Ltd 201469

Using Differential Measurements Basic approach of measuringambient reflected light isunreliable Vulnerable to changes inambient light due to flicker inlight sources, shadows, etc. Use differentialmeasurements insteadMeasure IR levelwith IRLED off Measure brightness withIRLED off Measure brightness with IRLED onDifference in brightness levelsindicates amount of IRreflectedARM University ProgramCopyright ARM Ltd 2014Measure IR levelwith IRLED on70

Response Time Issues IR Sensor (phototransistor)does not respondinstantaneously Has internal capacitance which must be charged or dischargedRate of change depends onbrightnessNeed to introduce time delay inprocessing sequence Change IRLED value Wait for some time for sensor toIRLEDOffOnOffOnOnIR SensorDarkerLighterrespond Read IR SensorARM University ProgramCopyright ARM Ltd 201471

BUBBLE LEVEL WITHTEXT LCDARM University ProgramCopyright ARM Ltd 201472

Learning Objectives Configuring GPIO pins forinput and output Interfacing with Text LCDcontroller Developing Code Printing text Interfacing withaccelerometerARM University ProgramCopyright ARM Ltd 201473

Hardware OverviewSupplyVDDText LCD ModuleMCUEnable ERead/ Write R/ WRegister Select RSData Bus DB0-7LCDController(HD44780orequivalent)16 Rows40 ColumnsSerial DataContrastAdjustmentVO MCU communicates with LCDcontroller via Parallel data bus (DB0-7)Read/ WriteRegister Select (register or data?)EnableARM University ProgramCopyright ARM Ltd 2014 LCD Glass40 Col.40 Col.DriverDriverGroundVSSLCD controller interprets commandsfrom MCU Write to display memoryChange configurationRead statusRead mem

Introductory Course: Building an Embedded System with a Microcontroller Microcontroller concepts Software design basics ARM Cortex-M0 architecture and interrupt system C as implemented in assembly language Peripherals and interfacing Advanced Course: Embedded System Design, Analysis and Optimization C