ebook img

Fast and Effective Embedded Systems Design. Applying the ARM mbed PDF

366 Pages·2012·10.61 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Fast and Effective Embedded Systems Design. Applying the ARM mbed

CHAPTER 1 Embedded Systems, Microcontrollers and ARM Chapter Outline 1.1 Introducing Embedded Systems 3 1.1.1 What isan EmbeddedSystem? 3 1.1.2 AnExample Embedded System 5 1.2 Microprocessors and Microcontrollers 6 1.2.1 SomeComputer Essentials 7 1.2.2 TheMicrocontroller 8 1.3 Development Processes in Embedded Systems 9 1.3.1 Programming Languages: Whatis soSpecial aboutC/Cþþ? 9 1.3.2 TheDevelopment Cycle 10 1.4 The World of ARM 11 1.4.1 ALittleHistory 12 1.4.2 SomeTechnical Detail: What doesthis RISCWord Mean? 13 1.4.3 TheCortex Core 14 Chapter Review 15 Quiz 15 References 16 1.1 Introducing Embedded Systems 1.1.1 What is an Embedded System? Weareallfamiliarwiththeideaofadesktoporlaptopcomputer,andtheamazingprocessing thattheycando.Thesecomputersaregeneralpurpose;wecangetthemtododifferentthings atdifferenttimes,dependingontheapplicationorprogramwerunonthem.Attheveryheart ofsuchcomputersisamicroprocessor,atinyandfantasticallycomplicatedelectroniccircuit which contains the core features of a computer. All of this is fabricated on a single slice of silicon, called an integrated circuit (IC). Some people, particularly those who are not engineers themselves, call these circuits microchips, or just chips. FastandEffectiveEmbeddedSystemsDesign.DOI:10.1016/B978-0-08-097768-3.00001-5 Copyright(cid:1)2012ElsevierLtd.Allrightsreserved. 3 4 Chapter 1 What is less familiar to many people is the idea that instead of putting a microprocessor in a general-purpose computer, it can also be placed inside a product which has nothing to do with computing, like a washing machine, toaster or camera. The microprocessor is then customizedtocontrolthatproduct.Thecomputeristhere,insidetheproduct;butitcannotbe seen,and theuserprobablydoesnoteven know itis there.Moreover,thoseadd-onsthatare normallyassociatedwithacomputer,likekeyboard,screenormouse,arenowheretobeseen. Such products are called embedded systems, because the computer that controls them is embedded right inside. Because they tend to focus on control, in many cases the microprocessors used in embedded systems develop different characteristics from the ones used in more general-purpose machines. They are called microcontrollers. Although much lessvisiblethantheirmicroprocessorcousins,microcontrollerssellinfargreatervolumeand their impact has been enormous. To the electronic and system designer they offer huge opportunities. Embedded systems come in many forms and guises. They are extremely common in the home,themotorvehicleandtheworkplace.Mostmoderndomesticappliances,likewashing machines, dishwashers, ovens, central heating and burglar alarms, are embedded systems. Themotorcarisfullofthem,inenginemanagement,security(forexample,lockingandanti- theftdevices),air-conditioning,brakes,radio,andsoon.Theyarefoundacrossindustryand commerce,inmachinecontrol,factoryautomation,robotics,electroniccommerceandoffice equipment. The list has almost no end, and it continues to grow. Figure1.1expressestheembeddedsystemasasimpleblockdiagram.Thereisasetofinputs from the controlled system. The embedded computer, usually a microcontroller, runs (User Interface) TIME Embedded Computer Input Software Output Variables Variables HHaarrddwwaarree (Link to other Systems) Figure 1.1: The embedded system Embedded Systems, Microcontrollers and ARM 5 a program dedicated to this application, permanently stored in its memory. Unlike the general-purpose desktop computer, which runs many programs, this is the only program it ever runs. Based on information supplied from the inputs, the microcontroller computes certain outputs, which are connected to things like actuators within the system. The actual electronic circuit, along with any electromechanical components, is often called the hardware;theprogramrunningonitisoftencalledthesoftware.Asidefromallofthis,there may also be interaction with a user, for example via keypad and display, and there may be interaction with other subsystems elsewhere, although neither of these is essential to the generalconcept.Oneothervariablewillaffectallthatwedoinembeddedsystems,andthisis time,representedasadominatingarrowwhichcutsacrossthefigure.Wewillneedtobeable tomeasuretime,makethingshappenatpreciselypredeterminedtimes,generatedatastreams orothersignalswithastrongtimedependence,andrespondtounexpectedthingsinatimely fashion. This chapter introduces or reviews many concepts relating to computers, microprocessors, microcontrollersandembeddedsystems.Itdoesthisinoverviewform,togiveaplatformfor further learning. We return to most concepts in later chapters, building on them and adding detail. More details can also be found in Reference 1.1. 1.1.2 An Example Embedded System A snack vending machine is a good example of an embedded system. One is represented in Figure 1.2, in block diagram form. At its heart is a single microcontroller. As the diagram shows, this accepts a number of input signals, from the user keypad, the coin-counting module and the dispensingmechanism itself. It generates output signals dependent on those inputs. A hungrycustomermay approachthe machine and start jabbingat thebuttons or feedingin coins. In the first case, the keypad sends signals back to the microcontroller, so that it can recognizeindividualkeyspressedandthenhookthesekeyvaluestogethertodecipheramore complex message. The coin-counting module will also send information on the amount of money paid. The microcontroller will attempt to make deductions from the information it receives and will outputstatus informationon the liquid crystal display. Has avalid product been selected? Has enough money been paid? If yes, then it will energize an actuator to dispensetheproduct.Ifno,itwilldisplayamessageaskingformoremoneyorare-entryof theproductcode.Agoodmachinewillbereadytogivechange.Ifitdoesdispense,therewill besensorsonthemechanismtoensurethattheproductisavailable,andfinallythattheaction is complete. These are shown in the diagram as gate position sensors. A bad machine (and haven’t we all met these?) will give annoying or useless messages on its display, demand moremoneywhenyouknowyou’vegiven therightamount,or leave thatchocolatebar you desperately want teetering on a knife-edge, not dropping down into the dispensing tray. 6 Chapter 1 Figure 1.2: Vending machine embedded system What has been described so far is a fairly conventional machine. We can, however, take it further. In modernvending systems there might be a mobile communications feature which allowsthevendingmachinetoreportdirectlytothemaintenanceteamifafaultisdiagnosed; theywillthencomeandfixthefault.Similarly,themachinemightreportstocklevelsthrough mobileorInternetcommunicationstoallowtheserviceteamtovisitandreplenishwhenever supplies run low. This simpleexamplereflectsexactly thediagramofFigure1.1.Themicrocontrolleraccepts inputvariables,makescalculationsanddecisionswiththis,andgeneratesoutputsinresponse. Itdoesthisinatimelymanner,andcorrectuseoftimeisimplicitintheseactions.Thereisin this case a user interface, and in a modern machine there is a network interface. While the above paragraphs seem to be describing the physical hardware of the system, in fact it is all controlledbythesoftwarethatthedesignerhaswritten.Thisrunsinthemicrocontrollerand determines what the system actually does. 1.2 Microprocessors and Microcontrollers Letusgobacktothemicrocontroller,whichsitsattheheartofanyembeddedsystem.Asthe microcontrollerisinessenceatypeofcomputer,itwillbeusefulforustogetagrasponbasic computerdetails.Wedothisincompleteoverviewhere,butreturntosomeofthesefeatures in later chapters. Embedded Systems, Microcontrollers and ARM 7 1.2.1 Some Computer Essentials Figure 1.3 shows the essential elements of any computer system. As its very purpose for existence, a computer can perform arithmetic or logical calculations. It does this in a digital electronic circuit called the arithmetic logic unit (ALU). The ALU is placed within a larger circuit, called the central processing unit (CPU), which provides some of the supporting features that it needs. The ALU can undertake a number of simple arithmetic and logic calculations. Which one it does depends on a code which is fed to it, called an instruction. Nowwearegettingclosertowhatacomputerisallabout.IfwecankeeptheALUbusy,by feeding it a sensible sequence of instructions, and also pass it the data it needs to work on, then we have the makings of a very useful machine indeed. The ability to keep feeding the ALU with instructions and data is provided by the control circuit which sits around it. It is worth noting that any one of these instructions performs a very simple function. However, because the typical computer runs so incredibly fast, the overall effect is one of very great computational power. The series of instructions is called aprogram,normallyheldinanareaofmemorycalledprogrammemory.Thismemoryneeds tobepermanent.Ifitis,thentheprogramisretainedindefinitely,whetherpowerisappliedor not, and it is ready to run as soon as power is applied. Memory like this, which keeps its contentswhenpowerisremoved,iscallednon-volatilememory.Theold-fashionednamefor thisisreadonlymemory(ROM).Thislatterterminologyisstillsometimesused,eventhough it is no longer accurate for new memory technology. The control circuit needs to keep accessingtheprogrammemory,tofindoutwhatthenextinstructionis.ThedatathattheALU works on may be drawn from the data memory, with the result placed there after the calculationiscomplete.Usuallythisistemporarydata.Thismemorytypethereforeneednot bepermanent,althoughthereisnoharmifitis.Memorythatlosesitscontentswhenpoweris removed is called volatile memory. The old-fashioned name for this type of memory is data and address Data Central Memory data and Processing The Input/ address Unit (CPU) Outside Output World data and address Program ALU Memory Control Figure 1.3: Essentials of a computer 8 Chapter 1 random access memory (RAM). This terminology is still used, although it conveys little useful information. To be of any use, the computer must be able to communicatewith the outside world, and it does this through its input/output (I/O). On a personal computer this implies human interaction, through things like the keyboard, visual display unit (VDU) and printer. In an embeddedsystem,atleastasimpleone,thecommunicationislikelytobeprimarilywiththe physical world around it, through sensors and actuators. Data coming in from the outside world might be quickly transferred to the ALU for processing, or it might be stored in data memory. Data being sent out to the outside world is likely to be the result of a recent calculation in the ALU. Finally, there must be data paths between each of these main blocks, as shown by the block arrows in the diagram. These are collections of wires, which carry digital information in eitherdirection.Onesetofwirescarriesthedataitself,forexamplefromprogrammemoryto theCPU;thisiscalledthedatabus.Theothersetofwirescarriesaddressinformationandis calledtheaddressbus.Theaddressisadigitalnumberthatindicateswhichplaceinmemory thedatashouldbestoredin,orretrievedfrom.Thewiresineachofthedataandaddressbuses could be tracks on a printed circuit board or interconnections within an IC. One of the defining features of any computer is the size of its ALU. Simple, old processors were 8bit, and some of that size still have useful roles to play. This means that, with their 8bits, they can represent a number between 0 and 255. (Check Appendix A if you are unfamiliarwithbinarynumbers.)Morerecentmachinesare32or64bit.Thisgivesthemfar greater processing power, but adds to their complexity. Given an ALU size, it generally followsthatmanyotherfeaturestakethesamesize,forexamplememorylocations,databus, and so on. Asalreadysuggested,theCPUhasaninstructionset,whichisasetofbinarycodesthatitcan recognize and respond to. For example, certain instructions will require it to add or subtract twonumbers,orstoreanumberinmemory.Manyinstructionsmustalsobeaccompaniedby data,oraddressestodata,onwhichtheinstructioncanoperate.Fundamentally,theprogram that the computer holds in its program memory and to which it responds is a list of instructionstakenfromtheinstructionset,withanyaccompanyingdataoraddressesthatare needed.Suchcodeissometimescalledmachinecode,todistinguishitfromotherversionsof the program that we may also develop. 1.2.2 The Microcontroller A microcontroller takes the essential features of a computer as just described, and adds to thesethefeaturesthatareneededforittoperformitscontrolfunctions.Itisusefultothinkof it as being made up of three parts e core, memory and peripherals e as shown in the block Embedded Systems, Microcontrollers and ARM 9 Program Further Memory Peripheral Power Data Further Memory Peripheral Digital I/0 Microprocessor Core Reset Analog Interrupt(s) I/0 Internal Data & Address Buses Counters Clock & Timers Figure 1.4: Features of an example microcontroller: core þ memory þ peripherals diagram of Figure 1.4. The core is the CPU and its control circuitry. Alongside this go the program and data memory. Finally, there are the peripherals. These are the elements that distinguishamicrocontrollerfromamicroprocessor,fortheyaretheelementsthatallowthe wide-ranging interaction with the outside world that the microcontroller needs. Peripherals canincludedigitaloranaloginput/output,serialports,timers,countersandmanyotheruseful subsystems. It almost goes without saying, but must not be forgotten, that the microcontroller needs power,intheformofastabledirectcurrent(DC)supply.Afurtherrequirement,aswithany personal computer (PC), is to have a clock signal. This is the signal that endlessly steps the microcontrollercircuitthroughthesequenceofactionsthatitsprogramdictates.Theclockis often derived from a quartz oscillator, such as you may have in your wristwatch. This gives a stable and reliable clock frequency. The clock often has a very important secondary function, of providing essential timing information for the activities of the microcontroller, for example in timing the events it initiates, or in controlling the timing of serial data. 1.3 Development Processes in Embedded Systems þþ 1.3.1 Programming Languages: What is so Special about C/C ? The CPUinstructionsetwas mentionedin Section1.2.1.Asprogrammers,it isour ultimate goal to produce a program that makes the microcontroller do what we want it to do; that program must be a listing of instructions, in binary, drawn from the instruction set. The 10 Chapter 1 programinthisrawbinaryformiswhatwehavealreadycalledmachinecode.Itisextremely tedious, to the point of being near impossible, for us as humans to work with the binary numbers that form the instruction set. AfirststeptowardssanityinprogrammingiscalledAssembler.InAssemblereachinstruction gets its own mnemonic, a little word which a human can remember and work with. The instruction set is represented by a set of mnemonics. The program is then written in these mnemonics,andacomputerprogramcalledacross-assemblerconvertsallthosemnemonics into the actual binary code that is loaded into program memory. Assembler has its uses, for one it allows us to work very closely with the CPU capabilities; Assembler programs can thereforebeveryfastandefficient.YetitiseasytomakemistakesinAssemblerandhardto find them, and the programming process is time consuming. A further step to programming sanity is to use a high-level language (HLL). In this casewe use a language like C, Java or Fortran to write the program, following the rules of that language.Thenacomputerprogramcalledacompilerreadstheprogramwehavewritten,and converts(compiles)thatintoalistingofinstructionsfromtheinstructionset.Thisassumeswe have made no mistakes in writing the program! This list of instructions becomes the binary code that we can download to the program memory. Our needs in the embedded world, however,arenotlikethoseofotherprogrammers.Wewanttobeabletocontrolthehardware we are working with, and write programs that execute quickly, in predictable times. Not all HLLs are equally good at meeting these requirements. People get very excited, and debate endlessly, about what is the best language in the embedded environment. However, most agreethat,formanyapplications,Chasclearadvantages.Thisisbecauseitissimpleandhas featuresthatallowustogetatthehardwarewhenrequired.AstepupfromCisCþþ,which is also widely used for more advanced embedded applications. 1.3.2 The Development Cycle Thisbookisaboutdevelopingembeddedsystems,anddevelopingthemquicklyandreliably, so it is worth getting an early picture of what that development process is all about. In the early days of embedded systems, the microcontrollers were very simple, without on-chip memory and with few peripherals. It took a lot of effort just to design and build the hardware. Moreover, memory was very limited, so programs had to be short. The main development effort was spent on hardware design, and programming consisted of writing rathersimpleprogramsinAssembler.Overtheyears,themicrocontrollersbecamemoreand more sophisticated, and memory much more plentiful. By now, many suppliers were selling predesignedcircuitboardscontainingthemicrocontrollerandallassociatedcircuitry.Where these were used there was very little development effort needed for the hardware. Now attention could be turned to writing complex and sophisticated programs, using all the Embedded Systems, Microcontrollers and ARM 11 Write/Revise Source Code Assemble/Compile (Simulate) Download Test in Hardware Figure 1.5: The embedded program development cycle memory that had become available. This tends to be the situation we find ourselves in nowadays. Despitethesechanges,theprogramdevelopmentcycleisstillbasedaroundthesimpleloop showninFigure1.5.Inthisbook,wewillmainlywritesourcecodeusingC.Thediagramof Figure1.5impliessomeoftheequipmentwearelikelytoneed.Thesourcecodewillneedtobe writtenonacomputerelet’scallitthehostcomputereforexampleaPC,usingsomesortof texteditor.Thesourcecodewillneedtobeconvertedintothebinarymachinecodewhichis downloadedtothemicrocontroller,placedwithinthecircuitorsystemthatitwillcontrol(let’s callthisthetargetsystem).Thatconversionisdonebythecompiler,runningonthehost computer.Programdownloadtothetargetsystemrequirestemporaryconnectiontothehost computer.Thereisconsiderableclevernessinhowtheprogramdataisactuallywrittenintothe programmemory,butthatneednotconcernushere.Beforetheprogramisdownloaded,itis oftenpossibletosimulateitonthehostcomputer;thisallowsaprogramtobedevelopedto agoodlevelbeforegoingtothetroubleofdownloading.However,thetruetestoftheprogram istoseeitrunningcorrectlyinthetargetsystem.Whenprogramerrorsarefoundatthisstage, astheyinevitablyare,theprogramcanberewritten,andcompiledanddownloadedoncemore. 1.4 The World of ARM The development of computers and microprocessors has at different times been driven forward by giant corporations or by tiny start-ups; but always it has been driven forward by 12 Chapter 1 verytalentedindividualsorteams.ThedevelopmentofARMhasseenacombinationofallof these. The full history of the development of ARM is an absolutely fascinating one, like so manyotherhi-techstart-upsinthepast30orsoyears.Atinysummaryisgivenbelow;doread it in a fuller version in one of the several websites devoted to this topic. Then watch that history continue to unfold in the years to come! 1.4.1 A Little History In 1981 the British Broadcasting Corporation launched a computer education project and askedforcompaniestobidtosupplyacomputerthatcouldbeusedforthis.Thewinnerwas the Acorncomputer.This becameanextremely popularmachine,and wasvery widelyused in schools and universities in the UK. The Acorn used a 6502 microprocessor, made by a company called MOS Technology. This was a little 8-bit processor, which would not be takenvery seriously these days, but was respected in its time. Responding to the growing interestinpersonalordesk-topcomputers,IBMin1981produceditsveryfirstPC,basedon a more powerful Intel 16-bit microprocessor, the 8088. There were many companies producing similar computers at the time, including of course Apple. These early machines were prettymuchincompatiblewitheach other,anditwasquiteunclearwhetheronewould finallydominate.Throughoutthe1980s,however,theinfluenceoftheIBMPCgrew,andits smallercompetitorsbegantofade.DespiteAcorn’sUKsuccessitdidnotexportwell,andits future no longer looked bright. It was around this time that those clever designers at Acorn made three intellectual leaps. They wanted to launch a new computer. This would inevitably mean moving on from the 6502, but they just could not find a suitable processor for the sort of upgrade they needed. Their first leap was the realization that they had the capability to design the microprocessor itself and did not need to buy it in from elsewhere. Being a small team and experiencing intense commercial pressure, they designed a small processor, but one with real sophistication. The computer they built with this, the Archimedes, was a very advanced machine, but struggled against the commercial might of IBM. The company found themselveslookingatcomputersaleswhichjustwerenotsufficient,butholdingthedesignof anextremelyclevermicroprocessor.Theyrealizedetheirsecondleapethattheirfuturemay not lie in selling the completed computer itself. Therefore, in 1990, Acorn computers cofounded another Cambridge company, called Advanced RISC Machines Ltd, ARM for short. They also began to realize e their third leap e that you do not need to manufacture silicontobeasuccessfuldesigner,whatmatteredwastheideasinsidethedesign.Thesecan be sold as intellectual property (IP). The ARM concept continued to prosper, with a sequence of smart microprocessor designs being sold as IP to an increasing number of major manufacturers around the world. The company has enjoyed huge success, and is currently called ARM Holdings. Thosewho buy

Description:
This book is an introduction to embedded systems design, using the ARM mbed and C programming language as development tools.The mbed provides a compact, self-contained and low-cost hardware core, and the on-line compiler requires no download or installation, being accessible wherever an internet lin
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.