The Definitive Guide to the ARM Cortex-M0 Joseph Yiu AMSTERDAM(cid:129)BOSTON(cid:129)HEIDELBERG(cid:129)LONDON(cid:129)NEWYORK(cid:129)OXFORD PARIS(cid:129)SANDIEGO(cid:129)SANFRANCISCO(cid:129)SINGAPORE(cid:129)SYDNEY(cid:129)TOKYO NewnesisanimprintofElsevier Newnesisan imprint ofElsevier TheBoulevard, LangfordLane,Kidlington, Oxford, OX51GB, UK 30 Corporate Drive,Suite 400, Burlington, MA 01803,USA Firstpublished 2011 Copyright (cid:1) 2011Man Cheung JosephYiu.Published by ElsevierInc. All rights reserved. Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicor mechanical, includingphotocopying,recording, oranyinformationstorage and retrieval system, withoutpermission inwriting from the publisher. Details on how toseek permission, further informationaboutthePublisher’spermissionspoliciesandourarrangementwithorganizationssuchas the Copyright ClearanceCenterand the Copyright Licensing Agency, can befound at ourwebsite: www.elsevier.com/permissions Thisbook andthe individual contributionscontained init are protected under copyright by the Publisher (other than asmay be noted herein). Notices Knowledge and best practice inthisfieldare constantlychanging. As new research and experience broadenourunderstanding,changesinresearchmethods,professionalpractices,ormedicaltreatment may become necessary. Practitioners and researchers must always rely on their own experienceand knowledge inevaluating and usinganyinformation, methods, compounds,or experimentsdescribed herein. Inusing such informationormethodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,including parties for whom they have aprofessional responsibility. Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assume anyliability for anyinjury and/ordamage to persons orproperty asa matter ofproductsliability, negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideas contained inthe materialherein. British Library Cataloguingin Publication Data A catalogue record for this book isavailable from the British Library Libraryof CongressControlNumber: 2010940590 ISBN: 978-0-12-385477-3 ForinformationonallNewnespublications visitourwebsiteatwww.elsevierdirect.com Printed and bound inthe United States 11 12 13 14 109 8 7 65 4 3 21 Foreword Itisanexcitingtimetobeamicrocontrolleruser.AgrowingrangeofARMCortex-Mdevices are available from many vendors, spanning a broad range of applications. Users who are familiar with 8-bit and 16-bit microcontrollers and are moving to ARM Cortex-Mebased devices are surprised at just how easy they are to use and, with the introduction of ARM Cortex-M0 devices, how low-cost and efficient 32-bit microcontrollers have become. So I was delighted that Joseph Yiu chose to write a guide for the users of these ARM Cortex-M0 devices. As a technical authority on the ARM Cortex-M family and a formative 8-bit user, Joseph is uniquely placed to guide users new to ARM Cortex microcontrollers on their first transition steps, and to impart detailed knowledge about the Cortex-M0 to the advanced user. Dr Dominic Pajak ARM Cortex-M0 Product Manager xiii Preface IstartedlearningaboutmicrocontrollerswhenIwasstudyingatuniversity.Atthattime,some ofthesingleboardcomputersIwasusinghadan8-bitmicrocontroller,andmyprogramswere storedinexternalEraseableProgrammableReadOnlyMemory(EPROM)chips.TheEPROM chips were in relatively large dual in line (DIP) packages and could be erased by shining ultravioletlightthroughtheglasswindow.Sincethen,microcontrollertechnologyhaschanged a lot: external EPROMs have been replaced by on-chip flash memories, DIP packages have been replaced by surface mountpackages, and mostmicrocontrollers havebecome in-system reprogrammable. More and more peripherals have been added to microcontrollers, and the complexity of the software has increased dramatically. Since 2004, the microcontroller market has made some dramatic changes. Previously, the microcontrollersonthemarketweremostly8-bitand16-bittypes,and32-bitmicrocontroller applicationswerelimitedtohigh-endproducts,mainlybecauseof thecost.Althoughmostof the 8-bit and 16-bit microcontrollers could be programmed in C, trying to squeeze all the required functionalities into a small microcontroller was becoming more and more difficult. You might spend one day writing a program in C, and then find that you needed to spend anothertwodaysrewritingpartoftheprograminassemblybecausetheprocessingspeedofthe microcontroller was too slow for all the required processing tasks. Even if you are developing simple applications and do not require high processing power in the microcontrollers, occasionally you might need to switch to a different microcontroller architecture because of project requirements, and this can take a tremendous effort. Not only will you need to spend the money to buy new tools, but it can take weeks to learn to use the tools and months to become familiar with a new architecture. In October 2004, the price of an ARM7 microcontroller dropped to below 3 US dollars. This wasverygoodnewsformanydeveloperswhoneededtodevelopcomplexembeddedsoftware. Since then, with the availability of the Cortex-M3, the price of ARM microcontrollers has dropped much further and you can get an ARM microcontroller for less than 1 US dollar. As a result, the use of ARM microcontrollers is gaining acceptance. In addition to providing excellentperformance,themodernARMmicrocontrollersrequireverylittlepower.Theuseof ARM microcontrollers is no longer limited to high-end products. xv xvi Preface Like many good ideas, the concept for the Cortex-M0 started life as a conversation between engineers in a bar. A small and growing number of ARM partners were looking for a 32-bit processor that was small, really small. The concept quickly became a full-blown engineering project (codenamed “Swift”). In 2009, the Cortex-M0 design was completed, and it quickly became one of the most successful ARM processor products. Throughtheexamplesinthisbook,youwillfindthattheCortex-M0microcontrollersareeasy touse.Insomeaspects,theyareeveneasiertousethansome8-bitmicrocontrollersbecauseof the simplicityof thelinear memory architecture,an uncomplicatedand yetflexible exception model, comprehensive debug features, and the software infrastructures provided by ARM, microcontroller vendors, and software solution providers. Because the Cortex-M processors are extremely C friendly, there is no need to optimize the applicationswithassembly.ThereisnoneedtolearnlotsofspecialCdirectivesjusttogetthe interrupt handlers working. For some embedded developers, the switch to ARM micro- controllers also means it is much easier to switch between different microcontroller products without the need to buy new tools and learn a new architecture. On the Internet you can find that many people are already using Cortex-M0 microcontrollers on a number of interesting projects. AfterworkingonanumberofARMprocessorprojects,Igainedalotofexperienceintheuse oftheCortex-Mprocessors(andpossiblysomegrayhairsaswell).Withencouragementfrom some friends and help from lots of people, I decided to put those experiences into a book to share with numerous embedded developers who are interested in using the ARM Cortex-M processors.Ilearnedalotwhilewritingmyfirstbook,whichisabouttheCortex-M3processor. Manythankstothosepeoplewhogavemeusefulfeedbackwhenthefirstbookwaspublished, bothinsideandoutsideARM.Iknowitwasn’tperfect,butatleastitisencouragingtofindthat manyreadersfoundmyCortex-M3bookuseful.Ihopethisbook,TheDefinitiveGuidetothe ARM Cortex-M0, will be even better. This book targets a wide range of audiences: from students, hobbyists, and electronic enthu- siasts, to professional embedded software developers, researchers, and even semiconductor productdesigners.Asaresult,itcoversawiderangeofinformation,includingmanyadvanced technical details that most embedded developers might never need. At the same time, it contains many examples, making it easy for novice embedded software developers to use. I hope that you find this book helpful and that you enjoy using the Cortex-M0 in your next embedded project. Acknowledgments A number of people have assisted me in researching for and writing this book. Firstofall,abigthankyoutomycolleaguesinARMfortheirhelpinreviewingandsuggesting improvements, especiallyEdmundPlayer,NickSampays,and DominicPajak, and alsoDrew Barbier, Colin Jones, Simon Craske, Jon Marsh, and Robert Boys. Iwouldalsoliketothankanumberofexternalreviewerswhoseinputintermsoffeedbackhas enabledmetohoneandimprovethequalityofthebook’stechnicalinformation.TheyareJoe Yu and Kenneth Dwyer from NXP, John Davies from Glasgow University, and Jeffrey S. MuellerfromTriadSemiconductor.Inadditiontothosewhoreviewedtheprepublicationbook, I would also thank the following who assisted me while I was writing it by answering my technical inquiries and by providing product information. They are Kenneth Dwyer, David Donley, and Amit Bhojraj from NXP; Drew Barbier from ARM; Milorad Cvjetkovic from Keil;JeffreyS.Mueller,WilliamFarlow,andJimKemerlingfromTriadSemiconductor;Jamie BrettlefromNationalInstruments;DerekMorrisfromCodeRedTechnologies;BrianBarrera fromCodeSourcery;andthesalesteamsfromRowleyAssociates,SteinertTechnologies,IAR Systems, and TASKING. I would also thank the staff from Elsevier for their professional work in getting this book published. And finally, a big thank you to all my friends within and outside of my work environment whose unstinting encouragement enthused and enabled me (though the odd cup of coffee helped too) to start and then complete the book. xvii Conventions Various typographical conventions have been used in this book, as follows: (cid:129) Normal assembly program codes: MOV R0; R1; Move data from Register R1 to Register R0 (cid:129) Assemblycodeingeneralizedsyntax;itemsinside“<>”mustbereplacedbyrealregister names: MRS <reg>; <special reg>; (cid:129) C program codes: for ði ¼ 0;i < 3;iþþÞ f func1ðÞ; g (cid:129) Pseudo code: if ða > bÞ f. (cid:129) Values: 1. 4’hC, 0x123 are both hexadecimal values. 2. #3 indicates item number 3 (e.g., IRQ #3 means IRQ number 3). 3. #immed_12 refers to 12-bit immediate data. 4. Registerbitsaretypicallyusedtoillustrateapartofavaluebasedonbitposition.For example, bit[15:12] means bit number 15 down to 12. (cid:129) Register access types: 1. R is Read only. 2. Wis Write only. 3. R/Wis Read or Write accessible. 4. R/Wc is Readable and cleared by a Write access. xix Terms and Abbreviations Abbreviations Meaning AAPCS ARM Architecture Procedure Call Standard AHB Advanced High-Performance Bus ALU Arithmetic Logic Unit AMBA Advanced Microcontroller Bus Architecture APB Advanced Peripheral Bus ARM ARM ARM Architecture Reference Manual BE8 Byte Invariant Big Endian mode BPU Break Point Unit CMOS Complementary Metal Oxide Semiconductor CMSIS Cortex Microcontroller Software Interface Standard DWT Data Watchpoint and Trace Unit (unit) EXC_RETURN Exception Return FPGA Field Programmable Gate Array gcc GNU C Compiler ICE In-Circuit Emulator IDE Integrated Development Environment ISA Instruction Set Architecture ISR Interrupt Service Routine JTAG JointTestActionGroup(astandardtestanddebuginterface) LR Link Register LSB Least Significant Bit MCU Microcontroller Unit MDK/MDK-ARM ARM Keil Microcontroller Development Kit xxi xxii Terms and Abbreviations Abbreviations Meaning MSB Most Significant Bit MSP Main Stack Pointer NMI Non-Maskable Interrupt NVIC Nested Vectored Interrupt Controller OS Operating System PC Program Counter PSP Process Stack Pointer PSR/xPSR Program Status Register RVDS ARM RealView Development Suite RTOS Real Time Operating System RTX Keil Real-Time eXecutive kernel SCB System Control Block SCS System Control Space TAP Test Access Port TRM Technical Reference Manual WIC Wakeup Interrupt Controller Reference The following documents are referenced in this book: Document Tile ARM Document number 1 Cortex-M0 Devices Generic User Guide ARM DUI 0497A 2 Cortex-M0 r0p0 Technical Reference Manual ARM DDI 0432C 3 ARMv6-M Architecture Reference Manual ARM DDI 0419B 4 Procedure Call Standard for ARM Architecture ARM IHI 0042D 5 ARM Workbench IDE User Guide ARM DUI 0330E 6 CoreSight Technology System Design Guide ARM DGI 0012B 7 ARM Debug Interface v5 ARM IHI 0031A 8 Keil MDK-ARM Compiler Optimization: Getting Keil Application Note 202 the Best Optimized Code for Your Embedded Application 9 RealView Compilation Tools Developer Guide ARM DUI 0203I CHAPTER 1 Introduction Why Cortex-M0? TheARMCortex-M0processorisdesignedtomeettheneedsofmodernultra-low-power microcontrollerunits(MCUs)andmixed-signaldevices.Itisintendedtosatisfythedemandfor ever-lower-costapplicationswithincreasingconnectivity(e.g.,Ethernet,USB,low-power wireless)andusesofanalogsensors(e.g.,touchsensorsandaccelerometers).Theseapplications requiretightintegrationofanaloganddigitalfunctionalitytopreprocessandcommunicatedata. Existing8-bitand16-bitdevicesoftencan’tsupporttheseapplicationswithoutsignificant increasesincodesizeandclockfrequency,thereforeincreasingpower.TheCortex-M0addresses theneedforincreasedperformanceefficiencywhileremaininglowcostandextendingbatterylife. Itisunsurprising,therefore,thattheCortex-M0processorisnowavailableinarapidlygrowing rangeofsiliconproducts,withtheprocessorbeingthefastestlicensingARMdesigntodate. TheideabehindARMCortex-M0wastocreatethesmallest,lowestpowerprocessorpossible, while remaining upward compatible with the higher-performance ARM Cortex-M3. ARM announcedtheCortex-M0processorinFebruary2009,anditachieveditsgoals.Theresulting design is just 12,000 logic gates in minimum configuration, as small as an 8-bit or 16-bit processor, but it is a full 32-bit processor that incorporates advanced technologies with many compelling benefits over 8-bit or 16-bit devices. Energy Efficiency TheperformanceefficiencyoftheCortex-M0(0.9DMIPS/MHz)meansitcangetataskdonein fewercycles(evena32-bitmultiplycanbecompletedinonecycle).ThismeansCortex-M0 devicescanspendmoretimeinalow-powersleepstate,offeringbetterenergyefficiency. Alternately,theycangetthesamejobdoneinfewerMHz,meaningloweractivepowerand electromagneticinterference(EMI).ThelowgatecountoftheCortex-M0meansthatthe leakage,andsleepcurrent,isminimized.Thehighlyefficientinterruptcontroller(NVIC)means thatinterruptoverheadislow,evenwhenhandlingnestedinterruptsofdifferentpriorities. Code Density The code size offered by the Thumb-2-based instruction set is smaller than 8-bit or 16-bit architectures for many applications. This means users can choose devices with smaller flash TheDefinitiveGuidetotheARMCortex-M0.DOI:10.1016/B978-0-12-385477-3.10001-1 Copyright(cid:1)2011ManCheungJosephYiu.PublishedbyElsevierInc.Allrightsreserved. 1
Description: