P le a s e v is it t h e C o m p a n io n W e b s it e t o F a s t a n d E ffe c t iv e E m b e d d e d S y s t e m s D e s ig n w w w .e m b e d d e d a c a d e m ic .c o m T h e c o m p a n io n w e b s it e c o n t a in s in s t r u c t o r s u p p o r t , p r o g r a m e x a m p le s , e r r a t a , u p d a t e s o n p a r t s a n d a n s w e r s t o fr e q u e n t ly a s k e d q u e s t io n s . F a s t a n d E ffe c t iv e E m b e d d e d S y s t e m s D e s ig n A p p ly in g t h e A R M m b e d R o b T o u ls o n T im W ilm s h u r s t AMSTERDAM • BOSTON • HEIDELBERG • LONDON • NEW YORK • OXFORD PA R IS • S A N D IE G O • S A N F R A N C IS C O • S IN G A P O R E • S Y D N EY • T O KYO Newn es is an imp rin t o f Elsev ier Newn es is an imp rin t o f Elsev ier Th e Bo u lev ard , Lan g fo rd Lan e, Kid lin g to n , Ox fo rd , OX5 1 GB 2 2 5 Wy man Street, Walth am, MA 0 2 4 5 1 , USA First p u b lish ed 2 0 1 2 Co p y rig h t Ó2 0 1 2 Ro b To u lso n an d Tim Wilmsh u rst. Pu b lish ed b y Elsev ier Ltd . All rig h ts reserv ed Th e rig h ts o f Ro b To u lso n an d Tim Wilmsh u rst to b e id en tified as th e au th o rs o f th is wo rk h as b een asserted in acco rd an ce with th e Co p y rig h t, Desig n s an d Paten ts Act 1 9 8 8 . No p art o f mech an ica p ermissio n th e Pu b lish Cen ter an d th is p u b licatio n may b e rep ro d u ced o r tran smitted in an y fo rm o r b y an y mean s, electro n ic o r l, in clu d in g p h o to co p y in g , reco rd in g , o r an y in fo rmatio n sto rag e an d retriev al sy stem, with o u t in writin g fro m th e p u b lish er. Details o n h o w to seek p ermissio n , fu rth er in fo rmatio n ab o u t er’s p ermissio n s p o licies an d o u r arran g emen t with o rg an izatio n s su ch as th e Co p y rig h t Clearan ce th e C o p y r ig h t L ic e n s in g A g e n c y , c a n b e f o u n d a t o u r w e b s ite : w w w.e ls e v ie r.c o m /p e r m is s io n s . T h is b o o k a n d th e in d iv id u a l c o n trib u tio n s c o n ta in e d in it a re p ro te c te d u n d e r c o p y rig h t b y th e P u b lis h e r (o th er th an as may b e n o ted h erein ). N o tic e s Kn o wled g e an d b est p ractice in th is field are co n stan tly ch an g in g . As n ew research an d ex p erien ce b ro ad en o u r u n d erstan d in g , ch an g es in research meth o d s, p ro fessio n al p ractices, o r med ical treatmen t may b eco me n ecessary . Practitio an y in fo meth o d s h av e a p n ers an d rmatio n , th ey sh o ro fessio n research ers mu st alway s rely o n th eir o wn ex p erien ce an d k n o wled g e in ev alu atin g an d u sin g meth o d s, co mp o u n d s, o r ex p erimen ts d escrib ed h erein . In u sin g su ch in fo rmatio n o r u ld b e min d fu l o f th eir o wn safety an d th e safety o f o th ers, in clu d in g p arties fo r wh o m th ey al resp o n sib ility . To th e fu llest ex ten t o f th e law, n eith er th e Pu b lish er n o r th e au th o rs, co n trib u to rs, o r ed ito rs, assu me an y liab ility fo r an y in ju ry an d /o r d amag e to p erso n s o r p ro p erty as a matter o f p ro d u cts liab ility , n eg lig en ce o r o th erwise, o r fro m an y u se o r o p eratio n o f an y meth o d s, p ro d u cts, in stru ctio n s, o r id eas co n tain ed in th e material h erein . B r itis h L ib r a r y C a ta lo g in g -in -P u b lic a tio n D a ta A catalo g u e reco rd fo r th is b o o k is av ailab le fro m th e British Lib rary L ib r a r y o f C o n g r e s s C a ta lo g in g -in -P u b lic a tio n D a ta A catalo g reco rd fo r th is b o o k is av ailab le fro m th e Lib rary o f Co n g ress ISBN: 9 7 8 -0 -0 8 -0 9 7 7 6 8 -3 Fo r in fo rmatio n o n all Newn es p u b licatio n s v is it o u r w e b s ite a t s t o r e .e ls e v ie r .c o m Prin ted an d b o u n d in Italy 1 2 1 3 1 4 1 5 1 0 9 8 7 6 5 4 3 2 1 Introduction Microprocessors are everywhere, providing ‘intelligence’ in cars, mobile phones, household andofficeequipment, televisionsandentertainmentsystems, medical products, aircrafte the list seems endless. Those everyday products, where a microprocessor is hidden inside to add intelligence, are called embedded systems. Not so long ago, designers of embedded systems had to be electronics experts, software experts, or both. Now, with user-friendly and sophisticated building blocks available for our use, both the specialist and the beginner can quickly engage in successful embedded system design. One such building block is the mbed, recently launched by the renowned computer giant ARM. The mbed is the central theme of this book; through it all the main topics of embedded systemdesignare introduced. The aimof the book is to teach the key elements of embedded system design through the use of the mbed. This book falls into two parts. Chapters 1e10 provide a wide-ranging introduction to embedded systems, using the mbed and demonstrating how it can be applied to rapidly produce successful embedded designs. These chapters aimto give full support to the reader, movingyouthroughaseries of carefully constructedconcepts andexercises. They start from basic principles and simple projects, and move towards more advanced system design. Chapters 11e15 build on this foundation, but enter a number of more specialist fields. The pace here may be a little faster, and you may find that you need to contribute more background research. All this book asksof youat thevery beginningis abasic graspof electrical/electronic theory. Thebook adoptsa‘learningthroughdoing’ approach. To makebestuseof ityouwill needan mbed, an Internet-connected computer and the various additional electronic components identified through the book. You will not need every single one of these if you choose not to do a certain experiment or book section. You will also need a digital voltmeter and ideally access to an oscilloscope. Each chapter is based around a major topic in embedded systems. Each has some theoretical introduction, and may have more theory within the chapter. The chapter then proceeds as a series of practical experiments. Have your mbed ready to hook up the next circuit, and download and compile the next example program. Run the program, and aim to understand xv xvi Introduction whatisgoingon. Asyourmbedconfidencegrows, sowill yourcreativity andoriginality; start to turn your own ideas into working projects. You will find that this book rapidly helps you: to understand and apply the key aspects of embedded systems to understand and apply the key aspects of the ARM mbed to learn from scratch, or develop your skills in embedded C/C++programming to develop your understanding of electronic components and configurations to understand how the mbed can be applied in some of the most exciting and innovative intelligent products emerging today to produce designs and innovations you never thought you were capable of! If you get stuck, or have questions, support is available for all readers through the book website and the mbed website, or by email discussion with the authors. If youareauniversity orcollegeinstructor, thenthisbook offersa‘completesolution’ to your embedded systems course. Both authors are experienced university lecturers and had your studentsinmindwhenwritingthisbook. Thebookcontainsastructuredsequenceof practical and theoretical learning activity. Ideally, you should equip every student or student pair with an mbed, a prototyping breadboard and a component kit. These are highly portable, so development work is not confined to the collegeor university laboratory. Laterin thecourse, students will start networking their mbeds together. Complete Microsoft PowerPoint presentations for each chapter are available to instructors via the book website, as well as answers to Quiz questions, and example solution code for the exercises and mini-projects. Part 1(Chapters1e10) of this book canbeusedto provideacompleteintroductory coursein embedded system design, with practical examples using the mbed. Part 2 (Chapters 11e15) can be used to enhance the introductory course, as the basis of further reading or for a more advanced course. This book is appropriate for any course or module that wants to introduce the concepts of embeddedsystems, inahands-onandinterestingway. Becausetheneedforelectronic theory is limited, the book is accessible to those disciplines that would not normally aim to take embeddedsystems. Thebookismeantto beaccessibletoYear1undergraduates, althoughwe expect it will more often be used in the years that follow. Students are likely to be studying one of the branches of engineering, physics or computer science. The book will also be of interest to the practicing professional and the hobbyist. This book is written by Rob Toulson, Research Fellow at Anglia Ruskin University in Cambridge, and Tim Wilmshurst, Head of Electronics at the University of Derby. After completing his PhD, Rob spent a number of years in industry, where he worked on digital signal processing and control systems engineering projects, predominantly in audio and Introduction xvii automotive fields. He then moved to an academic career, where his main focus is now in developing collaborative research between the technical and creative industries. Tim led the Electronics Development GroupintheEngineeringDepartment of CambridgeUniversity for a number of years, before moving to Derby. His design career has spanned much of the history of microcontrollers and embedded systems. Aside from our shared interest in embedded systems, we share an interest in music, and music technology. The book brings together our wide range of experiences. Having planned the general layout of the book, and aftersomeinitial work, wedividedthechapters betweenus. Timtook responsibility formost of the early ones, and issues relating to electronic and computing hardware. Rob worked mainly onthelaterchapters, andthemoreadvancedmbedapplications. Thisdivisionof labor was mainly for convenience, and at publication we both take responsibility for all the chapters. Because Tim has written several books on embedded systems in the past, a few background sections and diagrams have been taken from these and adapted for inclusion in this book. There seemed no point in ‘reinventing thewheel’ where background explanations were needed. Acknowledgments Throughout the writing of this book we have been grateful for the support of the ARM staff who are creators of the mbed project, notably Simon Ford and Chris Styles. Supporting experimental workandproof-readinghavebeenconductedby PhillipRichardsonatARUand Bheki Nyathi at Derby, to whom we are most grateful. A number of smart and innovative people have contributed libraries of code to the mbed online cookbook; we have referred to someof theseinthebook. Sincerethanksto thosepeople. Wealso expressourthanksto those who contribute to the discussion strands on the mbed site. We hope this book responds to some of your comments and questions. Among thesewe thank Martin Smith for his account of prototyping an mbed-based project, mentioned in Chapter 15. xix CHAPTER 1 Embedded Systems, Microcontrollers and ARM Chapter Outline 1.1 Introducing Embedded Systems 3 1.1.1 What is an Embedded System? 3 1.1.2 An Example Embedded System 5 1.2 Microprocessors and Microcontrollers 6 1.2.1 Some Computer Essentials 7 1.2.2 The Microcontroller 8 1.3 Development Processes in Embedded Systems 9 1.3.1 Programming Languages: What is so Special about C/Cþ þ ? 9 1.3.2 The Development Cycle 10 1.4 The World of ARM 11 1.4.1 A Little History 12 1.4.2 Some Technical Detail: What does this RISC Word Mean? 13 1.4.3 The Cortex Core 14 Chapter Review 15 Quiz 15 References 16 1.1 Introducing Embedded Systems 1.1.1 What is an Embedded System? Weareall familiarwiththeideaof adesktoporlaptopcomputer, andtheamazingprocessing that they cando. Thesecomputersaregeneral purpose; wecangetthemto do different things at different times, dependingontheapplicationorprogramwerunonthem. At thevery heart of suchcomputers is amicroprocessor, atiny andfantastically complicated electronic circuit 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. Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00001-5 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 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 customizedto control thatproduct. Thecomputeristhere, insidetheproduct; but it cannotbe seen, and the user probably does not even know it is there. Moreover, those add-ons that are normally associatedwithacomputer, likekeyboard, screenormouse, arenowhereto beseen. 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 less visiblethantheirmicroprocessorcousins, microcontrollerssell infargreatervolumeand 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, the motorvehicle and theworkplace. Most moderndomestic appliances, likewashing machines, dishwashers, ovens, central heating and burglar alarms, are embedded systems. Themotorcarisfull of them, inenginemanagement, security (forexample, lockingandantitheft devices), air-conditioning, brakes, radio, and so on. They are found across industry and commerce, inmachinecontrol, factory automation, robotics, electronic commerceandoffice equipment. The list has almost no end, and it continues to grow. Figure1.1expresses theembeddedsystemas asimpleblock diagram. Thereis aset of inputs from the controlled system. The embedded computer, usually a microcontroller, runs (User Interface) TIME Embedded Computer Input Variables Software Hardware Hardware (Link to other Systems) Figure 1.1: The embedded system Output Variables 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; theprogramrunningonit is oftencalledthesoftware. Asidefromall of this, 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 general concept. Oneothervariablewill affectall thatwedo inembeddedsystems, andthisis time, representedas adominatingarrowwhichcuts across thefigure. Wewill needto beable to measuretime, makethingshappenat precisely predeterminedtimes, generatedatastreams orother signals withastrong timedependence, andrespond to unexpected things inatimely fashion. This chapter introduces or reviews many concepts relating to computers, microprocessors, microcontrollers andembeddedsystems. It does this inoverviewform, to giveaplatformfor 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 dispensing mechanism itself. It generates output signals dependent on those inputs. A hungry customer may approach the machine and start jabbing at the buttons or feeding in coins. In the first case, the keypad sends signals back to the microcontroller, so that it can recognizeindividual keyspressedandthenhook thesekey valuestogetherto decipheramore 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 output status information on the liquid crystal display. Has a valid product been selected? Has enough money been paid? If yes, then it will energize an actuator to dispense the product. If no, it will display a message asking for more money or a re-entry of theproduct code. A goodmachinewill beready to givechange. If it doesdispense, therewill besensorsonthemechanismto ensurethattheproductisavailable, andfinally thattheaction 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 more money when you know you’ve given the right amount, or leave that chocolate bar 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 modern vending systems there might be a mobile communications feature which allowsthevendingmachineto report directly to themaintenanceteamif afault is diagnosed; they will thencomeandfix thefault. Similarly, themachinemightreportstock levelsthrough mobile orInternet communications to allow theserviceteamto visit and replenishwhenever supplies run low. This simple example reflects exactly the diagramof Figure 1.1. The microcontroller accepts inputvariables, makescalculationsanddecisionswiththis, andgeneratesoutputsinresponse. It doesthis inatimely manner, andcorrect useof timeis implicit intheseactions. Thereis in 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 controlled by the software that the designer has written. This runs in the microcontroller and determines what the system actually does. 1.2 Microprocessors and Microcontrollers Let usgo back to themicrocontroller, whichsits at theheart of any embeddedsystem. As the microcontrollerisinessenceatypeof computer, itwill beuseful forusto getagrasponbasic computer details. We do this in complete overview here, but return to some of these features 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 performarithmetic 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. Now we are getting closer to what a computer is all about. If we can keep the ALU busy, 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, normally heldinanareaof memory calledprogrammemory. This memory needs to bepermanent. If itis, thentheprogramisretainedindefinitely, whetherpowerisappliedor not, and it is ready to run as soon as power is applied. Memory like this, which keeps its contents whenpoweris removed, is callednon-volatilememory. Theold-fashionednamefor thisisreadonly memory (ROM). Thislatterterminology isstill sometimesused, eventhough it is no longer accurate for new memory technology. The control circuit needs to keep accessingtheprogrammemory, to findoutwhatthenextinstructionis. ThedatathattheALU works on may be drawn from the data memory, with the result placed there after the calculationis complete. Usually this is temporary data. This memory typethereforeneednot bepermanent, althoughthereisno harmif itis. Memory thatlosesitscontentswhenpoweris removed is called volatile memory. The old-fashioned name for this type of memory is data and address The Outside World Input/ Output data and address Central Processing Unit (CPU) data and address ALU Control Figure 1.3: Essentials of a computer Data Memory Program Memory 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 communicate with 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, at least asimpleone, thecommunicationis likely to beprimarily withthe 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. Onesetof wirescarriesthedataitself, forexamplefromprogrammemory to the CPU; this is called the data bus. Theother set of wires carries address information and is called theaddress bus. Theaddress is adigital numberthat indicates whichplaceinmemory thedatashouldbestoredin, orretrievedfrom. Thewiresineachof thedataandaddressbuses 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 8 bit, and some of that size still have useful roles to play. This means that, with their 8 bits, they can represent a number between 0 and 255. (Check Appendix A if you are unfamiliar withbinary numbers.) More recent machines are 32 or 64 bit. This gives themfar greater processing power, but adds to their complexity. Given an ALU size, it generally follows that many otherfeatures takethesamesize, forexamplememory locations, databus, and so on. Asalready suggested, theCPUhasaninstructionset, whichisasetof binary codesthatitcan recognize and respond to. For example, certain instructions will require it to add or subtract two numbers, or storeanumber in memory. Many instructions must also be accompanied by data, or addresses to data, on which the instruction can operate. Fundamentally, the program that the computer holds in its program memory and to which it responds is a list of instructions taken fromthe instruction set, withany accompanying data or addresses that are needed. Suchcodeis sometimes calledmachinecode, to distinguishit fromotherversions of 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 thesethefeaturesthat areneededforit to performitscontrol functions. It is useful to think of 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 Power Reset Interrupt(s) Program Memory Further Peripheral Data Memory Further Peripheral Microprocessor Core Internal Data & Address Buses Clock Figure 1.4: Features of an example microcontroller: core þ Digital I/0 Analog I/0 Counters & Timers 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 distinguish a microcontroller froma microprocessor, for they are the elements that allow the wide-ranging interaction with the outside world that the microcontroller needs. Peripherals canincludedigital oranaloginput/output, serial ports, timers, countersandmany otheruseful subsystems. It almost goes without saying, but must not be forgotten, that the microcontroller needs power, in the formof a stable direct current (DC) supply. A further requirement, as with any personal computer (PC), is to have a clock signal. This is the signal that endlessly steps the microcontrollercircuit throughthesequenceof actionsthat itsprogramdictates. Theclock is 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 CPU instruction set was mentioned in Section 1.2.1. As programmers, it is our 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 programinthisrawbinary formiswhat wehavealready calledmachinecode. Itisextremely tedious, to the point of being near impossible, for us as humans to work with the binary numbers that form the instruction set. A firststeptowardssanity inprogrammingiscalledAssembler. 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, and a computer programcalled a cross-assembler converts all those mnemonics 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 therefore bevery fast and efficient. Yet it is easy to make mistakes in Assembler and hard to 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 case we use a language like C, Java or Fortran to write the program, following the rules of that language. Thenacomputerprogramcalledacompilerreadstheprogramwehavewritten, and converts(compiles) thatintoalistingof instructionsfromtheinstructionset. 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, arenotlikethoseof otherprogrammers. Wewant to beableto control thehardware 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, formany applications, C has clearadvantages. Thisis becauseit is simpleandhas features that allowus to get at thehardwarewhenrequired. A stepupfromC is Cþ þ , which is also widely used for more advanced embedded applications. 1.3.2 The Development Cycle This book is about developingembeddedsystems, anddevelopingthemquickly andreliably, 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 rather simple programs in Assembler. Over theyears, the microcontrollers became more and more sophisticated, and memory much more plentiful. By now, many suppliers were selling predesignedcircuit boards containingthemicrocontrollerandall associated circuitry. 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. Despite these changes, the programdevelopment cycle is still based around the simple loop shown in Figure 1.5. Inthis book, wewill mainly write source codeusing C. The diagramof Figure1.5impliessomeof theequipmentwearelikelytoneed.Thesourcecodewill needtobe writtenonacomputere let’scall itthehostcomputere forexampleaPC, usingsomesortof text editor. The source codewill need to be converted into the binary machine codewhich is downloadedtothemicrocontroller, placedwithinthecircuitorsystemthatitwill control (let’s call this the target system). That conversion is done by the compiler, running on the host computer. Programdownload to the target systemrequires temporary connection to the host computer. Thereisconsiderableclevernessinhowtheprogramdataisactually writtenintothe programmemory, but that need not concern us here. Before the programis downloaded, it is often possible to simulate it on the host computer; this allows a programto be developed to agoodlevel beforegoingtothetroubleof downloading. However, thetruetestof theprogram isto seeitrunningcorrectly inthetargetsystem. Whenprogramerrorsarefoundatthisstage, asthey inevitably are, 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 very talentedindividualsorteams. Thedevelopmentof ARMhasseenacombinationof all of these. The full history of the development of ARM is an absolutely fascinating one, like so many otherhi-techstart-upsinthepast30orsoyears. A tiny summary isgivenbelow; 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 asked for companies to bid to supply a computer that could be used for this. Thewinner was the Acorn computer. This became an extremely popular machine, and was very widely used 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 taken very seriously these days, but was respected in its time. Responding to the growing interest in personal or desk-top computers, IBM in 1981 produced its very first PC, based on 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 pretty much incompatiblewith each other, and it was quite unclear whether onewould finally dominate. Throughout the 1980s, however, the influence of the IBM PC grew, and its smallercompetitors beganto fade. DespiteAcorn’s UK success it didnot export well, 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 anextremely clevermicroprocessor. They realizede theirsecondleape thattheirfuturemay 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 silicon to be a successful designer, what mattered was the ideas inside the design. These can 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. Those who buy Embedded Systems, Microcontrollers and ARM 13 the ARM designs incorporate them into their own products. For example, we will soon see that thembede the subject of this book e uses theARMCortex core. However, this is to be found in the LPC1768 microcontroller which sits in the mbed. This microcontroller is not made by ARM, but by NXP Semiconductors. ARM have sold NXP a license to include the Cortex core in their LPC1768 microcontroller, which ARM then buy back to put in their mbed. Got that? 1.4.2 Some Technical Detail: What does this RISC Word Mean? Because ARM chose originally to place the RISC concept in its very name, and because it remains acentral featureof ARMdesigns, it is worthcheckingout what RISC stands for. We haveseenthatany microcontrollerexecutesaprogramwhichisdrawnfromitsinstructionset, which is defined by the CPU hardware itself. In the earlier days of microprocessor development, designers were trying to make the instructions set as advanced and sophisticated as possible. The price they were paying was that this was also making the computer hardware more complex, expensive and slower. Such a microprocessor is called acomplexinstructionset computer (CISC). Boththe6502and8088mentionedabovebelong to theerawhentheCISC approachwasdominant, andareCISC machines. Onecharacteristic of theCISC approachisthatinstructionshavedifferentlevelsof complexity. Simpleonescan be expressed in a short instruction code, say one byte of data, and execute quickly. Complex ones may need several bytes of code to define them, and take a long time to execute. As compilers improved and high-level computer languages developed, it became less useful to focus on thecapabilities of theraw instructionset itself. Afterall, if youareprogramming inahigh-level language, thecompilershouldsolvemostof yourprogrammingproblemswith little difficulty. Another approach to CPU design is therefore to insist on keeping things simple, and have a limited instruction set. This leads to the RISC approach e the reduced instruction set computer. The RISC approach looks like a ‘back to basics’ move. A simple RISC CPU can execute code rapidly, but it may need to execute more instructions to complete a given task, comparedtoitsCISCcousin. Withmemory becomingevercheaperandof higherdensity, and more efficient compilers for programcodegeneration, this disadvantage is diminishing. One characteristicof theRISC approachisthateachinstructioniscontainedwithinasinglebinary word. That word must hold all information necessary, including the instruction code, as well as any address or data information needed. A further characteristic, an outcome of the simplicity of theapproach, isthatevery instructionnormally takesthesameamountof timeto execute. This allows other useful computer design features to be implemented. A good example is pipelining, anapproach by which as one instructionis being executed, the next is already being fetched frommemory. It is easy to do this with a RISC architecture, where all (or most) instructions take the same amount of time to complete. 14 Chapter 1 An interesting subplot to the RISC concept is the fact that, owing to their simplicity, RISC designs tend to lead to low power consumption. This is hugely important for anything that is battery powered, andhelpsto explainwhy ARMproductsfindtheirway into so many mobile phones. 1.4.3 The Cortex Core The Cortex microprocessor core is a 32-bit device, and follows a long line of distinguished ARM processors. A very simplified block diagram of one version, the M3, is shown in Figure 1.6. This diagram allows us to see again some computer features we have already identified, and add some new ideas. Somewhere in the middle you can see the ALU, already described as the calculating heart of the computer. The instruction codes are fed into this through the Instruction fetch mechanism, drawing instructions in turn from the program memory. Pipeliningisappliedtoinstructionfetch, sothatasoneinstructionisbeingexecuted, thenextisbeingdecoded, andtheoneafterisbeingfetchedfrommemory. Asitexecuteseach instruction, the ALU simultaneously receives data from memory and/or transfers it back to memory. This happens throughtheinterfaceblocks seen. Thememory itself is not part of the Cortex core. The ALU also has a block of registers associated with it. These act as a tiny chunk of local memory, which can be accessed quickly and used to hold temporary data as Interrupts Interrupt Controller Decoder Register Bank ALU Test Instruction Fetch Memory Interface and Debug Interface Memory Protection Unit Bus Interconnect Memory and Peripherals Figure 1.6: The Cortex-M3 core, simplified diagram Test Data Embedded Systems, Microcontrollers and ARM 15 acalculationisundertaken. TheCortex corealsoincludesaninterruptinterface. Interruptsare an important feature of any computer structure. They are external inputs that can be used to force the CPU to divert fromthe programsection it is currently executing and jump to some other sectionof code. The interrupt controllermanages thevarious interrupt inputs. It should not be too difficult to imagine this microprocessor core being dropped into the microcontroller diagram of Figure 1.4. There are several versions of the Cortex. The Cortex-M4 is the ‘smartest’ of the set, with digital signal processing capability. The Cortex-M3, the one we will be using, is targeted at embedded applications, including automotive and industrial. The Cortex-M1 is a small processor intended to be embedded in a field programmable gate array (FPGA) e a digital electronic circuit onachip, whichis configuredevery timepoweris applied, andcanevenbe reconfigured during operation if needed. The Cortex-M0 is the simplest of the group, with minimum size and power consumption. We will be meeting the Cortex-M3 core, as it is the one used in the mbed. A very detailed guideto thiscoreisgiveninReference1.2. Do not, however, try readingthisbook unlessyou are really keen to get into the fine detail; otherwise, leave it alone e it is very complex! Chapter Review • An embedded system contains one or more tiny computers, which control it and give it a sense of intelligence. • The embedded computer usually takes the form of a microcontroller, which combines microprocessor core, memory and peripherals. • Embedded system design combines hardware (electronic, electrical and electromechanical) and software (program) design. • The embedded microcontroller has an instruction set. It is the ultimate goal of the programmer to develop code which is made up of instructions from this instruction set. • Most programmingisdoneinahigh-level language, withacompilerbeingusedto convert that program into the binary code, drawn from the instruction set and recognized by the microcontroller. • ARM has developed a range of effective microprocessor and microcontroller designs, widely applied in embedded systems. Quiz 1. Explain the following abbreviations: IC, I/O, ALU, CPU. 2. Describe an embedded system in less than 100 words. 3. What are the differences between a microprocessor and a microcontroller? 16 Chapter 1 4. What range of numbers can be represented by a 16-bit ALU? 5. Whatisa‘bus’ inthecontextof embeddedsystems? Describetwo typesof busthatmight be found in an embedded system. 6. Describe the term ‘instruction set’ and explain how use of the instruction set differs for high- and low-level programming. 7. What are the main steps in the embedded program development cycle? 8. Explain the terms RISC and CISC and give advantages and disadvantages for each. 9. What is pipelining? 10. What did the acronym and company name ARM stand for? References 1.1. Wilmshurst, T. (2001). An Introduction to the Design of Small-Scale Embedded Systems. Palgrave. 1.2. Yiu, J. (2010). The Definitive Guide to the ARM Cortex-M3. 2nd edition. 2010 Newnes. CHAPTER 2 Introducing the mbed Chapter Outline 2.1 Introducing the mbed 17 2.1.1 The mbed Architecture 19 2.1.2 The LPC1768 Microcontroller 21 2.2 Getting Started with the mbed: A Tutorial 22 Step 1. Connecting the mbed to the PC 22 Step 2. Creating an mbed Account 23 Step 3. Running a Program 23 Step 4. Compiling the Program 24 Step 5. Downloading the Program Binary Code 25 Step 6. Modifying the Program Code 25 2.3 The Development Environment 25 2.3.1 The mbed Compiler and API 25 2.3.2 Using C/C++ 26 Chapter Review 26 Quiz 27 References 27 2.1 Introducing the mbed Chapter 1 reviewed some of the core features of computers, microprocessors and microcontrollers. Now we are going to apply that knowledge and enter the main material of this book, a study of the ARM mbed. In very broad terms, the mbed takes a microcontroller, such as we saw in Figure 1.4, and surrounds it with some very useful support circuitry. It places this on a conveniently sized littleprintedcircuitboard(PCB) andsupportsitwithanonlinecompiler, programlibrary and handbook. Thisgivesacompleteembeddedsystemdevelopmentenvironment, allowingusers to develop and prototype embedded systems simply, efficiently and rapidly. Fast prototyping is one of the key features of the mbed approach. Thembedtakestheformof a2 inchby 1 inch(53 mmby 26 mm) PCB, with40pinsarranged intwo rows of 20, with0.1inchspacingbetweenthepins. This spacingis astandardinmany electronic components. Figure2.1 shows different mbed views. Lookingat the main features, labeled in Figure 2.1b, we see that the mbed is based around the LPC1768 microcontroller. This is made by a company called NXP semiconductors, and contains an ARM Cortex-M3 Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00002-7 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 17 18 Chapter 2 (a) (b) NXP LPC1768 Microcontroller (c) Figure 2.1: The ARM mbed. (Image reproduced with permission of ARM Holdings) core. Program download to the mbed is achieved through a universal serial bus (USB) connector; thiscanalso powerthembed. Usefully, therearefivelight-emittingdiodes (LEDs) ontheboard, oneforstatusandfourthatareconnectedto fourmicrocontrollerdigital outputs. Theseallow aminimumsystemto betestedwith no external component connections needed. A reset switch is included, to force restart of the current program. Introducing the mbed 19 Thembedpinsareclearly identifiedinFigure2.1c,providingasummary of whateachpindoes. Inmany instances thepins aresharedbetweenseveral features to allowanumberof design options. Topleftwecanseethegroundandpowersupply pins. Theactual internal circuitruns from3.3V. However, theboardacceptsany supply voltagewithintherange4.5 to9.0V, while anonboardvoltageregulatordrops this to therequiredvoltage. A regulated3.3V output voltageisavailableonthetoprightpin, witha5 Voutputonthenextpindown. Theremainder of thepinsconnecttothembedperipherals.Thesearealmostall thesubjectof laterchapters; we will quickly overviewthemhere, thoughthey may havelimitedmeaningtoyounow. Thereare no fewerthanfiveserial interfacetypesonthembed: I2C, SPI, CAN, USB andEthernet. Then thereis aset of analoginputs, essential forreadingsensorvalues, andaset of PWMoutputs useful forcontrol of external powerdevices, forexampleDC motors. Whilenot immediately evident fromthefigure, pins 5 to 30 canalso beconfiguredforgeneral digital input/output. Thembedisconstructedto alloweasy prototyping, whichisof courseitsvery purpose. While the PCB itself is very high density, interconnection is achieved through the very robust and traditional dual-in-line pin layout. Background information for the mbed and its support tools can be found at the mbed home page(Reference2.1). Whilethisbook isintendedto giveyouall informationthatyouneedto start work with the mbed, it is inevitable that you will want to keep a close eye on this site, withitscookbook, handbook, blogandforum. Aboveall else, itprovidestheentry pointtothe mbed compiler, through which you will develop all your programs. 2.1.1 The mbed Architecture A block diagramrepresentationof thembedarchitectureisshowninFigure2.2. Itispossible, and useful, to relate the blocks shown here to the actual mbed. At the heart of the mbed is theLPC1768microcontroller, clearly seeninboth Figures 2.1and2.2. Thesignal pins of the mbed, as seen in Figure 2.1c, connect directly to the microcontroller. Thus, when in the coming chapters we use an mbed digital input or output, or the analog input, or any other of the peripherals, we will be connecting directly to the microcontroller within the mbed, and relyingonitsfeatures. Aninterestingasidetothis, however, isthattheLPC1768has100pins, butthembedhasonly 40. Thus, whenwegetdeeperintounderstandingtheLPC1768, wewill find that there are some features that are simply inaccessible to us as mbed users. This is, however, unlikely to be a limiting factor. Thereis asecondmicrocontrolleronthembed, whichinterfaces withtheUSB. Thisis called the interface microcontroller in Figure 2.2, and is the largest integrated circuit (IC) on the underside of the mbed PCB. The cleverness of the mbed hardware design is the way which this device manages the USB link and acts as a USB terminal to the host computer. In most commonuseit receives programcodefiles throughtheUSB, andtransfers thoseprograms to a 16 Mbit memory, which acts as the ‘USB disk’. When a program ‘binary’ is downloaded 20 Chapter 2 USB MBED 4.5V-9.0V in (“VIN”) 5.0V USB out (“VU”) 3.3V out (“VOUT”) 0V (“GND”) USB power Power Management reset Flash Memory “USB Disk” 16 Mbit Interface Microcontroller reset UART JTAG 3.3V internal supply Mbed external signal connections LPC1768 microcontroller Mbed external signal connections Ethernet PHY Ethernet Key PHY: Physical interface JTAG: Joint Test Action Group (interface) UART: Universal Asynchronous Receiver/Transmitter Figure 2.2: Block diagram of mbed architecture. to the mbed, it is placed in the USB disk. Whenthe reset button is pressed, the programwith the latest timestamp is transferred to the flash memory of the LPC1768, and program execution commences. Data transfer between interface microcontroller and the LPC1768 goes as serial data through the UART (which stands for universal asynchronous receiver/ transmitter e a serial data link, let’s not get into the detail now) port of the LPC1768. The ‘Power Management’ unit is made up of two voltage regulators, which lie either side of the status LED. There is also a current-limiting IC, which lies at the top left of the mbed. The mbed can be powered from the USB; this is a common way to use it, particularly for simple applications. For more power-hungry applications, or those that require a higher voltage, it canalso bepoweredfromanexternal 4.5to 9.0 V input, suppliedto pin2(labeled VIN). Power can also be sourced from mbed pins 39 and 40 (labeled VU and VOUT, respectively). The VU connection supplies 5 V, taken almost directly from the USB link; henceit is only availableif theUSB is connected. TheVOUT pinsupplies aregulated3.3 V, which is derived either from the USB or from the VIN input. For those who are inclined, the mbed circuit diagrams are available on the mbed website (Reference 2.2). Introducing the mbed 21 2.1.2 The LPC1768 Microcontroller A block diagram of the LPC1768 microcontroller is shown in Figure 2.3. This looks complicated, and we do not want to go into all the details of what is a hugely sophisticated digital circuit. However, the figure is in a way the agenda for this book, as it contains all the capability of the mbed, so it is worth getting a feel for the main features. If you want to Up to 64 KB SRAM Up to 512 KB FLASH Test/ Debug CPU PLL Nested VIC Trace Brown Out Detect SRAM Controller FLASH Accelerator Cortex-M3 Core MPU Power On Reset Multi-layer AHB Matrix Ethernet MAC 3 x I2C FM+ DMA 3x SSP/SPI USB Host/OTG/D PHY PLL 4 x UARTs RS485/IrDA/Modem I2S DMA GP DMA 2x CAN2.0B Advanced Peripheral Bus 12-bit/8-ch ADC 10-bit DAC 4 x 32-bit Timers Motor Control PWM KEY ADC: Analog-to-Digital Converter AHB: Advanced High-performance Bus CPU: Central Processing Unit D: Device (USB) DAC: Digital-to-Analog Converter DMA: Direct Memory Access FMþ: Fast-Mode Plus (I2C) GP: General Purpose (DMA) I2C: Inter-Integrated Circuit I2S: Inter-Integrated circuit Sound IrDA: Infrared Data Association MAC: Media Access Control MPU: Memory Protection Unit PHY: Physical layer PLL: Phase-Locked Loop OTG: On-The-Go (USB) SPI: Serial Peripheral Interface SRAM: Static RAM SSP: Synchronous Serial Port UART: Universal Asynchronous Receiver/Transmitter VIC: Vectored Interrupt Controller. Note: The LPC1768 has 64 KB of SRAM and 512 KB of flash. The Cortex core is made up of those items enclosed within the dashed line. See also key to Figure 2.1 (Reproduced from mbed NXP LPC1768 prototyping board. 2009. NXP BV. Document no. 9397 750 16802) Figure 2.3: The LPC1768 block diagram. Quad Encoder Interface brb276 22 Chapter 2 get complete detail of this microcontroller, then consult one or more of References 1.2, 2.3 and 2.4. Although these references are mentioned from time to time in the book, consulting them is not necessary for a complete reading of the book. Remember that a microcontroller is made up of microprocessor core plus memory plus peripherals, as shown in Figure 1.4. Let’s look for these. Top center in Figure 2.3, contained within the dotted line, is the core of this microcontroller, the ARM Cortex-M3. This is a compressed version of Figure 1.6, the M3 outline that was considered in Chapter 1. To theleftof thecorearethememories: theprogrammemory, madewithFlashtechnology, is usedforprogramstorage; to theleft of that is thestatic RAM(randomaccess memory), used for holding temporary data. That leaves most of the rest of the diagram to show the peripherals, which give the microcontroller its embedded capability. These lie in the center and lower half of the diagram, and reflect almost exactly what the mbed can do. It is interesting to compare the peripherals seen here with the mbed inputs and outputs seen in Figure2.1c. Finally, all thesethingsneedto beconnectedtogether, atask doneby theaddress and data buses. Clever though they are, we have almost no interest in this side of the microcontroller design, at least not for this book. It is sufficient to note that the peripherals connect through something called the advanced peripheral bus. This in turns connects back throughabus interconnect calledthe advanced high-performancebus matrix, andfromthere to the central processing unit (CPU). This interconnection is not completely shown in this diagram, and we have neither need nor wish to think about it further. 2.2 Getting Started with the mbed: A Tutorial Now comes the big moment when you connect the mbed for the first time, and run a first program. We will follow the procedure given on the mbed website and use the introductory program on the compiler, a simple flashing LED example. You will need: • an mbed microcontroller with its USB lead • a computer running Windows (XP, Vista or 7), Mac OS X or GNU/Linux • a web browser, for example Internet Explorer or Firefox. Now follow the sequence of instructions below. The purpose of this tutorial is to explain the main steps in getting a program running on the mbed. We will look into the detail of the program in the next chapter. Step 1. Connecting the mbed to the PC ConnectthembedtothePCusingtheUSB lead. TheStatuslightwill comeon, indicatingthat the mbed has power. After a few seconds of activity, the PC will recognize the mbed as astandardremovabledrive, anditwill appearonthedeviceslinkedtothecomputer, asseenin Figure 2.4. Introducing the mbed 23 Figure 2.4: Locating the mbed: (a) Windows XP example; (b) Mac OS X example Step 2. Creating an mbed Account OpentheMBED.HTM filefoundonthembedinyourwebbrowserandclick theCreateanew mbed Account link. Follow the instructions to create an mbed Account. This will lead you to the website, as seen in Figure 2.5. From here you can link to the compiler, libraries and documentation. Step 3. Running a Program Open the compiler using the link in the site menu, i.e. at the right of Figure 2.5. By doing this you enter your allocated personal program workspace. The compiler will open in a new tab or window. Follow these steps to create a new program: • As seen in Figure 2.6a, right-click (Mac users, Ctrl-click) on ‘My Programs’ and select ‘New Program . ’. • Chooseandenteranameforthenewprogram(forexampleProg_Ex_2_1) andclick ‘OK’. Do not leave spaces in the program name. • Your new program folder will be created under ‘My Programs’. Click onthe‘main.cpp’ fileinyour new programto openit inthe fileeditor window, as seen in Figure 2.6b. This is the main source code file in your program. Whenever you create Figure 2.5: The mbed home page 24 Chapter 2 Figure 2.6: Opening a new program: (a) selecting New Program; (b) opening the main source file a new program it always contains the same simple code. This is shown here as Program Example 2.1. This program will be examined in the next chapter. The other item in the program folder is the ‘mbed’ library. This provides all the functions used to start up and control the mbed, such as the DigitalOut interface used in this example. /* Program Example 2.1: Simple LED flashing */ #include "mbed.h" DigitalOut myled(LED1); int main() { while(1) { myled = 1; wait(0.2); myled = 0; wait(0.2); } } Program Example 2.1 Simple LED flashing Step 4. Compiling the Program To compile the program, click the ‘Compile’ button in the toolbar. This will compile all the source code files within the programfolder to create the binary machine code which will be downloaded to the mbed. Typically, this is the single program you have written, plus the library calls you have almost certainly made. After a successful compile, you will get a ‘Success!’ message in the compiler output, and a popup will prompt you to download the compiled .bin file to the mbed. Introducing the mbed 25 Of course, withthisgivenprogram, itwouldbemostsurprisingtofindithadanerrorinit; you will not be so lucky with future programs! Try inserting a small error into your source code, forexampleby removingthesemi-colonattheendof aline, andcompilingagain. Noticehow the compiler gives a useful error message at the bottom of the screen. Correct the error, compile again and proceed. The type of error you have just inserted is often called a syntax error. Thisisanerrorwhichrelatestotherulesof writinglinesof Ccode. Whenasyntax error is found, the compiler is unable to proceed with the compilation, as it perceives that the programhassteppedoutsidetherulesof thelanguage, andhencecannot reliably interpretthe code that is written. Step 5. Downloading the ProgramBinary Code After a successful compile, the program code, in binary form, can be downloaded to the mbed. Save it to the location of the mbed drive. You should see the Status LED (as seen in Figure2.1) flashas theprogramdownloads. OncetheStatus LED has stoppedflashing, press the reset button on the mbed to start your program running. You should now see LED1 flashing on and off every 0.2 seconds. Step 6. Modifying the ProgramCode In the main.cpp file, simply change the DigitalOut statement to read: DigitalOut myled(LED4); Now compile and download your code to the mbed. You should now see that LED4 flashes instead of LED1. You can also change the pause between flashes by modifying the values bracketed in the wait( ) command. 2.3 The Development Environment As Section 1.3 suggests, there are many different approaches to development in embedded systems. With the mbed there is no software to install, and no extra development hardware needed for program download. All software tools are placed online, so that you can compile anddownloadwhereveryouhaveaccessto theInternet. Notably, thereisaCþ þ compilerand an extensive set of software libraries, used to drive the peripherals. Thus, there is no need to write code to configure peripherals, which in some systems can be very time consuming. 2.3.1 The mbed Compiler and API The mbed development environment uses the ARM RVDS (RealView Development Suite) compiler, currently Version 4.1. All features of this compiler relevant to the mbed are available through the mbed portal. 26 Chapter 2 One thing that makes the mbed special is that it comes with an application programming interface (API). In brief, this is the set of programming building blocks, appearing as Cþ þ utilities, which allow programs to be devised quickly and reliably. Therefore, we will be writingcodeinC orCþ þ , but drawingonthefeatures of theAPI. Youwill meet most of the features of this as you work through the book. Note that you can see all components of the API by opening the mbed handbook, linked from the mbed home page. 2.3.2 Using C/C++ Asjustmentioned, thembeddevelopmentenvironmentusesaCþ þ compiler. Thatmeansthat all fileswill carrythe.cpp(Cplusplus)extension.C,however,isasubsetof Cþ þ ,andissimpler tolearnandapply. Thisisbecauseitdoesnotusethemoreadvanced‘object-oriented’ aspectsof Cþ þ . Ingeneral, C codewill compileonaCþ þ compiler, but not theotherway round. C isusually thelanguageof choiceforany embeddedprogramof lowormediumcomplexity, so will suit us well in this book. For simplicity, therefore, we aim to use only C in the programswedevelop. Itshouldberecognized, however, thatthembedAPI iswritteninCþ þ anduses thefeaturesof that languageto thefull. Wewill aimto outlineany essential features when we come to them. This book does not assume that you have any knowledge of C or Cþ þ , although youhaveanadvantageif youdo. Weaimto introduceall newfeatures of C as they come up, flagging this by using the symbol alongside. If you see that symbol and you are a C expert, then it means you can probably skim through that section. If you are not an expert, you will need to read the section with care and refer to Appendix B, which summarizes all theC features used. Evenif youareaC expert, youmay not haveused it inan embedded context. As you work through the book you will see a number of tricks and techniques that are used to optimize the language for this particular environment. C code feature Chapter Review • The mbed is a compact, microcontroller-based hardware platform, accompanied by a program development environment. • Communication to the mbed from a host computer is by USB cable; power can also be supplied through this link. • The mbed has 40 pins, which can be used to connect to an external circuit. On the board it has four user-programmable LEDs, so very simple programs can be run with no external connection to its pins. • The mbed uses the LPC1768 microcontroller, which contains an ARM Cortex-M3 core. Most mbed connections link directly to the microcontroller pins, and many of the mbed characteristics derive directly from the microcontroller. Introducing the mbed 27 • The mbed development environment is hosted on the web. Program development is undertaken while online, and programs are stored on the mbed server. Quiz 1. What do ADC, DAC and SRAM stand for? 2. What do UART, CAN, I2C and SPI stand for, and what do these mbed features have in common? 3. How many digital inputs are available on the mbed? 4. Which mbed pins can be used for analog input and output? 5. How many microcontrollers are on the mbed PCB and what specifically are they? 6. What is unique about the mbed compiler software? 7. An mbed is part of a circuit which is to be powered from a 9 V battery. After programming the mbed is disconnected from the USB. One part of the circuit external to thembedneeds to besupplied from9 V, andanotherpart from3.3 V. No otherbattery orpowersupply istobeused. Drawadiagramwhichshowshowthesepowerconnections should be made. 8. Anmbedisconnectedto asystem, andneedstoconnectwiththreeanaloginputs, oneSPI connection, one analog output and two PWM outputs. Draw a sketch showing how these connections can be made, and indicate mbed pin number. 9. A friend enters the code shown below into the mbed compiler, but when compiling a number of errors are flagged. Find and correct the faults. #include "mbed" Digital Out myled(LED1); int man() { white(1) { myled = 1; wait(0.2) myled = 0; watt(0.2); } 10. By not connecting all the LPC1768 microcontroller pins to the mbed external pins, a number of microcontroller peripherals are ‘lost’ for use. Identify which ones these are, for ADC, UART, CAN, I2C, SPI and DAC. References 2.1. The mbed home site. http://mbed.org/ 2.2. MBED Circuit Diagrams. 26/08/2010. http://mbed.org/media/uploads/chris/mbed-005.1.pdf 2.3. NXP B.V. LPC1768/66/65/64 32-bit ARM Cortex-M3 microcontroller. Objective data sheet. Rev. 6.0. August 2010. http://www.nxp.com/ 2.4. NXP B.V. LPC17xx User Manual. Rev. 02. August 2010. http://www.nxp.com/ C H A P T E R 3 D ig it a l In p u t a n d O u t p u t C h a p t e r O u t lin e 3 .1 S t a r t in g t o P r o g r a m 2 9 3 .1 .1 T h in k in g a b o u t t h e F ir s t P r o g r a m 3 .1 .2 U n d e r s t a n d in g t h e m b e d A P I 3 2 3 .1 .3 E x p lo r in g t h e w h ile L o o p 3 3 3 0 3 .2 V o lt a g e s a s L o g ic V a lu e s 3 4 3 .3 D ig it a l O u t p u t o n t h e m b e d 3 6 3 .3 .1 U s in g L E D s 3 6 3 .3 .2 U s in g m b e d E x t e r n a l P in s 3 .4 U s in g D ig it a l In p u t s 3 7 3 9 3 .4 .1 C o n n e c t in g S w it c h e s t o a D ig it a l S y s t e m 3 9 3 .4 .2 T h e D ig it a lIn A P I 4 0 3 .4 .3 U s in g if t o R e s p o n d t o a S w it c h In p u t 4 0 3 .5 In t e r f a c in g S im p le O p t o D e v ic e s 3 .5 3 .5 3 .5 3 .5 .1 O p t .2 C o n .3 S e v e .4 C o n o R n e c n -S n e c e fle c t in g e g m t in g t iv e a n e n t a S 4 2 a n d T r a n s m is s iv e S e n s o r s 4 2 O p to -S e n so r to th e m b e d 4 3 D is p la y s 4 5 e v e n - s e g m e n t D is p la y t o t h e m b e d 3 .6 S w it c h in g L a r g e r D C L o a d s 4 9 3 .6 .1 A p p ly in g T r a n s is t o r S w it c h in g 4 9 3 .6 .2 S w it c h in g a M o t o r w it h t h e m b e d 5 0 3 .6 .3 S w it c h in g M u lt ip le S e v e n - S e g m e n t D is p la y s 3 .7 M C h a p t Q u iz R e fe re in i- P r o je c t : L e t t e r C o u n t e r e r R e v ie w 5 3 5 3 n c e s 5 5 3 .1 S t a r t in g t o P r o g r a m Th is ch ap ter will co n sid d ig ital sig n als. Mo v in g a p ro g ram b ased o n th e time in th e emb ed d ed e tim in g a c tiv ity a s w e ll. er th b ey o v alu n v iro 4 6 5 1 5 3 a t m o s t b a s ic o f m ic ro c o n tro lle r a c tiv ity , th e in p u t a n d n d th is, it will sh o w h o w we can mak e simp le d ecisio e o f a d ig ita l in p u t. F ig u r e 1 .1 a ls o p r e d ic te d th e im p o n men t; n o su rp rise th erefo re th at at th is early stag e w F a s t a n d E f f e c t iv e E m b e d d e d S y s t e m s D e s ig n . D O I : 1 0 .1 0 1 6 /B 9 7 8 - 0 - 0 8 - 0 9 7 7 6 8 - 3 .0 0 0 0 3 - 9 Co p y rig h t Ó2 0 1 2 Elsev ier Ltd . All rig h ts reserv ed . 2 9 o u tp u t o f n s with in rtan ce o f e meet 3 0 Chapter 3 Yo u m a y a ls o b e e m b a r k in g o n C p r o g r a m m in g f o r th e fi r s t tim e . T h is c h a p te r ta k e s y o u th ro u g h q u ite a few o f th e k ey co n cep ts. If y o u are n ew to C, we su g g est y o u n o w read th ro u g h S e c t i o n s B 1 eB 5 i n c l u s i v e o f A p p e n d i x B . On e th in g electro n ics su p p o rt in wh en n eed 3 .1 .1 th at . So th is ed . is n o t ex p ecte me u n d erstan d area, y o u mig Th ere are man Th ere are two way s o f in s On e is to p lace th e co mm in fo rmatio n ru n n in g o v er are u sed , th e co mp iler ig n co mmen t. th at y o u write to o f th e p ro g ram. o u g h t p ro cess as v er it, an d h elp o so rt o f team-wo r ertin g co en t b etw sev eral o res an y m ee lin te is b o o k ry will, lik e Re is area a is a d eep k n o wled g e o f d ig ital h o wev er, b e u sefu l. If y o u n eed f e r e n c e 3 .1 a v a ila b le , to a c c e s s s well. / * P r o g r a m E x a m p l e D e m o n s t r a t i n g u s e * / # i n c l u d e / / " m b e d . h " p r o g r a m D i g i t a l O u t i n e y l a i th r seq th e wh an d b o /. Th is n two lin e o n e p to y o d e h a ro g ram; th ey h av e n o in tro d u ce co mmen ts u wh at th e p ro g ram was rstan d th e p ro g ram. Th is n d in g in wo rk to b e th are u sed is u sefu l fo fo rward -sla ly ; th is can e e lin e s , g iv e s a b rie f u en t p ro g rams in th e p ro g ram a little mo re a t in d iv id u a l lin e s o f in th is ex r a b lo ck sh sy mb o th en b e u / / i n c l u d e / / / / / / / / t h a s w w a i s t h e m b e d c r e a t e d , e f u n c o n t i n u o u s i t c h t h e l i t 0 . 2 s e c c t l o e d o n h e a d e r a n d f i l e l i n k e d a s p a r t w i t h i o n s t a r t s h e r e o p i s c r e a t e d o n , b y s e t t i n g d s t h e m b e d o f t h i s m b e d p r o g r a m L E D 1 o u t p u t t o amp le. o f tex t ls (//) sed fo r su mmary o f wh at th e b o o k . No tice also th at read ab le. We th en p u t co d e d o . 2 . 1 : A p r o g r a m w h i c h f l a s h e s m b e d L E D 1 o n a n d o f f . o f d i g i t a l o u t p u t a n d w a i t f u n c t i o n s . T a k e n f r o m t h e v a r i a b l e m y l e d m y l e d ( L E D 1 ) ; ( ) { ( 1 ) { e d = 1 ; t ( 0 . 2 ) ; y o u rself with in th It is g o o d p ractice y o u write, remin d th ers to read an d u n k in g , o r if y o u a re men ts in to a p ro g ram, n th e mark ers /* an d * e s . A lte rn a tiv e ly , w h e x t th at fo llo ws o n th at o p en in g co mmen t in th e p ro g ram, lastin g ram d o es. We ad o p t th is p ractice in all su b av e in tro d u ced so me b lan k lin es, to mak e mb er o f in -lin e co mmen ts; th ese in d icate m a w h i l m w th eo o k th k a t o u r fi r s t p r o g r a m , in tr o d u c e d a s P r o g r a m E x a m p le 2 .1 . T h is is s h o w n n v en ien ce, th is time with co mmen ts in serted . Co mp are th is with th e e o f th e p ro g ram, sh o wn in Ch ap ter 2 . Rememb er to ch eck acro ss to y o u n eed fu rth er C b ack g ro u n d . Co mmen ts are tex t messag es imp act o n th e actu al wo rk in g wid ely ; th ey h elp y o u r o wn th mean t to d o as y o u lo o k b ack o last p o in t is essen tial fo r an y mark ed ! i n t u in read in g electro n ic th to h av e a b o web sites in T h in k in g a b o u t t h e F ir s t P r o g r a m We n o w tak e a lo o ag ain b elo w fo r co o rig in al ap p earan c Ap p en d ix B wh en Th e p ro g we h a n u d o f y o in g o f h t lik e y g o o d l o g i c 1 s i t e . D ig it a l In p u t a n d O u t p u t m y l e d = 0 ; w a i t ( 0 . 2 ) ; } } / / / / / / / / s w w a e n e n 3 1 i t c h t h e l e d o f f i t 0 . 2 s e c o n d s d o f w h i l e l o o p d o f m a i n f u n c t i o n P r o g r a m E x a m p le 2 .1 R e p e a t e d ( a n d c o m m e n t e d ) fo r c o n v e n ie n c e L e t’s n o w id e n tif y a ll th e C p r o g r a m m in g f e a tu r e s o f P r o g r a m E x a m p le 2 .1 . T h e actio n o f a n y C o r Cþ þ p ro g ram is co n tain ed with in its m a in ( ) fu n ctio n , so th at is alway s a g o o d p lace to start lo o k in g . By th e way , writin g m a in ( ) with th o se b rack ets after it remin d s u s th at it is th e n ame o f a C fu n ctio n ; all fu n ctio n n ames are written in th is way in th e b o o k . T h e fu n c tio n d e fi n itio n ew h a t g o e s o n in s id e th e f u n c tio n eis c o n ta in e d w ith in th e o p en in g cu rly b rack et o r b race, ap p earin g immed iately after m a in ( ), an d g o es o n u n til th e clo sin g b race. Th ere are fu rth er p airs o f b races in sid e th ese o u ter o n es. Usin g p airs o f b races lik e th is is o n e o f th e way s th at C g ro u p s b lo ck s o f co d e to g eth er an d creates p ro g ram stru ctu re. C c o d e fe a tu re M a n y p r o g r a m s in e m b e d d e d s y s te m s a r e m a d e u p o f a n e n d le s s lo o p , i.e . a p ro g ram wh ich ju st g o es o n an d o n rep eatin g itself in d efin itely . Here is o ex amp le. We create th e lo o p b y u sin g th e w h ile k ey wo rd ; th is co n tro ls th e w ith in th e p a ir o f b r a c e s th a t f o llo w. S e c tio n B .7 ( in A p p e n d ix B ) te lls u s th a t n o r m a lly w u sed to set u p a lo o p , wh ich rep eats if a certain co n d itio n is satisfied . Ho wev er, if we w h ile (1 ), th en we “trick ” th e w h ile mech an ism to rep eat in d efin itely . C c o d e fe a tu re u r first co d e h ile is write Th e real actio n o f th e p ro g ram is co n tain ed in th e fo u r lin es with in th e w h ile lo o p . Th ese are mad e u p o f two calls to th e lib rary fu n ctio n w a it( ), an d two statemen ts, in wh ich th e v alu e o f m y le d is ch an g ed . Th e w a it( ) fu n ctio n is fro m th e mb ed y ; f u r th e r o p tio n s a r e s h o w n in Ta b le 3 .1 . T h e 0 .2 p a r a m e te r is in s e c o n d s , a n d d e fi n e s th e len g th cau sed b y th is fu n ctio n ean o th er v alu e can b e ch o sen . In th e two statemen ts in in g m y le d we mak e u se o f a C o p erato r fo r th e first time. Here, we u se th e a ssig n to r, wh ich ap p lies th e co n v en tio n al eq u als sig n . No te carefu lly th at in C th is o p erato r s th at a v ariab le is set to th e v alu e in d icated . Th u s, C c o d e fe a tu re lib rar d elay co n ta o p era mean m y l e d = 1 ; mean s th at Co n v en tio n ch ap ter. Th meet it fo r th e al “ ere th e v ariab le m y le d is set to th e v alu e eq u als” is rep resen ted b y a d o u b le are man y C o p erato rs, an d it is wo first time. Th ey are su mmarized in 1 , wh atev er its p rev io u s v alu e was. e q u a ls s ig n , i.e . ¼ ¼ . I t is u s e d la te r in th is rth n o ticin g an d learn in g each o n e as y o u S e c tio n B .5 . T a b le 3 .1 : m b e d lib r a r y w a it f u n c t io n s C / C þ þ f u n c t io n A c t io n w a i t W a it s fo r t h e n u m b e r o f s e c o n d s s p e c ifi e d w a i t _ m s W a it s fo r t h e n u m b e r o f m illis e c o n d s s p e c ifi e d w a i t _ u s W a it s fo r t h e n u m b e r o f m ic r o s e c o n d s s p e c ifi e d 3 2 Chapter 3 Th e p ro g ram starts b y in clu d in g th e all-imp o rtan t mb ed h ead er file, wh ich is th e co n n ectin g p ath way to all mb ed lib rary featu res. Th is mean s th at th e h ead er file is literally in serted in to th e p ro g ram, b efo re co mp ilin g starts in earn est. Th e # in c lu d e c o m p ile r d ir e c tiv e is u s e d f o r th is ( S e c tio n B .2 .3 ) . T h e p r o g r a m th e n a p p lie s th e m b e d a p p lic a tio n p r o g r a m m in g in te r f a c e ( A P I ) u tility D ig it a lO u t to d e fi n e a d ig ita l o u tp u t, a n d g iv e s it th e n ame m y le d . On ce d eclared , m y le d can b e u sed as a v ariab le with in th e p ro g ram. Th e n ame LED1 is reserv ed b y th e API fo r th e o u tp u t asso ciated with th at lig h t-emittin g d io d e ( L E D ) o n th e m b e d b o a r d , a s la b e le d in F ig u r e 2 .1 b . C c o d e fe a tu re No tice th at we w h ile co d e b lo mo re read ab le p ro g rams in th Co mp an ies wo in a read ab le a n in d en t th e co d e b y two ck . Th is h as n o effect o an d h en ce cu t d o wn o n is b o o k . Ch eck Sectio n rk in g with C o ften ap p ly n d co n sisten t fash io n . sp aces with in m a in ( ), an d th en two mo re with in n th e actio n o f th e p ro g ram, b u t d o es h elp to mak p ro g rammin g erro rs; it is a p ractice we ap p ly fo r B .1 1 f o r o th e r c o d e la y o u t p r a c tic e s th a t w e a d o p ‘h o u se sty les’, to en su re th at p ro g rammers write c th e e it t. o d e E x e r c is e 3 .1 G e t fa m ilia r w it h P r o g r a m E x a m p le 2 .1 , a n d t h e g e n e t h e fo llo w in g v a r ia t io n s . O b s e r v e t h e e ffe c t s . 1 . A d d t h e c o m m e n t s , o r o t h e r s o f y o u r o w n , g iv e n p r o g r a m c o m p ile s a n d r u n s w it h o u t c h a n g e . 2 . V a r y t h e 0 .2 p a r a m e t e r in t h e w a it ( ) fu n c t io n s . 3 . R e p la c e t h e w a it ( ) fu n c t io n s w it h w a it _ m s ( ) fu n p a r a m e t e r s e t t o g iv e t h e s a m e w a it t im e . A ls o v a 4 . U s e L E D 2 , 3 o r 4 in s t e a d o f 1 . 5 . M a k e a m o r e c o m p le x lig h t p a t t e r n u s in g t w o o r fu n c t io n c a lls . r a l p r o c e s s o f c o m p ilin g , b y t r y in g in t h e e x a m p le . S e e t h a t t h e c t io n s , w it h a c c o m p a n y in g r y t h is t im e . m o r e L E D s , a n d m o r e w a it ( ) n 3 .1 .2 Th e u sed web API In cla me mu U n d e r s t a n d in g t h e m b e d A P I mb ed API h as a p to it. Th e lib rary site Han d b o o k . Th su mmary fo r th is a ss m st attern th is mad e e first th is g iv e n at we will u p o f a se at we lo o k in Tab le 3 p attern th at will b eco me familiar , ca lle d D ig ita lO u t. Th is ap p ears b er fu n ctio n s, wh ich are listed b e h av e th e same n ame as th e class see rep eated man y times, so it is imp o rtan t to g et t o f u tilities, wh ich are all itemized in th e mb ed at is D ig ita lO u t, wh ich we h av e alread y u sed . Th e .2 . , th e D at th e lo w. T itself. ig ita h ead h e fir Th is lO u o f st o can t API co th e tab le. f th ese is b e u sed mp o n en t create Th e c lass th en a C þ þ co n str u to create Cþ þ s a Cþ þ h as a set o f c to r, w h ich o b jects. By D ig it a l In p u t a n d O u t p u t 3 3 T a b le 3 .2 : T h e m b e d d ig it a l o u t p u t A P I s u m m a r y ( f r o m w w w .m b e d .o r g ) F u n c t io n U s a g e D i g i t a l O u t C r e a t e a D ig it a lO u t c o n n e c t e d t o t h e s p e c ifi e d p in w r i t e S e t t h e o u t p u t , s p e c ifi e d a s 0 o r 1 ( in t ) r e a d R e t u r n t h e o u t p u t s e t t in g , r e p r e s e n t e d a s 0 o r 1 ( in t ) o p e r a t o r = A s h o r t h a n d fo r w r it e o p e r a t o r i n t ( ) A s h o rth a n d fo r re a d u sin g th e D ig ita lO u t co n stru cto r, we cre ate th e o b je ct m y le d . We c an th e n w r ite ( ) an d r e a d ( ). Th ese are memb m y le d .w r it e ( ) , a n d s o o n . H a v in g c r e API o p e ra to r sh o rth a n d , me n tio n e d in Hen ce, wh en we write m y l e d = can c re ate Cþ þ o b je cts . write to it an d read fro m er fu n ctio n s o f th e c la ss, ated th e m y le d o b ject we Ta b le 3 .2 , w h ic h a p p lie s In o u r first ex amp le it, u sin g th e fu n ctio so th eir fo rmat wo u can , h o wev er, in v o k th e assig n o p erato r we n s ld b e e th e ¼ . 1 ; th e v ariab le v alu e is th en n o t o n ly ch an g ed (n o rmal C u sag e), b u t also written to th e d ig ital o u tp u t. T h is r e p la c e s m y le d .w r it e ( 1 ) ; . We w ill fi n d s im ila r s h o r th a n d s o ff e r e d f o r a ll p erip h eral API g ro u p s in th e mb ed API. 3 .1 .3 E x p lo r in g t h e w h ile L o o p P r o g r a m E x a m p le 3 .1 is th e fi r s t “ o r ig in a l” p r o g r a m in th is b o o k , a lth o u g h it b u ild s d ir e c tly o n th e p rev io u s ex amp le. Create a n ew p ro g ram in th e mb ed co mp iler an d co p y th is ex amp le in to it. L o o k fi rs t a t th e s tru c tu re o f th e p ro g ra m , d e riv e d fro m th e th re e u s e s o f w h ile ; o n e o f th ese is a w h ile (1 ), wh ich we are u sed to , an d two are co n d itio n al. Th ese latter are b ased o n th e v alu e o f a v ariab le i. In th e first co n d itio n al u se o f w h ile , th e lo o p r e p e a ts a s lo n g a s i is le s s th a n 1 0 . Yo u c a n s e e th a t i is in c r e m e n te d w ith in th e lo o p , to b rin g it u p th is v alu e. In th e seco n d co n d itio n al lo o p , th e v alu e is d ecremen ted , an d th e lo o p rep eats as lo n g as i is g reater th an zero . C c o d e fe a tu re A v ery imp o rtan t n ew is d ecla red at th e b eg ty p e o f an y v ariab le b S e c tio n B .3 . I n th is e x a m p le , i is same lin e, its v alu e is in itialized , < a n d >. T h e u s e o f t h e s e i s immed iately familiar. C c o d e fe a tu re C featu re seen in th is p ro g ram is th e way th at th e v aria b le i in n in g o f m a in ( ). It is e s s e n tia l in C to d ec la re th e d a ta e fo re it is u s e d . T h e p o s s ib le d a ta ty p e s a re g iv e n in d e c la re d a s a c h a ra c te r, e ffe c tiv e ly a n 8 -b it n u m b e r. In th e to zero . Th ere are also fo u r n ew o p erato rs in tro d u ced : þ , th e s ame as in co n v e n tio n al alg eb ra , so sh o u ld b e 3 4 / * * / # i D i D i Chapter 3 P r o g r a m E x a m p l e 3 . 1 : D e m o n s t r a t e s u s e o f w h i l e l o o p s . N o e x t e r n a l c o n n e c t i o n r e q u i r e d n c l u d e " m b e d . h " g i t a l O u t m y l e d ( L E D 1 ) ; g i t a l O u t y o u r l e d ( L E D 4 ) ; i n t m c h a w h i w h i m w m w i a i r l e l e y l a i y l a i = n ( i = ( 1 ( i e d t ( e d t ( i ) 0 ; ) { < 1 = 0 . = 0 . + 1 { 0 ) 1 2 ) 0 2 ) ; / / d e c l a r e v a r i a b l e i , a n d / / s t a r t e n d l e s s l o o p / / s t a r t f i r s t c o n d i t i o n a l { l e o u a i o u a i = ( i r l t ( r l t ( i > 0 e d 0 . e d 0 . - 1 ) = t o w h i l e 0 l o o p ; ; ; ; } w h i y w y w i s e t { 1 ; / / i n c r e m e n t i / / e n d o f f i r s t / / s t a r t s e c o n d c o n d i t i o n a l c o n d i t i o n a l w h i l e l o o p l o o p 2 ) ; = 0 ; 2 ) ; ; } } / / e n d / / e n d } i n f i n i t e o f m a i n l o o p b l o c k P r o g r a m E x a m p le 3 .1 U s in g w h ile H a v in g c o m p ile d P r o g r a m E x a m p le 3 .1 , d o w n lo a d it to th e m b e d , a n d r u n it. Yo u s h o u ld s e e LED1 an d LED4 flash in g 1 0 times in tu rn . Mak e su re y o u u n d erstan d wh y th is is so . n E x e r c is e 3 .2 C c o d e fe a tu re 1 . A s lig h t ly m o r e e le g a n t w a y o f in c r e m e n t h e in c r e m e n t a n d d e c r e m e n t o p e r a t o r s i[ iþ 1 ; a n d i [ i 1 ; w it h iþ þ ; a n d i ; r e s p e c t iv a n d r u n t h e p r o g r a m a g a in . 2 . C h a n g e th e p ro g ra m s o th a t th e L E D s fl 3 . T r y r e p la c in g t h e m y le d [ 1 ; s t a t e m e n t t in g o r d e c r e m e n t in g a v a r ia b le is b y u s in g s e e n in S e c t io n B .5 . T r y r e p la c in g e ly , a s h o n ly fi v e t im e s e a c h . w it h m y le d .w r it e ( 1 ) ; n 3 .2 V o lt a g e s a s L o g ic V a lu e s Co mp u ters d eal with b in ary n u mb ers mad e u p o f lo ts o f b in ary d ig its, o r b its, an d each o n e o f th ese b its tak es a lo g ic v alu e o f 0 o r 1 . No w th at we are startin g to u se th e mb ed in earn est, it is D ig it a l In p u t a n d O u t p u t 3 5 wo rth th in k in g ab o u t h o w th o se lo g ic v alu es are actu ally rep resen ted in sid e th e mb ed ’s electro n ic circu it, an d at its co n n ectio n p in s. In an y d ig ital circu it, lo g ic v alu es are rep resen ted as electrical v o ltag es. Here n o w is th e b ig b en efit o f d ig ital electro n ics: we d o n o t n eed a p recise v o ltag e to rep resen t a lo g ical v alu e. In stead , we accep t a ra n g e o f v o ltag es as rep resen tin g a lo g ic v alu e. Th is mean s th at a v o ltag e can p ick u p so me n o ise o r d isto rtio n an d still b e in terp reted as th e rig h t lo g ic v alu e. Th e m ic r o c o n tr o lle r w e a r e u s in g in th e m b e d , th e L P C 1 7 6 8 , is p o w e r e d f r o m 3 .3 V. We c a n fi n d o u t wh ich ran g e o f v o ltag es it accep ts as Lo g ic 0 , an d wh ich as Lo g ic 1 , b y lo o k in g at its te c h n ic a l d a ta . T h is is f o u n d in R e f e r e n c e 2 .4 ( C h a p te r 2 ) , w ith im p o r ta n t p o in ts s u m m a r iz e d in Ap p en d ix C. (Th ere will b e mo men ts wh en it will b e u sefu l to lo o k at th is ap p en d ix , b u t d o n o t r u s h to it n o w.) T h is d a ta s h o w s th a t, f o r m o s t d ig ita l in p u ts , th e L P C 1 6 7 8 in te r p r e ts a n y in p u t v o lta g e b e lo w 1 .0 V ( s p e c ifi e d a s 0 .3 3 .3 V ) a s L o g ic 0 , a n d a n y in p u t v o lta g e a b o v e 2 .3 V ( s p e c ifi e d a s 0 .7 3 .3 V ) a s L o g ic 1 . T h is id e a is r e p r e s e n te d in th e d ia g r a m o f F ig u r e 3 .1 . If we wan t to in p u t a sig n al to th e mb ed , h o p in g th at it is in terp reted co rrectly as a lo g ic v alu e, th e n it w ill n e e d to s a tis f y th e r e q u ir e m e n ts o f F ig u r e 3 .1 . I f w e a r e o u tp u ttin g a s ig n a l f r o m th e mb ed , th en we can ex p ect it to co mp ly with th e same fig u re. Th e mb ed will n o rmally o u tp u t L o g ic 0 a s 0 V a n d L o g ic 1 a s 3 .3 V, a s lo n g a s n o e le c tr ic a l c u r r e n t is fl o w in g . I f cu rren t is flo win g , fo r ex amp le in to an LED, th en we can ex p ect so me ch an g e in o u tp u t v o ltag e. We will retu rn to th is p o in t. Th e n eat th in g is, wh en we o u tp u t a lo g ic v alu e, we are also g ettin g a p red ictab le v o ltag e to mak e u se o f. We can u se th is to lig h t LEDs (lig h t emittin g d io d es), switch o n mo to rs, o r man y o th er th in g s. Fo r m a n y a p p lic a tio n s in th is b o o k w e d o n o t w o rry m u ch a b o u t th e s e v o lta g e s , a s th e c irc u its w e b u ild m e e t th e r e q u ir e m e n ts o f F ig u r e 3 .1 . T h e r e a r e s itu a tio n s , h o w e v e r, w h e r e it is n e c e s s a r y to ta k e s o m e c a re o v e r lo g ic v o lta g e v a lu e s , a n d th e se a re m e n tio n e d a s th ey c o m e u p . 3 .3 V (su p p ly v o ltag e) Lo g ic 1 2 .3 V Un d efin ed Lo g ic Lev el 1 .0 V Lo g ic 0 0 V F ig u r e 3 .1 : In p u t lo g ic le v e ls fo r t h e m b e d 3 6 Chapter 3 3 .3 D ig it a l O u t p u t o n t h e m b e d In o u r first two p ro g rams w e h av e ju s t switch ed th e d iag n o stic LEDs w h ich are fitted o n t h e m b e d b o a r d . T h e m b e d , h o w e v e r , h a s 2 6 d i g i t a l i n p u t / o u t p u t ( I / O ) p i n s ( p i n s 5 e3 0 ) , wh ich c an b e c o n fig u re d as e ith er d ig ita l in p u ts o r o u tp u ts . Th es e a re s h o wn in F ig u r e 3 .2 . A c o m p a r is o n o f th is fi g u r e w ith th e m a s te r m b e d p in o u t d ia g r a m , i.e . F ig u r e 2 .1 c , s h o w s th a t th e s e p in s a r e m u lti- f u n c tio n . W h ile w e c a n u s e a n y o f th e m f o r simp le d ig ita l I/O, th ey all h av e seco n d ary fu n ctio n s, co n n ectin g with th e micro co n tro ller p erip h erals. It is u p to th e p ro g ramme r to sp ecify , w ith in th e p ro g ra m, h o w th ey are co n fig u red . 3 .3 .1 U s in g L E D s D D D D D D D D D D D D D D D D ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 m b e d M ic r o c o n tr o lle r Fo r th e first time we are co n n ectin g an ex tern al d ev ice to th e mb ed . Wh ile y o u may n o t b e an e l e c t r o n i c s s p e c i a l i s t i t i s i m p o r t a n t ew h e n e v e r y o u c o n n e c t a n y t h i n g t o t h e m b e d et h a t y o u h av e so me u n d erstan d in g o f wh at y o u are d o in g . Th e LED is a semico n d u cto r d io d e, an d b eh av es electrically as o n e. It will co n d u ct cu rren t in o n e d irectio n , so metimes called th e ‘fo rward ’ d irectio n , b u t n o t th e o th er. Wh at mak es it so u sefu l is th at wh en it is co n n ected so th at it co n d u cts, it emits p h o to n s fro m its semico n d u cto r ju n ctio n . Th e LED h as th e v o ltag e/ c u r r e n t c h a r a c te r is tic s h o w n in F ig u r e 3 .3 a . A s m a ll f o r w a r d v o lta g e w ill c a u s e v e r y little cu rren t to flo w. As th e v o ltag e in creases th ere co mes a p o in t wh ere th e cu rren t su d d en ly starts flo win g rath er rap id ly . Fo r mo st LEDs th is v o ltag e is in th e ran g e sh o wn , ty p ically a r o u n d 1 .8 V. V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 3 .2 : T h e m b e d d ig it a l I/ O D D D D D D D D D D ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita ig ita l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O l I/O D ig it a l In p u t a n d O u t p u t 3 7 VS ( 3 .3 V ) I ID D I D R R VD VD VD 1 .7 to 2 .2 V (a) LED V– I ch aracteristic (b ) Gate o u tp u t so u rcin g cu rrren t to LED lo ad (c) Gate o u tp u t sin k in g cu rren t fro m LED Key ID: Cu rren t th ro u g h LED VS: Su p p ly v o ltag e V D: Vo lta g e a c r o s s L E D , f o r c u r r e n t I D F ig u r e 3 .3 : D r iv in g L E D s fr o m lo g ic g a t e s F ig u r e s 3 .3 b a n d c s h o w c ir c u its u s e d to m a k e d ir e c t c o n n e c tio n s o f L E D s to th e o u tp u t o f lo g ic g a te s , fo r e x a m p le a n m b e d p in c o n fi g u re d a s a n o u tp u t. T h e g a te is h e re s h o w n a s a lo g ic b u ff e r ( th e tr ia n g u la r s y m b o l) . I f th e c o n n e c tio n o f F ig u r e 3 .3 b is m a d e , th e L E D lig h ts w h e n th e g a te is a t lo g ic h ig h . C u r r e n t th e n fl o w s o u t o f th e g a te in to th e L E D . A lte r n a tiv e ly , th e c ir c u it o f F ig u r e 3 .3 c c a n b e m a d e ; th e L E D n o w lig h ts w h e n th e lo g ic g a te is a t lo g ic z e r o , w ith c u rre n t fl o w in g in to th e g ate . U su a lly a c u rre n t-limitin g re s is to r n e e d s to b e c o n n e c te d in s e rie s w ith th e L ED , to c o n tro l h o w m u c h c u rre n t fl o w s . T h e e x c e p tio n to th is is if th e c o m b in a tio n o f o u tp u t v o lta g e a n d g a te in te rn a l re s is ta n c e is s u c h th a t th e c u rre n t is lim ite d to a s u ita b le v a lu e a n y wa y . S o m e L ED s , s u c h a s th e o n e s re c o m m e n d e d fo r th e n ex t p ro g ram , h av e th e s e rie s re s is ta n c e b u ilt in to th e m . T h e y th e re fo re d o n o t n e e d a n y e x te rn a l re s is to r c o n n e c te d . 3 .3 .2 U s in g m b e d E x t e r n a l P in s Th e d ig ital I/O p in s are n amed an d co n fig u red to o u tp u t u sin g D ig ita lO u t, ju st as we d id in th e earlier p ro g rams, b y d efin in g th em at th e start o f th e p ro g ram co d e, fo r ex amp le: D i g i t a l O u t m y n a m e ( p 5 ) ; Th e D ig ita lO u t o b ject created in th is way can b e u sed to set th e state o f th e o u tp u t p in , an d also to read b ack its cu rren t state. We w ill b e p arts u se d ; th e co n n ec an in tern al ap eq tio se p ly in g th e c ir c u it o f F ig u r e 3 .4 a . A p p e n d ix D g iv e s u iv a le n t d e v ic e s c a n o f c o u rs e b e im p le m e n te d . With n o f F ig u r e 3 .3 b . T h e p a r tic u la r L E D r e c o m m e n d e d ries re sisto r, o f v a lu e a ro u n d 2 4 0 U , s o an ex tern a l o ex amp in th is in Ap p n e is n le cir en o t p art n u mb ers fo r a ll c u it w e a re a p p ly in g d ix D, h o wev er, h as re q u ired . Chapter 3 re d g re e n G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 m b e d M ic r o c o n tr o lle r 3 8 ( a ) C o n n e c tio n d ia g r a m ( b ) B r e a d b o a r d b u ild F ig u r e 3 .4 : m b e d s e t - u p fo r s im p le L E D fl a s h in g P la c e th e m b e d in a b r e a d b o a r d , a s s e e n in F ig u r e 3 .4 b , mb ed h as a co mmo n g ro u n d o n p in 1 . Co n n ect th is acro c o n n e c tio n s o f th e b r e a d b o a r d , a s s e e n in F ig u r e 3 .4 b . Yo similar circu its th at y o u b u ild . Rememb er to attach th e a lo n g e r le g ) to th e m b e d p in s . T h e n e g a tiv e s id e (c a th o d e ) th is a n d m a n y c irc u its w e w ill ta k e p o w e r fro m th e u n iv an d co n n ect th e circu it sh o ss to o n e o f th e o u ter ro ws u sh o u ld ad o p t th is as a h ab n o d e o f th e LEDs (th e sid e sh o u ld b e co n n ected to g ro ersal serial b u s (USB). w o it w n . Th e f fo r all ith th e u n d . Fo r C r e a te a n e w p r o g r a m in th e m b e d c o m p ile r, a n d c o p y a c r o s s P r o g r a m E x a m p le 3 .2 . / * * / # i D i D i P r o g r a m E x a m p l e 3 . 2 : n c l u d e " m b e d . h " g i t a l O u t r e d l e d ( p 5 ) ; g i t a l O u t g r e e n l e d ( p 6 ) ; i n t m w h i r g w r g w a i l e e d r e a i e d r e a i n ( ( 1 l e e n t ( l e e n t ( ) F l a s h e s r e d a n d g r e e n L E D s i n s i m p l e t i m e - b a s e d p a t t e r n / / d e f i n e a n d n a m e a d i g i t a l o u t p u t o n p i n 5 / / d e f i n e a n d n a m e a d i g i t a l o u t p u t o n p i n 6 { ) { d = 1 ; l e d = 0 ; 0 . 2 ) ; d = 0 ; l e d = 1 ; 0 . 2 ) ; } } P r o g r a m E x a m p le 3 .2 F la s h in g e x t e r n a l L E D s Co mp ile, d o wn lo ad an d ru n th e co d e o n th e mb ed . Th e co d e ex ten d s id eas alread y ap p lied in P r o g r a m E x a m p le s 2 .1 a n d 3 .1 , s o it s h o u ld b e e a s y to u n d e r s ta n d th a t th e g r e e n D ig it a l In p u t a n d O u t p u t 3 9 a n d r e d L E D s a r e p r o g r a m m e d to fl a s h a lte r n a te ly . Yo u s h o u ld s e e th is h a p p e n w h e n th e co d e ru n s. n E x e r c is e 3 .3 U s in g a n y d ig it a l o u t p u t p in , w r it e a p r s w it c h in g t h e o u t p u t r e p e a t e d ly b e t w e e a fr e q u e n c y o f 1 0 0 H z ( i.e . a p e r io d o f M e a s u r e t h e v o lt a g e v a lu e s fo r L o g ic 0 t h e s q u a r e w a v e fr e q u e n c y a g r e e w it h y o g r a m w h ic h n L o g ic 1 a n 1 0 m s ) . V ie w a n d 1 . H o w o u r p ro g ra m o u tp u ts a s q u a re d 0 . U s e w a it ( ) fu th e o u tp u t o n a n d o t h e y r e la t e t o F m e d v a lu e ? w a v e , n c t io n o s c illo ig u r e 3 b y s t o g iv e s c o p e . .1 ? D o e s n 3 .4 U s in g D ig it a l In p u t s 3 .4 .1 C o n n e c t in g S w it c h e s t o a D ig it a l S y s t e m Ord in ary electro me ch an ical switch es can b e u sed to create lo g ic lev els, wh ich will satisfy th e lo g ic le v e l r e q u ir e m e n ts s e e n in F ig u r e 3 .1 . T h r e e c o m m o n ly u s e d w a y s a r e s h o w n in F ig u re 3 .5 . T h e s im p le s t, F ig u r e 3 .5 a , u s e s a n S P D T ( s in g le - p o le , d o u b le - th ro w ) s w itc h . Th is is wh at we will u se in th e n ex t ex a mp le. A resisto r in s erie s with th e lo g ic in p u t is so metime s in clu d ed in th is circu it, as a p recau tio n ary me as u re. Ho wev er, an S PST (sin g le-p o le, sin g le -th ro w) switch can b e lo wer co s t an d sma ller, a n d so is v ery wid ely u s ed . Th ey are co n n ec te d with a p u ll-u p o r p u ll-d o w n re s is to r to th e s u p p ly v o lta g e, as s h o w n in F ig u r e 3 .5 b o r c . W h e n th e s w itc h is o p e n , th e lo g ic le v e l is d e fi n e d b y th e co n n ectio n th ro u g h th e resis to r. Wh en it is clo sed , th e s witch asserts th e o th er lo g ic state. A wa s te d electrica l cu rre n t th en flo ws th ro u g h th e re s is to r. Th is is k e p t s ma ll b y h av in g a h ig h -v alu e resisto r. On th e mb ed , a s with ma n y micro co n tro llers, p u ll-u p an d p u ll-d o wn resisto rs are av ailab le with in th e micro co n tro ller, sav in g th e n eed to mak e th e ex tern al co n n ectio n . V V S V S S R V i V i V i R ( a ) s in g le - p o le , d o u b le - th r o w ( S P D T ) c o n n e c tio n ( b ) s in g le - p o le , s in g le - th r o w ( S P S T ) w ith p u ll- u p r e s is to r F ig u r e 3 .5 : C o n n e c t in g s w it c h e s t o lo g ic in p u t s ( c ) S P S T w ith p u ll- d o w n r e s is to r 4 0 Chapter 3 T a b le 3 .3 : T h e m b e d d ig it a l in p u t A P I s u m m a r y ( f r o m w w w .m b e d .o r g ) F u n c t io n U s a g e D i g i t a l I n C r e a t e a D ig it a lIn c o n n e c t e d t o t h e s p e c ifi e d p in r e a d R e a d t h e in p u t , r e p r e s e n t e d a s 0 o r 1 ( in t ) m o d e S e t t h e in p u t p in m o d e o p e r a t o r i n t ( ) A n o p e ra to r s h o rth a n d fo r re a d () 3 .4 .2 T h e D ig it a lIn A P I T h e m b e d A P I h a s th e d ig ita l in p u t f u n c tio n s lis te d in Ta b le 3 .3 , w ith f o r m a t id e n tic a l to th a t o f D ig ita lO u t, w h ich w e h av e a lre a d y s e e n . T h is s e c tio n o f th e A PI c re a te s a c la s s c a lle d D ig ita lI n , w ith th e m e mb e r fu n c tio n s s h o w n . T h e D ig ita lI n c o n s tru c to r c a n b e u s e d to c re a te d ig ita l in p u ts , a n d th e r e a d ( ) fu n c tio n u s e d to re a d th e lo g ic a l v a lu e o f th e in p u t. In p ra c tic e , th e s h o rth a n d o ffe re d a llo w s u s to re a d in p u t v a lu e s th ro u g h u s e o f th e d ig ita l o b jec t n a m e . T h is w ill b e s e e n in th e p ro g ra m e x a m p le th a t fo llo w s . A s w ith d ig ita l o u tp u ts , th e s a m e 2 6 p in s ( p i n s 5 e3 0 ) c a n b e c o n fi g u r e d a s d i g i t a l i n p u t s . I n p u t v o l t a g e s w i l l b e i n t e r p r e t e d a c c o r d i n g t o F ig u r e 3 .1 . N o te th a t u s e o f D ig it a lI n e n a b le s b y d e f a u lt th e in te r n a l p u ll- d o w n r e s is to r, i.e . th e in p u t c ir c u it is c o n fi g u r e d a s F ig u r e 3 .5 c . T h is c a n b e d is a b le d , o r a n in te r n a l p u ll- u p e n a b le d , u s in g th e m o d e ( ) fu n c tio n . S e e th e m b e d H an d b o o k fo r d eta ils o n th is. 3 .4 .3 U s in g if t o R e s p o n d t o a S w it c h In p u t We will n o w co n n ect to o u r circu it a d so d o in g , we mak e a sig n ifican t step mak es a d ecisio n b ased o n an ex tern man y emb ed d ed sy stems. Pro g ram E co n n ected to p in 7 , an d created with C c o d e fe a tu re ig fo al x a th ital in p u t, a rward . Fo r v ariab le, th m p le 3 .3 is e D ig ita lI n switch , an d u se it to co n tro l LED states. th e first time we will h av e a p ro g ram th e switch p o sitio n . Th is is th e essen ce o ap p lied to ach iev e th is; th e d ig ital in p u t co n stru cto r. In at f is To mak e th e d ecisio n with in th e p ro g ram, we u se th e statemen t i f ( s w i t c h i n p u t = = 1 ) . Th is lin e sees u se o f th e u se o f th e if an d e ls e k e ex ecu te, if th e sp ecified s w itc h in p u t is eq u al to ex ecu ted . Lo o k in g n o w th e g reen LED is switch 0 , th e e ls e co d e b lo ck is statemen t is u sed to cre C e q u a l o p e r a to r, ¼ ¼ , f o r th e fi r s t tim e . R e a d S e c tio n B .6 .1 to r e v ie w y wo rd s. Th e lin e cau ses th e lin e o r b lo ck o f co d e wh ich fo llo ws it to co n d itio n is met. In th is case, th e co n d itio n is th at th e v ariab le 1 . If th e co n d itio n is n o t satisfied , th en th e co d e th at fo llo ws e ls e is a t th e p ro g ra m w e c a n s e e th a t if th e s w itc h g iv e s a v a lu e o f L o g ic 1 , ed o ff an d th e red LED is p ro g rammed to flash . If th e switch in p u t is in v o k ed an d th e ro les o f th e LEDs are rev ersed . Ag ain , th e w h ile (1 ) a te a n o v era ll in fi n ite lo o p , s o th e L E D s fl a s h c o n tin u o u s ly . D ig it a l In p u t a n d O u t p u t / * * / # i D i D i D i i n P r o g r a m n c l g i t g i t g i t t m w h i l i / u d e a l O a l O a l I a i n e ( 1 f ( / e x E x a m p l e " m b u t r u t g n s w ( ) { ) { s w i t e c u t g r e e r e d l w a i t r e d l w a i t 3 . 3 : e d e d r e i t . h l e e n c h " c h e n l e d ( 0 e d ( 0 i n f o e d = . 2 = . 2 p u l l = 1 ) ; 0 ) ; F l a s h e s s e e d r e a i r e a i t = = 1 ) o w i n g 0 ; { = ; = 1 ; . 2 ) ; e d = . 2 ) ; 0 ; L E D s , d e p e n d i n g o n t h e s t a t e o f a 2 - w a y s w i t c h ; / / e / / h / / r / / 0 ; e d t w o / / t e s t v a l u e o f s w i t c h i n p u t b l o c k i f s w i t c h i n p u t i s 1 / / g r e e n l e d i s o f f / / f l a s h r e d l e d { l e d e n l t ( 0 e n l t ( 0 o f d ( p 5 ) ; l e d ( p 6 ) ; i n p u t ( p 7 ) ; } e l r g w g w o n e 4 1 } n d o e r e e d l f l a s / / e n d / / e n d / / e n d } } f i f i f s w i t c h i n p u t e d i s o f f h g r e e n l e d o f o f o f i s 0 e l s e w h i l e ( 1 ) m a i n P r o g r a m E x a m p le 3 .3 U s in g if a n d e ls e t o r e s p o n d t o e x t e r n a l s w it c h Ad ju st th e circu it o f Fig Th e in p u t it co n n ects to F ig u r e 3 .6 b s h o w s th e a switch an d co n n ected to d irectly . Create a n ew p an d ru n th e co d e o n th e n u r e 3 .4 to is co n fig u d d itio n o f th e b read ro g ram an mb ed . th at o f red in th e sw b o ard . d co p y Fig u th e p itch . It is acro r e 3 .6 a , b y a d d in g a n S P D T s w ro g ram as a d ig ital in p u t. Th e p In th is case, wires h av e b een so also p o ssib le to fin d switch es th s s P r o g r a m E x a m p le 3 .3 . C o m p itch as sh o wn . h o to g rap h in ld ered to th e at p lu g in ile, d o wn lo ad E x e r c is e 3 .4 W r it e a p r o g r a m t h a t c r e a t e s a s q u a r e w a v e o u t p u t , a s in E x e r c is e 3 .3 . In c lu d e n o w t w o p o s s ib le fr e q u e n c ie s , 1 0 0 H z a n d 2 0 0 H z , d e p e n d in g o n a n in p u t s w it c h p o s it io n . U s e t h e s a m e s w it c h c o n n e c t io n y o u h a v e ju s t u s e d . O b s e r v e t h e o u t p u t o n a n o s c illo s c o p e . n n E x e r c is e 3 .5 T h e c H o w e o n -c h s a m e ir c v e ip to u it o f r, th e p u ll- d g g le s F ig u r e 3 m b e d H o w n re s w it c h o r .6 u a n d is t o a n s e s a n S P D T b o o k t e lls u s r. R e c o n fi g u r S P S T p u s h b s w it c h c th a t th e e t h e c ir c u tto n . T e o n n D ig u it s t t e c te d it a lIn u s in g h a t th a s s h u t ilit F ig u r e p ro o w n in y a c tu a e 3 .5 c , g ra m r F ig u r e lly c o n fi u s in g e u n s c o r 3 .5 a . g u re s a n it h e r t h e r e c t ly . n Chapter 3 G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 m b e d M ic r o c o n tr o lle r 4 2 V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 ( a ) C o n n e c tio n d ia g r a m ( b ) B r e a d b o a r d b u ild F ig u r e 3 .6 : C o n t r o llin g t h e L E D w it h a s w it c h 3 .5 In t e r fa c in g S im p le O p t o D e v ic e s No w th at we h av e p o ssib ilities o p en s Oth ers h av e th eir o lo o k s at so me simp th e mb ed . In later d ev ices. 3 .5 .1 th e ab ility to in p u t an d o u tp u t sin g le b its o f d ata , a wid e ran g e o f u p . Man y simp le sen so rs can in terface d irectly with d ig ital in p u ts. wn d esig n ed -in in terfaces, wh ic h p ro d u ce a d ig ital o u tp u t. Th is sectio n le an d trad itio n al sen so rs an d d isp lay s th at can b e in terfaced d irectly to ch ap ters th is is tak en fu rth er, co n n ectin g to so me v ery n ew an d h i-tech O p t o R e fl e c t iv e a n d T r a n s m is s iv e S e n s o r s O p to - s e n s o r s , s u c h a s s e e n in F ig u r e 3 .7 a a n d b , a r e s im p le e x a m p le s o f s e n s o r s w ith ‘ a lm o s t’ d ig ita l o u tp u ts . W h e n a lig h t falls o n th e b a s e o f a n o p to -tra n s is to r, it c o n d u c ts ; w h e n th e re is n o lig h t it d o e s n o t. I n th e r e fl e c tiv e s e n s o r ( F ig u r e 3 .7 a ) , a n in f r a r e d L E D is m o u n te d in th e s a m e p a c k a g e a s a n o p to - tr a n s is to r. W h e n a r e fl e c tiv e s u r fa c e is p la c e d in fr o n t, th e lig h t b o u n c e s b a c k , a n d th e tr a n s is to r c a n c o n d u c t. I n th e tr a n s m is s iv e s e n s o r ( F ig u r e 3 .7 b ) , th e L E D is m o u n te d o p p o s ite th e tra n sisto r. With n o th in g in th e w ay , lig h t fro m th e L ED falls d ire ctly o n th e tra n s is to r, a n d s o it c a n c o n d u ct. W h en s o m e th in g c o m e s in th e w a y th e lig h t is b lo c k e d , a n d th e tra n s is to r s to p s c o n d u ctin g . T h is s e n s o r is a ls o s o me tim e s c a lle d a s lo tte d o p to -s e n s o r o r p h o to -in te rru p te r. E a c h s e n s o r c a n b e u s e d to d ete c t c e rta in ty p es o f o b je c t. D ig it a l In p u t a n d O u t p u t 4 3 R E F L E C T IV E S U R F A C E O p a q u e O b je c t P a th o f R e fle c te d L ig h t B o d y o f S e n so r a n o d e c a th o d e c o lle c to r B o d y o f S e n so r P a th o f T ra n s m itte d L ig h t e m itte r ( a ) R e fle c tiv e o p to - s e n s o r ( b ) T r a n s m is s iv e o p to - s e n s o r VS R1 R2 VC ( c ) S im p le d r iv e c ir c u it fo r o p to - s e n s o r F ig u r e 3 .7 : S im p le o p t o - s e n s o r s E ith e r o f th e s e n s o r s s h o w n c a n b e c o n n e c te d in th e c ir c u it o f F ig u r e 3 .7 c . H e r e , R 1 is calcu lated to co n tro l th e cu rren t flo win g in th e LED, tak in g su itab le v alu es fro m th e sen so r d atash ee t. Th e resisto r R 2 is ch o sen to allo w a su itab le o u tp u t v o ltag e swin g , in v o k in g th e v o lta g e th r e s h o ld s in d ic a te d in F ig u r e 3 .1 . W h e n lig h t f a lls o n th e tr a n s is to r b a s e , cu rren t can flo w th ro u g h th e tran sisto r. T h e v alu e o f R2 is ch o sen so th at with th at cu rren t fl o w in g , th e tr a n s is to r c o lle c to r v o lta g e V C f a lls a lm o s t to 0 V. I f n o c u r r e n t fl o w s , th e n V C ris e s to V S . In g e n e ra l, th e s e n s o r is m a d e m o re s e n s itiv e b y e ith e r d e c re a s in g R 1 o r in creasin g R2 . 3 .5 .2 C o n n e c t in g a n O p t o -S e n s o r t o t h e m b e d F ig u re 3 .8 s h o w s h o w a tr a n s m is s iv e o p to - s e n s o r c a n b e c o n n e c te d to a n m b e d . T h e d ev ice u sed is a KTIR0 6 2 1 DS, mad e b y Kin g b rig h t; similar d ev ices can b e u sed . Th e p articu lar sen so r u se d h as p in s th at can p lu g d irectly in to th e b read b o ard . Tak e care Chapter 3 G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 1 0 k 2 2 0 R K T IR V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 m b e d M ic r o c o n tr o lle r 4 4 ( a ) C o n n e c tio n d ia g r a m ( b ) B r e a d b o a r d b u ild F ig u r e 3 .8 : m b e d c o n n e c t e d t o a t r a n s m is s iv e o p t o - s e n s o r w h e n c o n n e c tin g th e s e fo u r p in s . C o n n e c tio n s a re in d ic a te d o n its h o u s in g ; a lte rn a tiv e ly , y o u can lo o k th ese u p in th e d ata th at K in g b rig h t p ro v id es. Th is can b e o b tain ed fro m th e K in g b r ig h t w e b s ite , R e f e r e n c e 3 .2 , o r f r o m th e s u p p lie r y o u u s e to b u y th e s e n s o r. P r o g r a m E x a m p le 3 .4 c o n tr o ls th is c ir c u it. T h e o u tp u t o f th e s e n s o r is c o n n e c te d to p in 1 2 , wh ich is co n fig u red in th e p ro g ram as a d ig ital in p u t. Wh en th ere is n o o b ject in th e sen so r, th en lig h t falls o n th e p h o to -tran sisto r. It co n d u cts, an d th e sen so r o u tp u t is at Lo g ic 0 . Wh en th e b eam is in terru p ted , th en th e o u tp u t is at Lo g ic 1 . Th e p ro g ram th erefo re switch es th e LED o n w h e n th e b e a m is in te r r u p te d , i.e . a n o b je c t h a s b e e n s e n s e d . To m a k e th e s e le c tio n , w e u s e th e if an d e ls e k ey wo rd s, as in th e p rev io u s ex amp le. No w, h o wev er, th ere is ju st o n e lin e o f co d e to b e ex ecu ted fo r eith er state. It is n o t n ecessary to u se b races to co n tain th ese sin g le lin es. / * P r o g r a m a c c o r d i n g * / E x a m p l e 3 . 4 : S i m p l e t o s t a t e o f s e n s o r p r o g r a m t o t e s t K T I R s l o t t e d o p t o s e n s o r . # i n c l u d e " m b e d . h " D i g i t a l O u t r e d l e d ( p 5 ) ; D i g i t a l I n o p t o _ s w i t c h ( p 1 2 ) ; i n t m a i n ( w h i l e ( 1 i f ( r ) { ) { o p t o _ s w i t c h = = 1 ) e d l e d = 1 ; e l s e r e d l e d } = 0 ; / / i n p u t = 1 i f b e a m i n t e r r u p t e d / / s w i t c h l e d o n i f b e a m i n t e r r u p t e d / / l e d o f f i f n o i n t e r r u p t i o n / / e n d o f w h i l e } P r o g r a m E x a m p le 3 .4 A p p ly in g t h e p h o t o - in t e r r u p t e r S w i t c h e s a n L E D D ig it a l In p u t a n d O u t p u t 3 .5 .3 S e v e n -S e g m e n t D is p la y s We h av to g eth e co n fig u matrix e n o r, to ratio an d 4 5 w u sed sin g le LEDs in sev eral p ro g rams. In ad d itio n , LEDs are o ften p ack ag ed fo rm p attern s, d ig its o r o th er ty p es o f d isp lay . A n u mb er o f stan d ard n s are v ery wid ely u sed ; th ese in clu d e b ar g rap h , sev en -seg men t d isp lay , d o t ‘star-b u rst’. Th e sev en -seg men t d isp lay is a p articu larly v ersatile co n fig u ratio n . An ex amp le sin g le d ig it, m a d e b y K in g b r ig h t ( R e f e r e n c e 3 .2 ) , is s h o w n in F ig u r e 3 .9 . B y lig h tin g d iff e r e n t co mb in atio n s o f th e sev en seg men ts, all n u merical d ig its can b e d isp lay ed , as well as a su rp risin g n u mb er o f alp h ab etic ch aracters. A d ecimal p o in t is u su ally in clu d ed , as sh o wn . Th is mean s th at th ere are eig h t LEDs in th e d isp lay , n eed in g 1 6 co n n ectio n s. To simp lify matters, eith er all LED an o d es are co n n ected to g eth er, o r all LED cath o d es. Th is is seen in F ig u r e 3 .9 b ; th e tw o p o s s ib le c o n n e c tio n p a tte r n s a r e c a lle d c o m m o n c a th o d e o r c o m m o n a n o d e. No w in stead o f 1 6 co n n ectio n s b ein g n eed ed , th ere are o n ly n in e, o n e fo r each LED an d o n e fo r th e co mmo n co n n ectio n . Th e actu al p in co n n ectio n s in th e ex amp le sh o wn lie in two ro ws, at th e to p an d b o tto m o f th e d ig it. Th ere are 1 0 p in s in all, with th e co mmo n an o d e o r cath o d e tak in g two p in s. F ig u r e 3 .9 : T h e s e v e n - s e g m e n t d is p la y . ( Im a g e r e p r o d u c e d w it h p e r m is s io n o f K in g b r ig h t E le c . C o . L t d .) 4 6 Chapter 3 A s m a ll s e v e n - s e g m e n t d is p la y a s s e e n in F ig u r e 3 .9 c a n b e d r iv e n d ir e c tly f r o m a micro co n tro ller. In th e case o f co mmo n cath o d e, th e cath o d e is co n n ected to g ro u n d , an d each seg men t is co n n ected to a p o rt p in . If th e seg men ts are co n n ected in th is seq u en ce to fo rm a b y te, ðMSBÞ DP g f e d c b a ðLSBÞ th e n th e v a lu e s s h o w n in Ta b le 3 .4 a p p ly . F o r e x a m p s e g m e n ts , i.e . a b c d e f , m u s t b e lit, w ith th e c o rr e s p o n d is to b e d isp la y e d , th en o n ly s eg me n ts b a n d c n ee d to L E D s c o n n e cte d in s e rie s , fo r e a c h s eg me n t. In th is e ac h s eries c o m b in atio n a n d , d ep en d in g o n th e s u p p n o t b e p o s s ib le to d riv e th e d is p la y d ir e c tly . 3 .5 .4 le , if 0 is to b e d in g b its fro m th e b e lit. N o te th at c a s e, a h ig h e r v o ly v o lta g e o f th e is p lay ed , th e n a ll o u te r m ic ro c o n tro lle r s e t to 1 . If 1 larg er d is p lay s h av e s ev e ral lta g e is n e e d e d to d riv e micro c o n tro lle r, it ma y C o n n e c t in g a S e v e n -s e g m e n t D is p la y t o t h e m b e d A s w e k n o w, th e m b e d r u n s f r o m a 3 .3 V s u p p ly . T h e d a ta s h e e t o f o u r d is p la y ( a c c e s s e d f r o m R e f e r e n c e 3 .2 ) , s h o w s th a t e a c h L E D r e q u ir e s a r o u n d 1 .8 V a c r o s s it in o r d e r to lig h t. Th is is with in th e mb ed cap ab ility . If th ere were two LEDs in series in each seg men t h o wev er, th e mb ed wo u ld b arely b e ab le to switch th em in to co n d u ctio n . Bu t can we ju st co n n ect th e mb ed o u tp u t d irectly to th e seg men t, o r d o we n eed a cu rren t-limitin g resisto r, a s s e e n in F ig u r e 3 .3 b ? L o o k in g a t th e L P C 1 7 6 8 d a ta s u m m a r iz e d in A p p e n d ix C , w e s e e th a t th e o u tp u t v o lta g e o f a p o r t p in d r o p s a r o u n d 0 .4 V, w h e n 4 m A is fl o w in g . T h is imp lies an o u tp u t resistan ce o f 1 0 0 U . Let’s n o t g et in to th e electro n ics o f all o f th is; su ffice it to say , th is v alu e is ap p ro x imate, an d o n ly ap p lies in th is reg io n o f o p eratio n . Ap p ly in g Oh m’s law, th e cu rren t flo w in an LED co n n ected d irectly to a p o rt p in o f th is ty p e is g iv e n b y I D y ð 3 :3 1 :8 Þ =1 0 0 ¼ 1 5 mA ( 3 .1 ) T a b le 3 .4 : E x a m p le s e v e n - s e g m e n t d is p la y c o n t r o l v a lu e s D is p la y v a lu e 0 1 2 3 4 5 6 7 8 9 S e g m e n t d r iv e ( B ) (M S B ) 0 0 1 1 (L S B ) 1 1 1 1 0 0 0 0 0 1 1 0 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 0 1 1 0 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 0 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 B (h e x) 0 x0 6 0 x5 B 0 x4 F 0 x6 6 0 x6 D 0 x7 D 0 x0 7 0 x7 F 0 x6 F A c t u a l d is p la y 0 x3 F D ig it a l In p u t a n d O u t p u t 4 7 Th is cu rren t, 1 5 mA, will lig h t th e seg men ts v ery b rig h tly , b u t is accep tab le. It can b e red u ced , fo r ex amp le fo r p o wer-co n scio u s ap p licatio n s, b y in sertin g a resisto r in series with each seg men t. C o n n e c t a s e v e n - s e g m e n t d is p la y to a n m b e d , u s in g th e c ir c u it o f F ig u r e 3 .1 0 . I n th is s im p le ap p licatio n th e co mmo n cath o d e is co n n ected d irect to g ro u n d , an d each seg men t is co n n ected to o n e mb ed o u tp u t. W to In it is in cremen C c o d e fe a tu re b e d riv e n b y P ro g ra m E x a m p le O u t allo ws y o u to g ro u p a s et o w o rd d ire c t to it. T h e e q u iv a le n ly in g B u s O u t simp ly req u ires y ck e ts th e p in s wh ic h will b e m ith in th w h ile , th is ex ted b y is p ro g fo r cre amp le, 1 . Th e to 7 -s e g m e n t d is p la y ram we see atin g a co n d th e v ariab le n ew v alu e o p in p in p in p in p in p in p in 1 p in 5 p in s 3 7 , s e 6 , s e 4 , s e 2 , s e 1 , s e 9 , s e 0 , s e , s e g ,8 g . a g . b g . c g . d g . e g . f g . g . d p fo r itio i is f i 3 .5 . T h f d ig ita t in p u t o u to sp emb ers th e first n al lo o p in itially is ap p lie G V V n 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 2 is first o f l o u tp u ts is th e B u ecify a n o f th at b time a fo . Rev iew set to 0 , d with in n d in b R 0 1 2 3 4 5 6 7 0 9 8 all ap p lies th e B u s O in to o n e b u s, so th at s in o b ject, th o u g h th ame, in th is case d is p u s. r lo o its fo an d o th e lo m b e d M ic r o c o n tr o lle r Th e circu it can API class. B u s write a d ig ital u sed h ere. Ap p th en list in b ra p . Th is rmat in n each o p . Wh is an a Sectio iteratio en i re V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 3 .1 0 : T h e m b e d c o n n e c t e d t o a c o m m o n c a t h o d e s e v e n - s e g m e n t d is p la y u t y o at la m u is y , b ed can n o t an d lte rn a tiv e n B .7 .2 . n o f th e lo o p ach es 4 , th e 4 8 Chapter 3 lo o p termin ates. Ho wev er, as th e fo r lo o p is th e o n ly co d e with in th e en d less w h ile lo o p , it simp ly starts ag ain . Th e p ro g ram g o es o n to ap p ly th e s w itc h , c a s e an d b r e a k k ey wo rd s. Use th ese wo rd s p ro v id e a mech an ism to allo w o n e item to b e ch o sen fro m d e s c r ib e d in S e c tio n B .6 .2 . I n th is c a s e , a s th e v a r ia b le i is in c r e m e n te d , u sed to select th e wo rd th at mu st b e sen t to th e d isp lay , in o rd er fo r th e req u ired d illu min ate. Th is meth o d o f ch o o sin g o n e v alu e fro m a list is o n e way o f ach iev in g ta b le, wh ich is an imp o rtan t p ro g rammin g tech n iq u e. C c o d e fe a tu re Th ere are n o w q u ite a few n ested b lo ck s o f co d e in th is ex with in th e fo r b lo ck wh ich lies in s id e th e w h ile b lo c k , wh b lo ck . Th e clo sin g b race fo r eac h is co mme n ted in th e p ro g co mp lex C p ro g rams it b eco mes v ery imp o rtan t to en su re a c lo sin g b ra c e, a t th e rig h t p la ce . / * P r o g r a m E x a m p l e 2 , 3 i n t u r n . * / 3 . 5 : S i m p l e d e m o n s t r a t i o n # i n c l u d e " m b e d . h " B u s O u t d i s p l a y ( p 5 , p 6 , p 7 , p 8 , p 9 , p 1 0 , p 1 1 , p 1 2 ) ; i n t m a i w h i l e f o r s n ( ( 1 ( i w i ) o f / / 7 - s e g m e n t s e g m e n t s d to g eth er, a list, as its v alu e is ig it to a lo o k-u p a mp le . Th e s w itc h b lo ck lie s ich fin ally lies with in th e m a in ram lis tin g . Wh en writin g mo re th at each b lo ck is en d ed with d i s p l a y . D i s p l a y d i g i t s 0 , 1 , a , b , c , d , e , f , g , d p { ) n t t c c c c c { a a a a h i = 0 ( i s e s e s e s e ; i < 4 ; ) { 0 : 1 : 2 : 3 : } d i s d i s d i s d i s i + + ) p l a p l a p l a p l a y = y = y = y = { 0 x 3 0 x 0 0 x 5 0 x 4 F ; 6 ; B ; F ; b r e b r e b r e b r e a k ; a k ; a k ; a k ; / / d i s p l a y / / d i s p l a y / / e n d 0 1 o f s w i t c h w a i t ( 0 . 2 ) ; } / / e n d / / e n d / / e n d } } o f o f o f f o r w h i l e m a i n P r o g r a m E x a m p le 3 .5 U s in g f o r t o s e q u e n c e v a lu e s t o a s e v e n - s e g m e n t d is p la y C o m p ile , d o w n lo a d a n d r u n th e p r o g r a m . T h e d is p la y s h o u ld a p p e a r s im ila r to F ig u r e 3 .1 1 . No tice carefu lly , h o wev er, b y lo o k in g at wh ere p in 8 is co n n ected , th at th is is a c o m m o n a n o d e c o n n e c tio n . I t d o e s n o t e x a c tly r e p lic a te F ig u r e 3 .1 0 . P in 3 h a s b e e n left u n co n n ected . n E x e r c is e 3 .6 W r it e a p r o g r a m w h ic h fl a s h e s t h e le t t e r s H E L P in t u r n o n a s e v e n - s e g m e n t d is p la y , u s in g t h e c ir c u it o f F ig u r e 3 .1 0 . n D ig it a l In p u t a n d O u t p u t 4 9 F ig u r e 3 .1 1 : m b e d c o n n e c t e d t o a c o m m o n a n o d e s e v e n - s e g m e n t d is p la y 3 .6 3 .6 .1 S w it c h in g L a r g e r D C L o a d s A p p ly in g T r a n s is t o r S w it c h in g T h e m b e d c a n d riv e s im p le D C lo a d s d ire c tly w ith its d ig ita l I/O p in s , a s w e s a w w ith th e LEDs. Th e mb ed su mmary d ata (rep eated in Ap p en d ix C) tells u s th at a p o rt p in can so u rce u p to aro u n d 4 0 mA. Ho wev er, th is is a sh o rt circu it cu rren t, so we are u n lik ely to b e ab le to b en efit fro m it with an actu al electrical lo ad co n n ected to th e p o rt. I f it is n e c e s s a r y to d r iv e a lo a d es a y a m o to r ew h ic h n e e d s m o r e c u r r e n t th a n a n m b e d p o r t p in can su p p ly , o r wh ich n eed s to ru n fro m a h ig h er v o ltag e, th en an in terface circu it will b e n e e d e d . T h r e e p o s s ib ilitie s , w h ic h a llo w D C lo a d s to b e s w itc h e d , a r e s h o w n in F ig u r e 3 .1 2 . E a c h h a s a n in p u t la b e le d V L, w h ic h is th e lo g ic v o lta g e s u p p lie d fro m th e p o rt p in . T h e fi rs t tw o c irc u its s h o w h o w a re s is tiv e lo a d , s u c h a s a m o to r o r h e a te r, c a n b e s w itc h e d , u s in g a b ip o lar tran sisto r an d a metal o x id e semico n d u cto r field effect tran sisto r (MOSFET e a m o u th fu l, b u t a n im p o rta n t d ev ic e in to d a y ’s e le c tro n ic s ), re s p e c tiv e ly . In th e c a s e o f th e b ip o la r tra n s is to r, th e s im p le fo rm u la e s h o w n c a n b e a p p lie d to c a lc u la te R B, s ta rtin g w ith k n o wled g e o f th e req u ired lo ad cu rren t an d th e v alu e o f th e cu rren t g ain (b ) o f th e tran sisto r. In th e case o f th e MOSFET, th ere is a th resh o ld g ate-to -so u rce v o ltag e, ab o v e wh ich th e tran sisto r switch es o n . Th is is a p articu larly u sefu l co n fig u ratio n , as th e MOSFET g ate can b e re a d ily d riv e n b y a m ic ro c o n tro lle r p o rt b it o u tp u t. 5 0 Chapter 3 V V S R R L S L I L R V L G a te I L B V b L I B G a te I B > I L b R B < - 0 .6 V L V L S o u rc e > V GS (th ) I B ( a ) r e s is tiv e lo a d , n p n tr a n s is to r ( b ) r e s is tiv e lo a d , n - c h a n n e l M O S F E T V 'f r e e w h e e l i n g ' d i o d e S L , w ith re s is ta n c e R d e c a y in g c u rre n t flo w s in th is p a th , w h e n tra n s is to r s w itc h e d o ff. IL V L ( c ) In d u c tiv e L o a d , n - c h a n n e l M O S F E T F ig u r e 3 .1 2 : T r a n s is t o r s w it c h in g o f D C lo a d s F ig u r e 3 .1 2 c s h o w s a n in d u c tiv e lo a d , s u c h a s a s o imp o rtan t a d d itio n h e re is th e freewh eelin g d io d e. with cu rren t flo win g in it s to re s en erg y in th e mag cu rren t is in terru p te d , in th is ca se b y th e tra n sisto r retu rn e d to th e c ircu it. Th is h a p p e n s th ro u g h th e d co n tin u e to circu late . If th e d io d e is n o t in clu d e d th can /will d e stro y th e fie ld effe ct tran s isto r. 3 .6 .2 len o id o r DC mo to r, b ein Th is is n eed ed b ec au s e a n etic field th at su rro u n d s b e in g switch e d o ff, th e e io d e , wh ich allo ws d ec ay en a h ig h -v o ltag e tran sien g switch e d . n y in d u ctan it. Wh en th n erg y h as to in g cu rren t t o ccu rs, wh S w it c h in g a M o t o r w it h t h e m b e d A g o o d switch in g tran sisto r fo r small DC lo ad s is th e ZVN4 2 0 6 A, wh o se main c h a r a c te r is tic s a r e lis te d in Ta b le 3 .5 . A n im p o r ta n t v a lu e is th e m a x im u m V GS th r e s h o ld An ce at b e to ich D ig it a l In p u t a n d O u t p u t 5 1 T a b le 3 .5 : C h a r a c t e r is t ic s o f t h e Z V N 4 2 0 6 A n - c h a n n e l M O S F E T C h a r a c t e r is t ic Z V N 4 2 0 6 A M a x im u m d r a in - s o u r c e v o lt a g e V 6 0 V D S M a x im u m g a t e - s o u r c e t h r e s h o ld V 3 V G S (th ) M a x im u m d r a in - s o u r c e r e s is t a n c e w h e n ‘O n ’. R 1 .5 U D S (o n ) M a x im u m c o n t in u o u s d r a in c u r r e n t ID 6 0 0 m A M a x im u m p o w e r d is s ip a t io n 0 .7 W In p u t c a p a c it a n c e 1 0 0 p F v a lu e , s h o w n a s 3 V. T h is m e a n s th a t th e M O S F E T w ill r e s p o n d , ju s t, to th e 3 .3 V L o g ic 1 o u tp u t lev el o f th e mb ed . n E x e r c is e 3 .7 C o n n e c t t h e c ir c u it o f F ig u r e 3 .1 3 , u s in g c a n b e s u p p lie d fr o m a n e x t e r n a l b a t t e r y p n o n - c r it ic a l, a n d d e p e n d s o n t h e m o t o r y m o t o r s w it c h e s o n a n d o ff c o n t in u o u s ly , t h e s w it c h in g u n t il y o u c a n n o lo n g e r d e t th e m o to r s p e e d c o m p a re to w h e n th e m 3 .6 .3 a s m a ll D C m o t o r . T h e 6 V fo r t h e m o t o r a c k o r b e n c h p o w e r s u p p ly . It s e x a c t v o lt a g e is o u a r e u s in g . W r it e a p r o g r a m s o t h a t t h e s a y 1 s o n , 1 s o ff. In c re a s e th e fre q u e n c y o f e c t t h a t it is s w it c h in g o n a n d o ff. H o w d o e s o t o r w a s ju s t le ft s w it c h e d o n ? n S w it c h in g M u lt ip le S e v e n -S e g m e n t D is p la y s 6 V M o to r IN 4 0 0 1 Z V N 4 2 0 6 A G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 m b e d M ic r o c o n tr o lle r We saw earlier in th e ch ap ter h o w a sin g le sev en -seg men t d isp lay co u ld b e co n n ected to th e mb e d . Ea ch d is p la y req u ire d e ig h t c o n n e ctio n s , a n d if we wan te d ma n y d is p lay s , th e n w e F ig u r e 3 .1 3 : S w it c h in g a D C m o t o r V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 + 6 V 5 2 Chapter 3 wo u ld q u ick ly ru n o u t o f I/O p in s . Th ere is a v ery u s efu l tech n iq u e to g e t aro u n d th is p ro b le m , s h o w n in F ig u r e 3 .1 4 . E a c h s e g m e n t ty p e o n e a c h d is p la y is w ir e d to g e th e r, a s s h o wn , an d co n n ec te d b a ck to a micro c o n tro ller p in co n fig u red as d ig ital o u tp u t. Th e c o m m o n c a th o d e o f e a c h d ig it is th e n c o n n e c te d to its o w n d riv e M O S F E T. T h e tim in g d ia g ra m s h o w n th e n a p p lie s . T h e s e g m e n t d riv e s a re c o n fi g u re d fo r D ig it 1 , a n d th a t d ig it’s d riv e tra n s is to r is a c tiv a te d , illu m in a tin g th e d ig it. A m o m e n t la te r th e s e g m e n t d riv e s a re c o n fi g u re d fo r D ig it 2 , a n d th a t d ig it’s d riv e tra n s is to r is a c tiv a te d . T h is c o n tin u e s e n d le s s ly w ith e a c h d ig it in tu rn . If it is d o n e ra p id ly e n o u g h , th e n th e h u m a n e y e p e rc e iv e s a ll d ig its a s b e in g co n tin u o u s ly illu min a te d ; a u s e fu l ra te is fo r ea c h d ig it to b e illu min a te d in tu rn fo r aro u n d 5 ms. g f a /c a b a /c c d p g f a /c a b a /c c d p g f a /c a b g a /c c d p f a /c a b a /c c d p S e g m e n t D riv e s e d e d e d e d D ig it 1 D ig it 2 D ig it 3 D ig it 4 Z V N 4 2 0 6 A Z V N 4 2 0 6 A Z V N 4 2 0 6 A Z V N 4 2 0 6 A D ig it D riv e s ( a ) D is p la y c o n n e c tio n s s e g m e n t p a tte rn fo r D ig it 1 s e g m e n t p a tte rn fo r D ig it 4 s e g m e n t p a tte rn fo r D ig it 3 s e g m e n t p a tte rn fo r D ig it 2 S e g m e n t D riv e s D ig it 1 D ig it D riv e s D ig it 2 D ig it 3 D ig it 4 ( b ) T im in g d ia g r a m F ig u r e 3 .1 4 : M u lt ip le x in g s e v e n - s e g m e n t d is p la y s s e g m e n t p a tte rn fo r D ig it 4 D ig it a l In p u t a n d O u t p u t 3 .7 U a th ‘h 5 3 M in i-P r o je c t : L e t t e r C o u n t e r se th e slo tted simp le letter e sen so r. Cle alf ’ d ig it, so o p to co u n ar th y o u -sen so r, p u sh -b u tto n ter. In cremen t th e n u e d isp lay wh en th e p can co u n t fro m 0 to sw mb u sh 1 9 itch an d o n e sev en -seg men t LED d isp lay to create er o n th e d isp lay b y o n e ev ery time a letter p asses b u tto n is p ressed . Use an LED to create an ex tra . C h a p t e r R e v ie w • Lo g ic sig n als, ex p ressed math ematically as 0 o r 1 , are rep resen ted in d ig ital electro n ic circu its as v o ltag es. On e ran g e o f v o ltag es rep resen ts 0 , an o th er rep resen ts 1 . Th e mb ed h as 2 6 d ig ital I/O p in s, wh ich can b e co n fig u red as eith er in p u t o r o u tp u t. L E D s c a n b e d riv e n d ire c tly fro m th e m b e d d ig ita l o u tp u ts . T h e y a re a u s e fu l m e a n s o f d isp lay in g a lo g ic v alu e, an d o f co n trib u tin g to a simp le h u man in terface. Electro mech an ical switch es can b e co n n ected to p ro v id e lo g ic v alu es to d ig ital in p u ts. A ran g e o f simp le o p to -sen so rs h av e almo st d ig ital o u tp u ts, an d can with care b e co n n ected d irectly to mb ed p in s. W h e re th e m b e d p in c a n n o t p ro v id e e n o u g h p o w e r to d riv e a n e le c tric a l lo a d d ire c tly , in terface circu its mu st b e u sed . Fo r simp le o n /o ff switch in g a tran sisto r is o ften all th at is n eed ed . • • • • • Q u iz 1 . 2 . 3 . C o m p le te Ta b le 3 .6 , c o n v e r tin g b e tw e e n th e d iff e r e n t n u m b e r ty n u mb ers is an ex amp le. Is it p o ssib le to d isp lay u n amb ig u o u sly all o f th e cap italized alp h D , E a n d F o n th e s e v e n - s e g m e n t d is p la y s h o w n in F ig u r e 3 .9 ? F o b e d is p la y e d , d e te rm in e th e s e g m e n t d riv e v a lu e s . G iv e y o u r a n s h ex ad ecimal fo rmats. A lo o p in an mb ed p ro g ram is u n tid ily co d ed as fo llo ws: p es. Th e first ro w o f ab et ch aracters A, B, C, r th o se th at can u sefu lly wers in b o th b in ary an d w h i l e ( 1 ) { r e d l e d = 0 ; w a i t _ m s ( 1 2 ) ; g r e e n l e d = 1 ; w a i t ( 0 . 0 0 2 ) ; g r e e n l e d = 0 ; w a i t _ u s ( 2 4 0 0 0 ) ; } Wh at is th e to tal p erio d o f th e lo o p , ex p ressed in seco n d s, milliseco n d s an d micro seco n d s? 5 4 Chapter 3 T a b le 3 .6 : B in a r y H e x a d e c im a l D e c im a l 0 1 0 1 1 1 1 0 5 E 9 4 1 1 0 1 7 7 1 2 9 6 F 2 1 1 0 1 1 1 0 0 1 0 0 1 4 0 9 6 4 . 5 . 6 . 7 . T h e c ir c u it o f F ig u r e 3 .5 b is u s e d e ig h t tim e s o v e r to c o n n e c t e ig h t s w itc h e s to 8 m b e d d ig ital in p u ts. Th e p u ll-u p resisto rs h av e a v alu e o f 1 0 k U , an d are co n n ected to th e mb ed s u p p ly o f 3 .3 V. W h a t c u r r e n t is c o n s u m e d d u e to th is c ir c u it c o n fi g u r a tio n w h e n a ll s w itc h e s a r e c lo s e d s im u lta n e o u s ly ? I f th is c u r r e n t d r a in m u s t b e lim ite d to 0 .5 m A , to wh at v alu e mu st th e p u ll-u p resisto rs b e in creased ? Reflect o n th e p o ssib le imp act o f p u llu p resisto rs in lo w-p o wer circu its. W h a t is th e c u r r e n t ta k e n b y th e d is p la y c o n n e c te d in F ig u r e 3 .1 0 , w h e n th e d ig it 3 is sh o win g ? I f in F ig u r e 3 .1 0 a s e g m e n t c u r r e n t o f a p p r o x im a te ly 4 m A w a s r e q u ir e d , w h a t v a lu e o f resisto r wo u ld n eed to b e in tro d u ced in series with each seg men t? A stu d en t b u ild s an mb ed -b ased sy stem. To o n e p o rt h e co n n ects th e circu it o f F ig u r e 3 .1 5 a , u s in g L E D s o f th e ty p e u s e d in F ig u r e 3 .4 , b u t is th e n d is a p p o in te d th a t th e (a ) 3 .3 V (b ) Z V N 4 2 0 6 A m b e d p o rt o u tp u t F ig u r e 3 .1 5 : T r ia l s w it c h in g c ir c u it s D ig it a l In p u t a n d O u t p u t 8 . 9 . LEDs d o n o t ap p ear to lig h t wh en ex p ected . Ex p lain wh y th is is so , an d su g g c h a n g in g th e c irc u it to g iv e th e re q u ire d b e h a v io r. An o th er stu d en t wan ts to co n tro l a DC mo to r fro m th e mb ed , an d th erefo re c ir c u it o f F ig u r e 3 .1 5 b , w h e r e V S is a D C s u p p ly o f a p p r o p r ia te v a lu e . A s a in d icatio n th at th e mo to r is ru n n in g , sh e co n n ects a stan d ard LED, as seen in d irectly to th e p o rt b it. Sh e th en co mp lain s o f u n reliab le circu it b eh av io r. E n ecessary ch an g es th at sh o u ld b e mad e to th e circu it. L o o k a t th e m b e d c ir c u it d ia g r a m , R e f e r e n c e 2 .2 , a n d fi n d th e f o u r o n b o a r d Estimate th e cu rren t each o n e tak es wh en ‘o n ’, assu min g a fo rward v o ltag e References 3 .1 . 3 .2 . Flo y d , T. (2 0 0 8 ). Dig ital Fu n d amen tals. 1 0 th ed itio n . Pearso n Ed u catio n . T h e K in g b r ig h t h o m e s ite . h ttp ://w w w.k in g b r ig h t.c o m / 5 5 est a way o f b u ild s th e fu rth er F ig u r e 3 .3 , x p lain an y LEDs. o f 1 .8 V. C H A P T E R 4 A n a lo g O u t p u t C h a p t e r O u t lin e 4 .1 In t r o d u c in g D a t a C o n v e r s io n 5 7 4 .1 .1 T h e D ig it a l- t o - A n a lo g C o n v e r t e r 4 .2 A n a lo g O u t p u t s o n t h e m b e d 4 .2 4 .2 4 .2 4 .2 .1 C r e a t in .2 S a w to o .3 T e s t in g .4 G e n e ra g C o n sta n t th W a v e fo r th e D A C R t in g a S in e 5 8 5 9 O u t p u t V o lt a g e s m s 6 0 e s o lu t io n 6 3 W a v e 6 4 6 0 4 .3 A n o t h e r F o r m o f A n a lo g O u t p u t : P u ls e W id t h M o d u la t io n 4 .4 P u ls e W id t h M o d u la t io n o n t h e m b e d 6 6 4 .4 4 .4 4 .4 4 .4 4 .4 4 .4 .1 U s in g t h e m b e d P W M S o u r c e .2 S o m e T r ia l P W M O u t p u t s 6 .3 S p e e d C o n t r o l o f a S m a ll M o .4 G e n e r a t in g P W M in S o ft w a r e .5 S e rv o C o n tro l 7 1 .6 O u t p u t t in g t o a P ie z o T r a n s d C h a p t e r R e v ie w Q u iz 7 4 R e fe re n c e 7 5 4 .1 s 6 5 6 6 7 to r 6 8 6 8 u c e r 7 2 7 4 In t r o d u c in g D a t a C o n v e r s io n Micro co n tro llers are d ig ital d ev ices, b u t th ey sp en d mo st o f th eir time d ealin g with a wo rld w h ic h is a n a lo g , a s illu s tr a te d in F ig u r e 1 .1 . To m a k e s e n s e o f in c o m in g a n a lo g s ig n a ls , f o r ex amp le fro m a micro p h o n e o r temp eratu re sen so r, th ey mu st b e ab le to co n v ert th em in to d ig ital fo rm. After p ro cessin g th e d ata, th ey may th en n eed to co n v ert d ig ital d ata b ack to a n a lo g fo rm , fo r e x a m p le to d riv e a lo u d s p e a k e r o r d ire c t c u rre n t (D C ) m o to r. We g iv e th e s e p ro cesses th e g lo b al h ead in g ‘d ata co n v ersio n ’. Tech n iq u es ap p lied in d ata co n v ersio n fo rm a h u g e an d fascin atin g b ran ch o f electro n ics. Th ey are o u tsid e th e su b ject matter o f th is b o o k ; h o wev er, if y o u wish to learn mo re ab o u t th em, co n sid er an y majo r electro n ics tex t. To g et d e e p in to th e to p ic , r e a d R e f e r e n c e 4 .1 . Wh ile co n v ersio n in b o th d irectio n s b etween d ig ital an d an alo g is n ecessary , it is co n v ersio n fro m an alo g to d ig ital fo rm th at is th e mo re ch allen g in g task ; th erefo re, in th is ch ap ter th e F a s t a n d E f f e c t iv e E m b e d d e d S y s t e m s D e s ig n . D O I : 1 0 .1 0 1 6 /B 9 7 8 - 0 - 0 8 - 0 9 7 7 6 8 - 3 .0 0 0 0 4 - 0 Co p y rig h t Ó2 0 1 2 Elsev ier Ltd . All rig h ts reserv ed . 5 7 5 8 Chapter 4 e a s ie r o p tio n is c o n s id e re d : c o n v ers io n fro m d ig ita l to a n a lo g . (An a lo g -to -d ig ita l c o n v ers io n is c o v e r e d in C h a p te r 5 .) 4 .1 .1 T h e D ig it a l-t o -A n a lo g C o n v e r t e r A d ig ital-to -an an alo g o u tp u t. can , h o wev er, in p u t, rep resen th e DAC calcu v o lta g e. alo g Th e rep re ted b lates c a s y o n v erter (DAC) is a circu it th at co n v erts c tu a l c irc u itry in s id e a DAC is c o mp lex , en t th e DAC as a b lo ck d iag ram, as in F D, an d an an alo g o u tp u t, rep resen ted b y its o u tp u t v o ltag e is a vo lta g e referen ce, a b an ig u Vo a p in ary in p u t n u mb er d n eed n o t co n cern r e 4 .1 . T h is h a s a d . Th e ‘y ard stick ’ b y rec is e, stab le an d k in to an u s. We ig ital wh ich n o wn Mo st DACs h av e a simp le relatio n sh ip b etween th eir d ig ital in p u t an d an alo g o u tp u t, with m a n y ( in c lu d in g th e o n e in s id e th e L P C 1 7 6 8 ) a p p ly in g E q u a tio n 4 .1 : V o D ¼ 2 V n 4 .1 r Here, Vr is th e v alu e o f th e v o ltag e referen ce, D is th e v alu e o f th e b in ary in p u t wo rd , n is th e n u m b e r o f b its in th a t w o r d , a n d Vo is th e o u tp u t v o lta g e . F ig u r e 4 .2 s h o w s th is e q u a tio n rep resen ted g rap h ically . Fo r each in p u t d ig ital v alu e, th ere is a co rresp o n d in g an alo g o u tp u t. It is as if we are creatin g a v o ltag e staircase with th e d ig ital in p u ts. Th e n u mb er o f p o ssib le o u tp u t v a lu e s is g iv e n b y 2 n , a n d th e s te p s iz e b y V r /2 n ; th is is c a lle d th e re s o lu tio n . T h e m a x im u m p o ssib le o u tp u t v alu e o ccu rs wh en D ¼ (2 n 1 ), so th e v alu e o f Vr as an o u tp u t is n ev er q u ite reach ed . Th e ra n g e o f th e DAC is th e d ifferen ce b etween its max imu m an d min imu m o u tp u t v a lu e s . F o r e x a m p le , a 6 - b it DAC w ill h a v e 6 4 p o s s ib le o u tp u t v a lu e s ; if it h a s a 3 .2 V r e f e r e n c e , it w ill h a v e a r e s o lu tio n ( s te p s iz e ) o f 5 0 m V. Fig u re o u tp u t p o wer th erefo 2 .3 s h o w s th a t ch aracteristic, su p p ly v o ltag e r e b e 3 .3 /1 0 2 4 th e i.e . , i.e , i.e LPC1 7 6 8 h as a 1 0 -b it DAC; th ere will th erefo re b e 2 1 0 step s in its 1 0 2 4 . R e f e r e n c e 2 .4 f u r th e r te lls u s th a t it n o r m a lly u s e s its o w n . 3 .3 V, a s v o lta g e r e f e r e n c e . T h e s te p s iz e , o r r e s o lu tio n , w ill . 3 .2 2 m V. + D (n -b it Dig ital in p u t) Vo ltag e Referen ce Dig ital to An alo g Co n v erter + V - O (An alo g Ou tp u t) Co n tro l Lin es F ig u r e 4 .1 : T h e d ig it a l- t o - a n a lo g c o n v e r t e r A n a lo g O u t p u t 5 9 Outp ut Vo lta g e n (2 - 1 ) V r n (2 - 2 ) V 3 V V 2 n 2 n 2 r r n 2 r r 2 V V r n 2 n 0 0 0 0 0 1 0 1 0 0 1 1 n (2 - 2 ) n (2 - 1 ) 2 n D (In p u t Bin a ry Nu mb er) F ig u r e 4 .2 : T h e D A C in p u t / o u t p u t c h a r a c t e r is t ic 4 .2 A n a lo g O u t p u t s o n t h e m b e d T h e m b e d p in c o n n e c tio n d ia g r a m , F ig u r e 2 .1 c , h a s a lr e a d y s h o w n u s th a t th e m b e d is r ic h in a n a l o g i n p u t / o u t p u t c a p a b i l i t i e s . P i n s 1 5 e2 0 c a n b e a n a l o g i n p u t , w h i l e p i n 1 8 i s t h e o n l y an alo g o u tp u t. T h e a p p lic a tio n p r o g r a m m in g in te r f a c e ( A P I ) s u m m a r y f o r a n a lo g o u tp u t is s h o w n in Ta b le 4 .1 . It fo llo w s a p a tte rn s im ila r to th e d ig ita l in p u t a n d o u tp u t u tilitie s w e h av e a lre a d y s e e n . H e re, w ith A n a lo g O u t, w e c a n in itializ e a n d n a m e a n o u tp u t; u s in g w r ite ( ) o r w r ite _ u 1 6 ( ), w e c a n s e t th e o u tp u t v o lta g e e ith e r w ith a fl o a tin g p o in t n u m b e r o r w ith a h ex a d e c im a l n u m b e r. F in a lly , w e ca n simp ly u se th e ¼ s ig n a s a s h o rth a n d fo r w rite, w h ich is w h a t w e w ill mo stly b e d o in g . N o tic e in Ta b le 4 .1 th e w a y th a t d a ta ty p e s fl o a t, a n d u n s ig n e d s h o r t a re in v o k e d . I n C /C þ þ a ll d ata e lem en ts h av e to b e d ec lared b efo re u se ; th e s am e is tru e fo r th e retu rn ty p e o f a fu n c tio n a n d th e p ara m e te rs it ta k e s . A rev iew o f th e c o n ce p t o f fl o a tin g p o in t n u m b e r r e p r e s e n ta tio n c a n b e f o u n d in A p p e n d ix A . Ta b le B .4 in A p p e n d ix B s u m m a r iz e s th e d iffe re n t d a ta ty p e s th a t a re av a ila b le . T h e DAC itse lf re q u ire s a n u n sig n e d b in a ry n u mb e r a s in p u t, s o th e w r ite _ u 1 6 ( ) fu n c tio n re p re se n ts th e m o re d irec t a p p ro a c h o f w ritin g to it. C c o d e fe a tu re T a b le 4 .1 : A P I s u m m a r y f o r m b e d a n a lo g o u t p u t F u n c t io n U s a g e A n a l o g O u t C r e a t e a n A n a lo g O u t o b je c t c o n n e c t e d t o t h e s p e c ifi e d p in w r i t e S e t t h e o u t p u t v o lt a g e , s p e c ifi e d a s a p e r c e n t a g e ( fl o a t ) w r i t e _ u 1 6 S e t t h e o u t p u t v o lt a g e , r e p r e s e n t e d a s a n u n s ig n e d s h o r t in t h e r a n g e [ 0 x 0 , 0 x F F F F ] r e a d R e t u r n t h e c u r r e n t o u t p u t v o lt a g e s e t t in g , m e a s u r e d a s a p e r c e n t a g e ( fl o a t ) o p e r a t o r = A n o p e r a t o r s h o r t h a n d fo r w r it e ( ) 6 0 Chapter 4 We try n o w a few simp le p ro g rams wh ich ap p ly th e mb ed DAC, creatin g first fix ed v o ltag es an d th en wav efo rms. 4 .2 .1 C r e a t in g C o n s t a n t O u t p u t V o lt a g e s C re a te a n ew A o u t, b y u s in b y s ettin g A o A o u t tak es a a ctu a l o u tp u t y o u o u tp u t is / * R e * / # i A n i n p ro g ra m u s in g P ro g ra m E x a m p le 4 g th e A n a lo g O u t u tility . It is th e n u t to a n y p e rm is sib le v a lu e; w e d o fl o a tin g p o in t n u m b e r b e tw e e n 0 .0 v o ltag e o n p in 1 8 is b e tw ee n 0 V s ca le d to th is. P r o g r a m E x a m p l e 4 . 1 : T h r e e a d t h e o u t p u t o n a D V M . n c l a l o t m w h i A o u w a i A o u w a i A o u w a i } u d e g O u a i n l e ( t = 0 t ( 2 t = 0 t ( 2 t = 0 t ( 2 t ( ) . ) . ) . 1 " m b e d . h " A o u t ( p 1 8 ) ; ) { ) { 2 5 ; ; 5 ; ; 7 5 ; ; / / c r e a t e v a l u e s a n / / 0 . 2 5 * 3 . 3 V / / 0 . 5 * 3 . 3 V / / 0 . 7 5 * 3 . 3 V o f D A C a n a l o g = .1 . I n th is w e c r e a te a n a n a lo g o u tp u t la b e le d p o s sib le to s et th e a n alo g o u tp u t s im p ly th is th ree tim e s in th e p ro g ra m. B y d e fa u lt, a n d 1 .0 a n d o u tp u ts th is to p in 1 8 . T h e a n d 3 .3 V, s o th e fl o a ti n g p o in t n u m b e r th a t a r e o u t p u t o u t p u t i n o n 1 8 p i n t u r n o n P i n 1 8 . = 0 . 8 2 5 V = 1 . 6 5 V 2 . 4 7 5 V } P r o g r a m E x a m p le 4 .1 T r ia l D A C o u t p u t Co mp ile th e p ro g ram in th e u su al way , an d let it ru n . Co n n ect a d ig ital v o ltmeter (DVM) b e tw e e n p in s 1 a n d 1 8 o f th e m b e d . Yo u s h o u ld s e e th e th r e e o u tp u t v o lta g e s n a m e d in th e c o m m e n ts o f P r o g r a m E x a m p le 4 .1 b e in g o u tp u t in tu r n . n E x e r c is e 4 .1 A d ju s t P r o g r a m E x a m p le 4 .1 s o t h a t t h e w r it e _ u 1 6 ( ) fu n c t io n is u s e d t o s e t t h e a n a lo g o u t p u t , g iv in g t h e s a m e o u t p u t v o lt a g e s . n 4 .2 .2 Sawtooth Waveforms We will n o w mak e a sawto o th wav e an d v iew it o n an o scillo sco p e. Create a n ew p ro g ram an d e n te r th e c o d e o f P r o g r a m E x a m p le 4 .2 . As in man y cases p rev io u sly , th e p ro g ram is mad e u p o f an en d less w h ile (1 ) lo o p . With in th is th ere is a fo r lo o p . In th is ex amp le, th e v ariab le i is in itially set to 0 , an d o n each iteratio n o f A n a lo g O u t p u t 6 1 th e lo o p it is in c r e m e n te d b y 0 .1 . T h e n e w v a lu e o f i is a p p lie d w ith in th e lo o p . W h e n i r e a c h e s 1 , th e lo o p termin ates. As th e fo r lo o p is th e o n ly co d e with in th e en d less w h ile lo o p , it rep eats co n tin u o u sly . / * * / # i A n f l i n P r o g r a m n c l a l o o a t t m w h i f u d e g O u i ; a i n l e o r A o w a t E x a m p l e 4 . 2 : S a w t o o t h w a v e f o r m o n D A C o u t p u t . V i e w o n o s c i l l o s c o p e " m b e d . h " A o u t ( p 1 8 ) ; ( ) ( 1 ( i u t i t { ) { = 0 ; i < 1 ; i = i + 0 . 1 ) { = i ; ( 0 . 0 0 1 ) ; / / i / / i s w a i t i n c r e m e n t e d 1 i n s t e p s o f 0 . 1 m i l l i s e c o n d } } } P r o g r a m E x a m p le 4 .2 S a w t o o t h w a v e fo r m Co n n ect an o scillo sco p e p ro b e to p in 1 8 o f th e mb ed , with its earth co n n ectio n to p in 1 . Ch eck th a t y o u g e t a s a w to o th w a v e f o r m s im ila r to th a t s h o w n in F ig u r e 4 .3 . E n s u r e th a t th e d u r a tio n 4 .5 V D C 4 .0 3 .5 3 .0 2 .5 2 .0 1 .5 1 .0 0 .5 0 .0 -0 .5 0 .0 m s 0 .5 1 .0 1 .5 2 .0 2 .5 3 .0 P ic o T e c h n o lo g y w w w .p ic o te c h .c o m F ig u r e 4 .3 : A s te p p e d s a w to o th w a v e fo rm 3 .5 4 .0 4 .5 5 .0 6 2 Chapter 4 o f each step is th e 1 ms y o u d efin e in th e p ro g ram, an d try v ary in g th is. Th e wav efo rm sh o u ld s ta r t f r o m 0 V a n d n o t g o h ig h e r th a n 3 .3 V. E x p la in th e m a x im u m v a lu e y o u s e e . If y o u d o n o t h av e an o scillo sco p e y o u can set th e wait p arameter to b e mu ch lo n g er (say 1 0 0 m s ) a n d u s e th e DV M ; y o u s h o u ld th e n s e e th e v o lta g e s te p u p f r o m 0 V to 3 .3 V a n d th e n reset b ack to 0 V ag ain . n E x e r c is e 4 .2 Im p r o v e t h e r e s o lu t io n o f y o u r s a w t o o t h b y h a v in g m o r e b u t s m a lle r in c r e m e n t s , i.e . r e d u c e t h e v a lu e b y w h ic h i in c r e m e n t s . T h e r e s u lt s h o u ld b e a s s e e n in F ig u r e 4 .4 . n n E x e r c is e 4 .3 C r e a t e a n e w p r o je c t a n d d e v is e a p r o g r a m w h ic h o u t p u t s a t r ia n g u la r w a v e fo r m ( i.e . o n e t h a t c o u n t s d o w n a s w e ll a s u p ) . T h e o s c illo s c o p e o u t p u t s h o u ld lo o k lik e F ig u r e 4 .5 . n 4 .5 V D C 4 .0 3 .5 3 .0 2 .5 2 .0 1 .5 1 .0 0 .5 0 .0 -0 .5 0 .0 m s 0 .5 1 .0 1 .5 2 .0 2 .5 3 .0 P ic o T e c h n o lo g y w w w .p ic o te c h .c o m F ig u r e 4 .4 : A s m o o th s a w to o th w a v e fo rm 3 .5 4 .0 4 .5 5 .0 A n a lo g O u t p u t 6 3 4 .5 V D C 4 .0 3 .5 3 .0 2 .5 2 .0 1 .5 1 .0 0 .5 0 .0 -0 .5 0 .0 m s 2 .0 1 .0 3 .0 4 .0 5 .0 6 .0 P ic o T e c h n o lo g y w w w .p ic o te c h .c o m 7 .0 8 .0 9 .0 1 0 .0 F ig u r e 4 .5 : A t r ia n g u la r w a v e fo r m 4 .2 .3 T e s t in g t h e D A C R e s o lu t io n No w let u s retu rn to th e q u estio n o f th e DAC reso lu tio n , wh ich we to u ch ed o n in Sectio n 4 .1 .1 . Tr y c h a n g in g th e fo r lo o p in y o u r v e r s io n o f P r o g r a m E x a m p le 4 .2 to th is : f o r ( A o u w a i l e d i = t = t ( 1 = 0 ; i < 1 ; i = i + 0 . 0 0 0 1 ) { i ; 1 ) ; ! l e d 1 ; } We h av e also in clu d ed a little LED in d icatio n h ere, so ad d th is lin e b efo re m a in ( ) to set it u p : D i g i t a l O u t l e d 1 ( L E D 1 ) ; Th is ad will ta k (h en ce h o u rs!). Ou r p u rp o C c o d e fe a tu re ju ste e 1 0 th e p se is d p ro g 0 0 0 s erio d n o t, h ram tep s o f th o wev will p ro d to reach e wav efo er, to v ie u ce th e rm w th an ex tre max imu is 1 0 0 0 e wav ef mely slo w sawto o th wav efo rm, wh ich m v alu e, each o n e tak in g a seco n d 0 seco n d s, o r two an d th ree q u arter o rm, b u t to ex p lo re carefu lly th e DAC 6 4 Chapter 4 c h a r a c te r is tic o f F ig u re 4 .2 . N o tic e th e u s e o f th e N OT o p e r a to r, in th e f o r m o f a n e x c la m a tio n mark (!), fo r th e first time . Th is cau ses lo g ical in v ersio n , so a Lo g ic 0 is rep laced b y 1 , an d v ic e v e rs a . S w itc h y o u r DV M to its fi n e s t v o lta g e ra n g e , s o th a t y o u h a v e m illiv o lt re s o lu tio n o n th e sca le ; th e 2 0 0 mV scale is u sefu l h ere. C o n n ect th e DVM b etween p in s 1 an d 1 8 , an d ru n th e p ro g ra m. Th e LED ch an g es state ev ery time a n ew v alu e is o u tp u t to th e DAC. H o w e v e r, y o u w ill n o tic e a n in te r e s tin g th in g . Yo u r DV M r e a d in g d o e s n o t c h a n g e w ith ev ery LED ch an g e. In stead it ch an g es s tate in d istin ct step s, with each ch an g e b ein g a r o u n d 3 m V. Yo u w ill n o tic e a ls o th a t it ta k e s a r o u n d fi v e L E D ‘ b lin k s ’ , i.e . 1 0 u p d a te s o f th e DAC v a lu e , b e fo re e a c h DAC c h a n g e . A ll th is w a s a n tic ip a te d in S e c tio n 4 .1 .1 , w h e r e a s te p s iz e o f 3 .2 2 m V w a s p r e d ic te d ; e a c h s te p s iz e is e q u a l to th e DAC reso lu tio n . Th e flo at v alu e is ro u n d ed to th e n earest d ig ital in p u t to th e DAC, an d it ta k e s aro u n d 1 0 in c reme n ts o f th e flo at v alu e fo r th e DAC d ig ital in p u t to b e in cremen ted b y o n e. 4 .2 .4 G e n e r a t in g a S in e W a v e It is an easy step fro m h ere to g en erate a sin e wav e. We will ap p ly th e s in ( ) f u n c tio n , w h ic h is p a r t o f th e C s ta n d a r d lib r a r y ( s e e S e c tio n B .9 .2 ) . Ta k e a lo o k a t P r o g r a m E x a m p le 4 .3 . To p r o d u c e o n e c y c le o f th e s in e w a v e , w e w a n t to ta k e s i n e v a l u e s o f a n u m b e r w h i c h i n c r e a s e s f r o m 0 t o 2 p$ r a d i a n s . I n t h i s p r o g r a m w e u s e a f o r lo o p to in cremen t v ariab le i fro m 0 to 2 in small step s, an d th en mu ltip ly th at n u mb er b y p wh en th e sin e v alu e is calcu lated . Th ere are o th er way s o f g ettin g th is resu lt. Th e fin al c h a lle n g e is th a t th e DAC c a n n o t o u tp u t n e g a tiv e v a lu e s . T h e re fo re , w e a d d a fi x e d v a lu e (a n o ffs e t) o f 0 .5 to th e n u m b e r b e in g s e n t to th e DAC ; th is e n s u r e s th a t a ll o u tp u t v a lu e s lie with in its av ailab le ran g e. No tice th at we are u sin g th e mu ltip ly o p erato r, * , fo r th e first time. C c o d e fe a tu re / * * / # i A n f l i n P r o g r a m n c l a l o o a t t m w h u d e g O u i ; a i n i l e f o r A w } t E x a m p l e 4 . 3 : S i n e w a v e o n D A C o u t p u t . V i e w o n o s c i l l o s c o p e " m b e d . h " A o u t ( p 1 8 ) ; ( ) ( 1 ( o u a i { ) { i = 0 ; i < 2 ; i = i + 0 . 0 5 ) { t = 0 . 5 + 0 . 5 * s i n ( i * 3 . 1 4 1 5 9 ) ; t ( . 0 0 1 ) ; / / / / C o m p u t e t h e s i n e v a l u e , + h a l f C o n t r o l s t h e s i n e w a v e p e r i o d } } P r o g r a m E x a m p le 4 .3 G e n e r a t in g a s in u s o id a l w a v e fo r m t h e r a n g e A n a lo g O u t p u t n E x e r c is e 4 .4 O b s e rv e o n th e o s it s fr e q u e n c y fr o m a g r e e ? T r y v a r y in g fre q u e n c y y o u c a n 4 .3 6 5 c illo s c o in fo r m th e fre a c h ie v p e th e a t io n q u e n c e w it h s in e in t h y b y t h is w a v e t h a t P r o g r a m E x a m p le 4 .3 p r o d u c e s . E s t im a t e e p r o g r a m , a n d t h e n m e a s u r e it . D o t h e t w o v a lu e s v a r y in g t h e w a it p a r a m e t e r . W h a t is t h e m a x im u m p ro g ra m ? n A n o t h e r F o r m o f A n a lo g O u t p u t : P u ls e W id t h M o d u la t io n T h e DAC is a fi n e c irc u it a n d it h a s m a n y u s e s . Ye t it a d d s c o m p le x ity to a m ic ro c o n tro lle r, an d so metimes mo v es u s to th e an alo g d o main b efo re we are read y to g o . Pu lse wid th m o d u la tio n (P W M ) is a n a lte rn a tiv e ; in d e e d , th e m b e d h a s s ix P W M o u tp u ts b u t o n ly o n e an alo g o u tp u t. PWM rep resen ts a n eat an d remark ab ly simp le way o f g ettin g a rectan g u lar d ig ital wav efo rm to co n tro l an an alo g v ariab le, u su ally v o ltag e o r cu rren t. PWM co n tro l is u sed in a v ariety o f ap p licatio n s, ran g in g fro m teleco mmu n icatio n s to ro b o tic co n tro l. A P W M s ig n a l is s h o w n in F ig u r e 4 .6 . T h e p e r io d is n o r m a lly k e p t c o n s ta n t, a n d th e p u ls e wid th , o r ‘o n ’ time, is v aried , h en ce th e n ame. Th e d u ty cycle is th e p ro p o rtio n o f time th at th e p u ls e is ‘ o n ’ o r ‘ h ig h ’ , a n d is e x p r e s s e d a s a p e r c e n ta g e , i.e .: d u ty cy cle ¼ p u lse o n time 1 0 0 % p u lse p erio d A 1 0 0 % d u ty cy cle th e re fo re me an s ‘c o n tin u o u sly o n ’ a n d a 0 % o ff ’. P WM stre ams a re e as ily g en e ra te d b y d ig ita l co u n te rs a n d b e d e s ig n e d in to a m ic ro co n tro lle r. T h ey c an a ls o b e p ro d u c e d a s ta n d a rd d ig ita l o u tp u t, w ith n o d e d ic a te d h a rd w a re a t a ll. T h W h a tev e r d u ty cy c le in F ig u r e 4 .6 . I f th e o v a lu e is h ig h . B y c o n u sin g PWM, it is th is a P WM s tre am h as , th ere is n time is s ma ll, th e av erag e tro llin g th e d u ty cy c le, th e av e ra g e th a t w e a re u su a lly 'o n ' t im e , t o an av erag e v a v a lu e is lo w ; re fo re , th is av in te re sted in . n A v e ra g e v a lu e P e r io d , T F ig u r e 4 .6 : A P W M w a v e fo rm d u ty co m s imp is is 4 .2 cy c le m e a n s ‘c o n tin u o u s ly p arato rs , w h ich c an re ad ily ly b y p ro g ra m lo o p s a n d s ee n la te r in th e c h a p ter. lu e , a s in if th e o n erag e v a It can b e d ic ate d b y th e d o tted lin e time is larg e, th e av e ra g e lu e is co n tro lle d . Wh en ex tra cted fro m th e P WM 6 6 Chapter 4 VS S R Vin R D Vo u t L C I ( a ) A r e s is to r - c a p a c ito r lo w - p a s s filte r ( b ) A n in d u c tiv e lo a d F ig u r e 4 .7 : S im p le a v e r a g in g c ir c u it s s tr e a m in a n u m b e r o f w a y s . E le c tr ic a lly , w e c a n u s e a lo w - p a s s fi lte r, e .g . th e r e s is to r - c a p a c ito r c o m b in a tio n o f F ig u r e 4 .7 a . I n th is c a s e , a n d a s lo n g a s P W M f r e q u e n c y a n d v a lu e s o f R a n d C a r e a p p ro p ria te ly c h o s e n , Vo u t b e c o me s a n a n a lo g o u tp u t, w ith a b it o f rip p le , a n d th e c o m b in a tio n o f P W M a n d fi lte r a c ts ju s t lik e a DAC . A lte r n a tiv e ly , if w e s w itc h th e c u r re n t fl o w in g in a n in d u c tiv e lo a d , a s s e e n in F ig u r e 4 .7 b , th e n th e in d u c ta n c e h a s a n a v e r a g in g e f f e c t o n th e c u r r e n t fl o w in g th r o u g h it. T h is is v e ry im p o r ta n t, a s th e w in d in g s o f a n y m o to r a re in d u c tiv e , s o th is te c h n iq u e c a n b e u s e d f o r m o to r c o n tr o l. T h e s w itc h in F ig u r e 4 .7 b is c o n tr o lle d b y th e P W M s tre a m, a n d c a n b e a tra n s is to r. We h av e in c id e n ta lly to in tro d u c e th e fre ew h e e lin g d io d e , ju s t a s w e d id in F ig u r e 3 .1 2 c , to p r o v id e a c u r r e n t p a th a s th e s w itc h o p e n s . In p ractice, th is in tern al in ertias a co n v en tio n al fi av erag e temp era electric wh ich , lamen t tu re o f al filterin g is n o t alwa in reality , act lik e lo w lig h t b u lb with PWM. th e b u lb filamen t, an d y s req u ired . -p ass filters. In th is case, th e d immin Man y p We can v ary in g g effect h y sical sy stems h av e , fo r ex amp le, d im th e p u lse wid th v aries th e is ach iev ed . As an ex amp le, th e co n tro l o f a DC mo to r is a v ery co mmo n task in ro b o tics; th e sp eed o f a DC mo to r is p ro p o rtio n al to th e ap p lied DC v o ltag e. We co u ld u se a co n v en tio n al DAC o u tp u t, d riv e it th ro u g h a n e x p e n s iv e a n d b u lk y p o w e r a m p lifi e r, a n d u s e th e a m p lifi e r o u tp u t to d riv e th e m o to r. A lte rn a tiv e ly , a P W M s ig n a l c a n b e u s e d to d riv e a p o w e r tra n s is to r d ire c tly , w h ic h r e p la c e s th e s w itc h in F ig u r e 4 .7 b ; th e m o to r is th e in d u c to r /r e s is to r c o m b in a tio n in th e same circu it. Th is tech n iq u e is tak en mu ch farth er in th e field o f p o wer electro n ics, with th e PWM co n cep t b ein g tak en far b ey o n d th ese simp le b u t u sefu l ap p licatio n s. 4 .4 4 .4 .1 P u ls e W id t h M o d u la t io n o n t h e m b e d U s in g t h e m b e d P W M S o u r c e s A s m e n tio n e d , it is e a s y to g e n e ra te P W M p u ls e s tre a m s u s in g s im p le d ig ita l b u ild in g b lo ck s. We d o n o t ex p lo re h o w th at is d o n e in th is b o o k , b u t y o u can fin d th e in fo rmatio n A n a lo g O u t p u t 6 7 T a b le 4 .2 : A P I s u m m a r y f o r P W M o u t p u t F u n c t io n U s a g e P w m O u t C r e a t e a P w m O u t o b je c t c o n n e c t e d t o t h e s p e c ifi e d p in w r i t e S e t t h e o u t p u t d u t y c y c l e , s p e c i fi e d a s a n o r m a l i z e d fl o a t ( 0 . 0 e1 . 0 ) r e a d R e t u r n t h e c u r r e n t o u t p u t d u t y - c y c l e s e t t i n g , m e a s u r e d a s a n o r m a l i z e d fl o a t ( 0 . 0 e1 . 0 ) p e r i o d S e t t h e P W M p e r io d , s p e c ifi e d in s e c o n d s ( fl o a t ) , k e e p in g t h e d u t y c y c le t h e s a m e p e r i o d _ m s S e t t h e P W M p e r io d , s p e c ifi e d in m illis e c o n d s ( in t ) , k e e p in g t h e d u t y c y c le t h e s a m e p e r i o d _ u s S e t t h e P W M p e r io d , s p e c ifi e d in m ic r o s e c o n d s ( in t ) , k e e p in g t h e d u t y c y c le t h e s a m e p u l s e w i d t h S e t t h e P W M p u ls e w id t h , s p e c ifi e d in s e c o n d s ( fl o a t ) , k e e p in g t h e p e r io d t h e s a m e p u l s e w i d t h _ m s S e t t h e P W M p u ls e w id t h , s p e c ifi e d in m illis e c o n d s ( in t ) , k e e p in g t h e p e r io d t h e s a m e p u l s e w i d t h _ u s S e t t h e P W M p u ls e w id t h , s p e c ifi e d m ic r o s e c o n d s ( in t ) , k e e p in g t h e p e r io d t h e s a m e o p e r a t o r = A n o p e r a t o r s h o r t h a n d fo r w r it e ( ) elsewh ere th at th ere LPC1 7 6 8 freq u en cy if y o u are six micro c ; if th e wish , fo r PWM o u o n tro ller, p erio d is ex amp le tp u ts av a an d h en c ch an g ed in R e f e r e n c e 1 .1 . A s f o r th e m b e d , F ig u r e 2 .1 c s h o w s ila b le , fro m p in 2 1 to 2 6 in c lu s iv e . N o te th a t o n th e e th e mb ed , th e PWM so u rces all sh are th e same p erio d / fo r o n e, th en it is ch an g ed fo r all. A s w ith a ll p e rip h e ra ls , th e m b e d P WM p o rts a re s u p p o rte d b y lib ra ry u tilitie s a n d fu n c tio n s , a s s h o w n in Ta b le 4 .2 . T h is is r a th e r m o r e c o m p le x th a n th e A P I ta b le s w e h a v e s e e n s o f a r, s o w e c a n e x p e c t a little m o re c o m p le x ity in its u s e . N o ta b ly , in s te a d o f h av in g ju s t o n e v a riab le to c o n tro l ( e .g . a d ig ita l o r a n a n a lo g o u tp u t) , w e n o w h a v e tw o , p e r io d a n d p u ls e w id th , o r d u ty c y c le d e r iv e d f ro m th is c o m b in a tio n . S im ila r to p re v io u s e x a m p le s , a P W M o u tp u t c a n b e e s ta b lis h e d , n a m e d a n d a llo c ate d to a p in u s in g P w m O u t. S u b s e q u e n tly , it c a n b e v a rie d , b y s e ttin g its p erio d , d u ty cy cle o r p u ls e w id th . A s s h o rth an d , th e w r ite ( ) fu n c tio n c an s im p ly b e rep la ce d b y ¼ . 4 .4 .2 S o m e T r ia l P W M O u t p u t s As a first p ro g ram u sin g an mb ed PWM so u rce, let’s create a sig n al th at can b e seen o n an o s c illo s c o p e . M a k e a n e w p r o je c t, a n d e n te r th e c o d e o f P r o g r a m E x a m p le 4 .4 . T h is w ill g e n e r a te a 1 0 0 H z p u ls e w ith 5 0 % d u ty c y c le , i.e . a p e r f e c t s q u a r e w a v e . / * * / # i P w i n S e t s P W M n c l m O u t m P W P W " W M ( ) p e 0 . u d e t P a i n M 1 . M 1 = s o u r c e t o m b e d . h " 1 ( p 2 1 ) ; { r i o d ( 0 . 0 1 0 ) ; 5 ; f i x e d f r e q u e n c y / / c r e a t e / / / / s e t s e t a a n d P W M d u t y c y c l e . O b s e r v e o u t p u t o u t p u t c a l l e d P W M 1 p i n P W M p e r i o d d u t y c y c l e } P r o g r a m E x a m p le 4 .4 T r ia l P W M o u t p u t t o t o 1 0 m s 5 0 % o n 2 1 o n o s c i l l o s c o p e . 6 8 Chapter 4 In th is p ro h av e to u s a d ecimal time with g ram e th e n u mb th e fo ex amp le we first set th e PWM p erio d . Th ere is n o sh o rth an d fo r th is, so we f u ll P W M 1 .p e r io d ( 0 .0 1 0 ) ; s ta te m e n t. We th e n d e fi n e th e d u ty c y c le a s er, b etween th e v alu es o f 0 an d 1 . We co u ld also set th e d u ty cy cle as a p u lse llo win g : P W M 1 . p u l s e w i d t h _ m s ( 5 ) ; / / s e t P W M p u l s e w i d t h t o 5 m s Wh en y o u ru n th e p ro g ram y o u sh o u ld b e ab le to see th e sq u are wav e o n th e o scillo sco p e, an d v erify th e o u tp u t freq u en cy . E x e r c is e 4 .5 n 1 . C h a n (2 0 % e x a m 2 . C h a n p u ls e g ) p g w e th e d u ty c y c a n d 0 .8 ( 8 0 % le a s s h o w n in e th e p ro g ra m id t h _ m s ( ) . le o f P r o g r a m E x a m p le 4 .4 t o s o m e d iffe r e n t v a lu e s , s a y 0 .2 ) , a n d c h e c k t h e c o r r e c t d is p la y is s e e n o n t h e o s c illo s c o p e , fo r F ig u r e 4 .8 . t o g iv e t h e s a m e o u t p u t w a v e fo r m s , b u t u s in g p e r io d _ m s ( ) a n d n 4 .4 .3 S p e e d C o n t r o l o f a S m a ll M o t o r We will n o w ap p ly th e mb ed PWM so u rce to co n tro l mo to r sp eed . Use th e simp le mo to r c ir c u it w e u s e d in th e p r e v io u s c h a p te r ( F ig u r e 3 .1 3 ) , a n d c r e a te a p r o je c t u s in g P r o g r a m E x a m p le 4 .5 . T h is r a m p s th e P W M u p f r o m a d u ty c y c le o f 0 % to 1 0 0 % , u s in g p r o g r a m m in g featu res th at we k n o w. / * * / # i P w f l i n P r o g r a m n c l m O u o a t t m P W M w h i f u d e t P i ; a i n 1 . p l e ( o r P W w a E x a m p l e 4 . 5 : P W M c o n t r o l t o D C m o t o r i s r e p e a t e d l y p e r i o d t o 1 0 r a m p e d " m b e d . h " W M 1 ( p 2 1 ) ; ( ) e r 1 ) ( i M 1 i t { i o d ( 0 . 0 1 0 ) ; { = 0 ; i < 1 ; i = i + 0 . 0 1 ) = i ; ( 0 . 2 ) ; / / s e t P W M m s { / / u p d a t e P W M d u t y c y c l e } } } P r o g r a m E x a m p le 4 .5 C o n t r o llin g m o t o r s p e e d w it h m b e d P W M s o u r c e Co mp ile, d o wn lo ad an d ru n th e p ro g ram. See h o w y o u r mo to r p erfo rms an d o b serv e th e w a v e f o r m o n th e o s c illo s c o p e . Yo u a r e s e e in g o n e o f th e c la s s ic a p p lic a tio n s o f P W M , co n tro llin g mo to r sp eed th ro u g h a simp le d ig ital p u lse stream. A n a lo g O u t p u t 4 .0 V D C 3 .5 3 .0 2 .5 2 .0 1 .5 1 .0 0 .5 0 .0 -0 .5 -1 .0 0 .0 m s 0 .5 0 .0 m s 0 .5 1 .0 1 .5 2 .0 2 .5 3 .0 3 .5 4 .0 4 .5 5 .0 3 .0 3 .5 2 .0 2 .5 1 .5 P ic o T e c h n o lo g y w w w .p ic o te c h .c o m 4 .0 4 .5 5 .0 P ic o T e c h n o lo g y w w w .p ic o te c h .c o m 4 .0 V D C 3 .5 3 .0 2 .5 2 .0 1 .5 1 .0 0 .5 0 .0 -0 .5 -1 .0 1 .0 F ig u r e 4 .8 : P W M o b s e rv e d fro m th e m b e d o u tp u t 6 9 7 0 Chapter 4 4 .4 .4 G e n e r a t in g P W M in S o ft w a r e Alth o u g h th at th ese an d so me mo to r o n say 1 ms we are tim an d o n , h av e ju st u sed PWM so u rces th at are av ailab le o n th e mb ed , it is u sefu l to realize n o t essen tial fo r creatin g PWM; we can actu ally d o it ju st with a d ig ital o u tp u t in g . I n E x e r c is e 3 .8 y o u w e r e a s k e d to w r ite a p r o g r a m th a t s w itc h e d a s m a ll D C o ff co n tin u o u sly , 1 seco n d o n , 1 seco n d o ff. If y o u sp eed th is switch in g u p , to 1 ms o ff, y o u will immed iately h av e a PWM so u rce. C r e a te a n e w p r o je c t w ith P r o g r a m E x a m p le 4 .6 a s s o u r c e c o d e . N o tic e c a r e f u lly w h a t th e p ro g ra m d o e s. T h e re a re two fo r lo o p s in th e m a in w h ile lo o p . T h e m o to r is in itia lly s witc h e d o ff fo r 5 s . T h e fi rs t fo r lo o p th e n s witc h e s th e m o to r o n fo r 4 0 0 m s a n d o ff fo r 6 0 0 u s; it d o e s th is 5 0 0 0 tim e s . T h is re s u lts in a P WM s ig n a l o f p e rio d 1 m s a n d d u ty cy cle 4 0 % . T h e s e c o n d fo r lo o p s witc h e s th e m o to r o n fo r 8 0 0 m s a n d o ff fo r 2 0 0 u s ; th e p e rio d is s till 1 m s b u t th e d u ty cy cle is 8 0 % . T h e m o to r is th e n s witc h e d fu ll o n fo r 5 s . T h is s e q u e n ce c o n tin u es in d e fin itely . / * o n * / # i D i i n i n w P r o g r a m E x a m p l e 4 . 6 : S o f t w a r e g e n e r a t e d a n d o f f i n c l u d e d f o r c o m p a r i s o n . n c l g i t t i t m h i l P W M . 2 P W M v a l u e s g e n e r a t e d i n t u r n , w i t h f u l l u d e " m b e d . h " a l O u t m o t o r ( p 6 ) ; ; a i e ( m o w a f o n ( 1 ) t o i t r m o w a m o w a ) { { r ( t i t i = ( 5 i = o r t _ o r t _ 0 ) ; 0 ; = u s = u s ; i < 1 ( 4 0 ( 6 / / m o t o r 5 0 0 0 ; i = i + 1 ) { / / 5 0 0 0 s w i t c h e d P W M o f f c y c l e s , f o r l o w 5 s e c s d u t y c y c l e ; 0 0 ) ; ; 0 0 ) ; / / o u t p u t h i g h / / o u t p u t l o w f o r f o r 4 0 0 u s 6 0 0 u s } f o r ( m o t w a i m o t w a i i = 0 ; i < 5 0 0 0 ; i = i + 1 ) o r = 1 ; t _ u s ( 8 0 0 ) ; o r = 0 ; t _ u s ( 2 0 0 ) ; { / / 5 0 0 0 P W M c y c l e s , / / o u t p u t h i g h / / o u t p u t l o w f o r h i g h d u t y c y c l e 8 0 0 u s f o r 2 0 0 u s s w i t c h e d f u l l y } m o t o r = 1 ; w a i t ( 5 ) ; / / m o t o r o n f o r 5 s e c s } } P r o g r a m E x a m p le 4 .6 G e n e r a t in g P W M in s o f t w a r e Co mp ile an d d o wn lo ad th is p ro g ram, an d ap p ly th th at th e mo to r ru n s with th e sp eed p ro file in d icate r e a d ily v e r ifi e d o n th e o s c illo s c o p e . Yo u m a y w o n d ed icated PWM p o rts, wh en it seems q u ite easy to h o wev er, th at in th is ex amp le th e cen tral p ro cessin g e c ir c u it o f F ig u r e 3 .1 2 . Yo u s h o u ld fi n d d . PWM p erio d an d d u ty cy cle can b e d er wh eth er it is n ecessary to h av e g en erate PWM with so ftware. Rememb er, u n it (CPU) b eco mes to tally co mmitted to A n a lo g O u t p u t 7 1 th is task an d can d o n o th in g else. With th e h ard ware p o rts, we can set th e PWM ru n n in g an d th e C P U c a n th e n g e t o n w ith s o m e c o m p le te ly d iffe re n t a c tiv ity . n E x e r c is e 4 .6 V a ry th e m o to r in it ia lly k e e p in g p r o b a b ly fi n d t h o w n fr ic t io n . T h o s c illo s c o p e , a n a t m u c h h ig h e r s p e e d s in P r o g r a m E x a m p le 4 .6 b y t h e fr e q u e n c y c o n s t a n t . D e p e n d in a t fo r s m a ll v a lu e s o f d u t y c y c le t h e is is p a r t ic u la r ly t r u e o f g e a r e d m o t d c o n fi r m t h a t o n a n d o ff t im e s a r e a n d lo w e r fr e q u e n c ie s . c h a n g in g t h e d u t y c y c le o f t h e P W g o n t h e m o t o r y o u u s e , y o u w ill m o t o r w ill n o t r u n a t a ll, o w in g t o o rs . O b s e rv e th e P W M o u tp u t o n a s in d ic a t e d in t h e p r o g r a m . T r y a M , it s th e ls o n 4 .4 .5 Servo Control A s e rv o is a s m a ll ro ta ry p o s itio n c o n tro l d ev ic e , o fte n u s e d in ra d io -co n tro lle d c a rs a n d a irc ra ft to c o n tro l th e a n g u la r p o s itio n o f v a ria b le s s u c h a s s te e rin g , e lev a to rs a n d ru d d e rs . S e rv o s a re n o w p o p u la r in c e rta in ro b o tic a p p lic a tio n s . T h e s e rv o s h a ft c an b e p o s itio n e d a t s p e c ific a n g u la r p o s itio n s b y s en d in g th e s e rv o a P WM s ig n a l. A s lo n g a s th e m o d u la te d s ig n a l ex is ts o n th e in p u t lin e , th e s erv o w ill m ain ta in th e a n g u la r p o s itio n o f th e s h a ft. A s th e m o d u la te d s ig n a l c h a n g es , th e a n g u la r p o s itio n o f th e s h a f t c h a n g e s . T h is is illu s tr a te d in F ig u r e 4 .9 . M a n y s e r v o s u s e a P WM s ig n al w ith a 2 0 ms p erio d , a s is s h o w n h ere . In th is ex amp le, th e p u lse w id th is m o d u la te d f r o m 1 .2 5 m s to 1 .7 5 m s to g iv e th e f u ll 1 8 0 d e g r e e r a n g e o f th e s e r v o . C o n n e c t a s e r v o to th e m b e d a s in d ic a te d in F ig u r e 4 .1 0 . T h e s e r v o r e q u ir e s a h ig h e r c u r r e n t th a n th e u n iv e rs a l s e ria l b u s (U S B ) s ta n d a rd c a n p ro v id e , s o it is e s s e n tia l th a t y o u p o w e r 2 0 ms 0 d eg rees 1 .2 5 m s 0 1 .5 m s 1 .7 5 m s F ig u r e 4 .9 : S e r v o c h a r a c t e r is t ic s 9 0 d eg rees 1 8 0 d eg rees Chapter 4 V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 + 6 V B A T 1 6 m b e d M ic r o c o n tr o lle r 5 S V 1 6 v G n d V in V b n R P V V M 6 v 0 v 7 2 + 6 V ( a ) C ir c u it D ia g r a m ( b ) C o n s tr u c tio n D e ta il F ig u r e 4 .1 0 : U s in g P W M t o d r iv e a s e r v o it u sin g an ex tern al su p p ly . A 4 AA (6 V) serv o . No te th at th e mb ed itself can still b e s p ack v o ltag e lies with in th e p ermissib le in p u th e mb ed co u ld b e su p p lied fro m th e b attery th e in c o m in g 6 V to th e 3 .3 V th a t it r e q u ir n b attery p u p p lied f t v o ltag e p ack , th es. ack m ro m th ran g e ro u g h eets th e su p p ly req u iremen t o f th e e U S B . A lte rn a tiv e ly , b e c a u s e th e f o r p in 2 m e n tio n e d in F ig u r e 2 .1 , th is p in . Th e mb ed th en reg u lates E x e r c is e 4 .7 C re a te P W M F ig u r e m o v e s 4 .4 .6 We c ex am so n g Lo n d a n e w p r p e r io d t o 4 .9 , a n d th e s e rv o o je c t a 2 0 m s o b s e rv s h a ft n d . T e t fro w r it e a p r o g r a m ry a n u m b e r o f d h e s e r v o ’s p o s it io m o n e lim it t o t h t h a t s e t s a P W M o u t p u t o n p in 2 1 . S e t t h e iffe r e n t d u t y p e r io d s , t a k in g v a lu e s fr o m n . T h e n w r it e a p r o g r a m t h a t c o n t in u a lly e o th e r. n O u t p u t t in g t o a P ie z o T r a n s d u c e r an u se p le we called o n call th e PWM so u se it to so u ‘Oran g es an d a p articu lar u rce simp ly n d a p iezo Lemo n s’. messag e. If Oran -ges an d as a v ariab le tran sd u cer an d Th is so n g ima y o u can read freq p la g in e mu s le-mon s, say th e u en y th s th ic y cy e at o u b ells of F ig u r e 4 .1 1 : T h e ‘O ra n g e s a n d L e m o n s ’ tu n e sig n al g en start o f an th e b ells o may reco S t. erato r. In o ld Lo n d f each ch g n ize th e Cle-men t 's th is o n fo lk u rch in tu n e in A n a lo g O u t p u t 7 3 T a b le 4 .3 : F r e q u e n c ie s o f n o t e s u s e d in t u n e W o r d / s y lla b le M u s ic a l n o t e O ra n - E F re q u e n c y (H z ) B e a ts 6 5 9 1 g e s C # 5 5 4 a n d E 6 5 9 1 1 le - C # 5 5 4 m o n s, A 4 4 0 1 sa y B 4 9 4 ½ th e C # 5 5 4 ½ b e lls D 5 8 7 1 o f B 4 9 4 S t E 6 5 9 C le m - C # 5 5 4 e n t’s A 4 4 0 1 1 1 1 2 F ig u re 4 .1 1 ; if y o u c a n n o t, d o n ’t w o r r y ! Yo u ju s t n e e d to k n o w th a t a n y n o te th a t is a min im (‘h alf n o te’ in th e USA) lasts twice as lo n g as a cro tch et (‘q u arter n o te’ in th USA), wh ich in tu rn lasts twice as lo n g as a q u av er (‘eig h th n o te’ in th e USA). Pu t an o th way , a cro tch et lasts o n e b eat, a min im two , an d a q u av er a h alf. Th e p attern fo r th e mu s is a s s h o w n in Ta b le 4 .3 . N o te th a t h e re w e a r e s im p ly u s in g th e P W M a s a v a r ia b le fre q u e n cy s ig n al s o u rce, a n d n o t actu ally mo d u latin g th e p u ls e wid th as a p ro p o rtio n o freq u en cy at all. e er ic f C r e a te a n e w p r o g r a m a n d e n te r P r o g r a m E x a m p le 4 .7 . T h is in tr o d u c e s a n im p o rtan t n ew C featu re, th e a rra y. If y o u are u n familiar with th is, th en read th e r e v ie w in S e c tio n B .8 .1 . T h e p r o g ra m u s e s tw o a r r a y s , o n e d e fi n e d f o r f r e q u e n c y d ata, th e o th er fo r b eat len g th . Th ere are 1 2 v alu es in each , fo r each o f th e 1 2 n o tes in th e tu n e. Th e p ro g ram is stru ctu red ro u n d a fo r lo o p , with v ariab le i as co u n te r. As i in cremen ts, each array eleme n t is selected in tu rn . N o tic e th at i is set ju st to reach th e v alu e 1 1 ; th is is b ecau se th e v alu e 0 ad d re ss es th e first e le men t in each array , an d th e v alu e 1 1 h en ce ad d re ss e s th e twelfth . F ro m th e freq u e n cy a rray th e PWM p erio d is c alcu la ted an d set, alway s with a 5 0 % d u ty ratio . Th e b eat arra y d etermin es h o w lo n g eac h n o te is h eld , u sin g th e w a it fu n ctio n . C c o d e fe a tu re / * P r o g r a m E x a m p l e 4 . 7 : * / # i n c l u d e " m b e d . h " P w m O u t b u z z e r ( p 2 1 ) ; P l a y s t h e t u n e " O r a n g e s a n d L e m o n s " o n a p i e z o b u z z e r , u s i n g P W M 7 4 Chapter 4 f l o a t f f l o a t b i n t m a i w h i l e f o r b b u z w a i } } } r e e a n ( ( ( u z z e t ( q u e t [ ] ) { 1 ) i n t z e r r = 0 0 . 4 / / f r e q u e n c y a r r a y n c y [ ] = { 6 5 9 , 5 5 4 , 6 5 9 , 5 5 4 , 4 4 0 , 4 9 4 , 5 5 4 , 5 8 7 , 4 9 4 , 6 5 9 , 5 5 4 , 4 4 0 } ; = { 1 , 1 , 1 , 1 , 1 , 0 . 5 , 0 . 5 , 1 , 1 , 1 , 1 , 2 } ; / / b e a t a r r a y { i . p . 5 * b = 0 ; i < = 1 1 ; i + + ) { e r i o d ( 1 / ( 2 * f r e q u e n c y [ i ] ) ) ; ; / / s e t d u t y e a t [ i ] ) ; / / h o l d f o r / / s e t P W M c y c l e b e a t p e r i o d p e r i o d P r o g r a m E x a m p le 4 .7 ‘ O r a n g e s a n d L e m o n s ’ p r o g r a m Co mp ile th e p ro g ram an d d o wn lo ad . Co n n ect th e p iezo tran sd u cer b etween p in s 1 an d 2 1 , an d th e s e q u e n c e s h o u ld p la y o n r e s e t. T h e tr a n s d u c e r s e e m s v e r y q u ie t w h e n h e ld in a ir. Yo u c a n in crease th e v o lu me sig n ifican tly b y fix in g o r h o ld in g it to a flat su rface su ch as a tab le to p . n E x e r c is e 4 .8 T r y t h e fo llo w in g : 1 . M a k e t h e ‘O r a n g e s a n d L e m o n s ’ s e q u e n c e p la y a n o c t a v e fre q u e n c y o f e a c h n o te . 2 . C h a n g e t h e t e m p o b y m o d ify in g t h e m u lt ip lie r in t h e w a it 3 . ( F o r t h e m o r e m u s ic a lly in c lin e d .) C h a n g e t h e t u n e , s o t h a lin e o f ‘T w in k le T w in k le L it t le S t a r ’. T h is u s e s t h e s a m e n o t e o f fre q u e n c y 6 9 9 H z . T h e tu n e s ta rts o n A . B e c a u s e th e re c o n s id e r p u t t in g a s m a ll p a u s e b e t w e e n e a c h n o t e . h ig h e r b y d o u b lin g t h e c o m m a n d . t t h e m b e d p la y s t h e fi r s t s , e x c e p t it a ls o n e e d s F # , a re re p e a te d n o te s , n C h a p t e r R e v ie w • • • • • • A d ig ital-to -an alo g co n v erter (DAC) co n v erts an in p u t b in ary n u mb er to an o u tp u t an alo g v o ltag e, wh ich is p ro p o rtio n al to th at in p u t n u mb er. DACs are wid ely u sed to create co n tin u o u sly v ary in g v o ltag es, fo r ex amp le to g en erate an alo g wav efo rms. Th e mb ed h as a sin g le DAC, an d an asso ciated set o f lib rary fu n ctio n s. Pu lse wid th mo d u latio n (PWM) p ro v id es a way o f co n tro llin g certain an alo g q u an tities, b y v ary in g th e p u lse wid th o f a fix ed freq u en cy rectan g u lar wav efo rm. PWM is wid ely u sed fo r co n tro llin g flo w o f electrical p o wer, fo r ex amp le LED b rig h tn ess o r mo to r co n tro l. T h e m b e d h a s s ix p o s s ib le P W M o u tp u ts . T h e y c a n a ll b e in d iv id u a lly c o n tr o lle d , b u t m u s t all sh are th e same freq u en cy . A n a lo g O u t p u t 7 5 Q u iz 1 . 2 . A 7 (a) (b ) (c) (d ) Wh d ec Wh (a) (b ) (c) Wh 3 . 4 . - b it D A C o b e y s E q u a tio n 4 .1 , a n d h a s a v o lta g e r e f e r e n c e r a n g e o f 2 .5 6 V. Wh at is its reso lu tio n ? Wh at is its o u tp u t if th e in p u t is 1 0 0 0 1 0 1 ? Wh at is its o u tp u t if th e in p u t is 0 x 2 A? W h a t is its d ig ita l in p u t in d e c im a l a n d b in a r y if its o u tp u t r e a d s 0 .4 8 V ? at is th e mb ed ’s DAC reso lu tio n an d wh at is th e smallest an alo g v o ltag e step in crease o r rease wh ich can b e o u tp u t fro m th e mb ed ? at is th e o u tp u t o f th e LPC1 7 6 8 DAC, if its in p u t d ig ital wo rd is: 0 0 0 0 0 0 1 0 0 0 0 x 8 0 1 0 1 0 0 0 1 0 0 0 ? at o u tp u t v o ltag es will b e read o n a DVM wh ile th is p ro g ram lo o p ru n s o n th e mb ed ? w h i l e ( 1 ) { f o r ( i = 0 ; i < 1 ; i = i + 0 . 2 ) { A o u t = i ; w a i t ( 0 . 1 ) ; } } 5 . 6 . 7 . 8 . 9 . Th e wav efo rm Wh at are th e a actu ato rs? A PWM d ata s wid th ? A PWM d ata cy cle? Th e PWM o n wav efo rm? in Q u e s tio n 5 g iv e s a c ru d e s a w to o th . W h a t is its p e rio d ? d v an tag es o f u sin g p u lse wid th mo d u latio n (PWM) fo r co n tro l o f an alo g tream h as a freq u en cy o f 4 k Hz an d a d u ty cy cle o f 2 5 %. Wh at is its p u lse stream h as p erio d o f 2 0 ms an d an o n time o f 1 ms . Wh at is its d u ty an mb ed is set u p with th ese statemen ts. Wh at is th e o n time o f th e P W M 1 . p e r i o d ( 0 . 0 0 4 ) ; / / s e t P W M p e r i o d P W M 1 = 0 . 7 5 ; / / s e t d u t y c y c l e Reference 4 .1 . K e s tn e r, W., E d . ( 2 0 0 5 ) . T h e D a ta C o n v e r s io n H a n d b o o k . A n a lo g D e v ic e s I n c . N e w n e s . C H A P T E R 5 A n a lo g In p u t C h a p t e r O u t lin e 5 .1 A n a lo g - t o - D ig it a l C o n v e r s io n 5 .1 5 .1 5 .1 5 .1 .1 T .2 R .3 S .4 A h e A n a lo g - t o - D ig it a a n g e , R e s o lu t io n a n a m p lin g F r e q u e n c y n a lo g In p u t w it h t h 7 7 l C o n v e rte r 7 8 d Q u a n t iz a t io n 8 1 e m b e d 8 2 7 9 5 .2 C o m b in in g A n a lo g In p u t a n d O u t p u t 8 2 5 .2 .1 C o n t r o llin g L E D B r ig h t n e s s b y V a r ia b le V o lt a g e 5 .2 .2 C o n t r o llin g L E D B r ig h t n e s s b y P W M 8 4 5 .2 .3 C o n t r o llin g P W M F r e q u e n c y 8 4 5 .3 P r o c e s s in g D a t a f r o m A n a lo g In p u t s 8 6 5 .3 .1 D is p la y in g V a lu e s o n t h e C o m p u t e r S c r e e n 5 .3 .2 S c a lin g A D C O u t p u t s t o R e c o g n iz e d U n it s 5 .3 .3 A p p ly in g A v e r a g in g t o R e d u c e N o is e 8 7 5 .4 S o m e S im p le A n a lo g S e n s o r s 8 2 8 6 8 7 8 8 5 .4 .1 T h e L ig h t - D e p e n d e n t R e s is t o r 8 8 5 .4 .2 In t e g r a t e d C ir c u it T e m p e r a t u r e S e n s o r 5 .5 E x p lo r in g D a t a C o n v e r s io n T im in g 8 9 9 0 5 .5 .1 E s t im a t in g C o n v e r s io n T im e a n d A p p ly in g N y q u is t 5 .6 M C h a p t Q u iz R e fe re in i- P r o je c t : T w o - D im e n s io n a l L ig h t T r a c k in g e r R e v ie w 9 2 9 3 n c e s 9 3 5 .1 A n a lo g -t o -D ig it a l C o n v e r s io n 9 0 9 2 T h e w o r l d a r o u n d t h e e m b e d d e d s y s t e m i s a l a r g e l y a n a l o g o n e , a n d s e n s o r s eo f t e m p e r a t u r e , s o u n d , a c c e le ra tio n , a n d s o o n em o s tly h a v e a n a lo g o u tp u ts . Ye t it is e s s e n tia l fo r th e micro co n tro ller to h av e th ese sig n als av ailab le in d ig ital fo rm. Th is is wh ere th e an alo g to -d ig ital co n v erter (ADC) co mes in . An alo g sig n als can b e rep eated ly co n v erted in to d ig ital rep resen tatio n s, with a reso lu tio n an d at a rate d etermin ed b y th e ADC. Fo llo win g th is an alo g -to -d ig ital co n v ersio n , th e micro co n tro ller can b e u sed to p ro cess o r an aly ze th is in fo rmatio n , b ased o n th e v alu e(s) o f th e an alo g in p u t. F a s t a n d E f f e c t iv e E m b e d d e d S y s t e m s D e s ig n . D O I : 1 0 .1 0 1 6 /B 9 7 8 - 0 - 0 8 - 0 9 7 7 6 8 - 3 .0 0 0 0 5 - 2 Co p y rig h t Ó2 0 1 2 Elsev ier Ltd . All rig h ts reserv ed . 7 7 7 8 5 .1 .1 Chapter 5 T h e A n a lo g -t o -D ig it a l C o n v e r t e r An ADC is an electro n ic circu it wh o se d ig ital o u tp u t is p ro p o rtio n al to its an alo g in p u t. E ffe c tiv e ly , it ‘m e a s u re s ’ th e in p u t v o lta g e a n d g iv e s a b in a ry o u tp u t n u m b e r p ro p o rtio n a l to its s iz e . T h e lis t o f p o s s ib le a n a lo g in p u t s ig n a ls is e n d le s s , in c lu d in g s u c h d iv e rs e s o u rc e s a s au d io an d v id eo , med ical o r climatic v ariab les, an d a h o st o f in d u strially g en erated sig n als. Of th ese, so me, su ch as temp eratu re, h av e a v ery lo w freq u en cy co n ten t. Oth ers, v id eo fo r ex amp le, are v ery h ig h freq u en cy . Owin g to th is h u g e ran g e o f ap p licatio n s, it is n o t su rp risin g to d isco v er th at man y ty p es o f ADC h av e b een d ev elo p ed , with ch aracteristics o p timized fo r th ese d ifferin g ap p licatio n s. Th e ADC almo st alway s o p erates with in a larg er en v iro n men t, o ften called a d ata acq u isitio n s y s te m . S o m e f e a tu r e s o f a g e n e r a l p u r p o s e d a ta a c q u is itio n s y s te m a r e s h o w n in F ig u r e 5 .1 . To th e rig h t o f th e d iag ram is th e ADC itself. Th is h as an an alo g in p u t an d a d ig ital o u tp u t. It is u n d er co mp u ter co n tro l; th e co mp u ter can start a co n v ersio n . Th e co n v ersio n tak es fin ite time, may b e so me micro seco n d s, so th e ADC n eed s to sig n al wh en it h as fin ish ed . Th e o u tp u t d ata can th en b e read . Th e ADC wo rk s with a v o ltag e referen ce, wh ich may b e th o u g h t o f as a ru ler o r tap e measu re. In o n e way o r an o th er th e ADC co mp ares th e in p u t v o ltag e with th e v o ltag e referen ce, an d co mes u p with th e o u tp u t n u mb er d ep en d in g o n th is co mp ariso n . As with so In te rn a l to M ic ro c o n tro lle r Ex tern al to Mic ro c o n tro lle r Clo c k in p u t ADC Mu ltip lex er Tran sd u cer Gen erates s ig n al Co n v erts its An alo g In p u t to D ig ita l Ou tp u t Selects o n e in p u t ch an n el Vo ltag e Referen ce An alo g in p u t to ADC Dig ital Ou tp u t In p u t S e le c t Start Co n v ersio n Co n v ersio n Co mp lete F ig u r e 5 .1 : A n e x a m p le d a t a a c q u is it io n s y s t e m CPU Co n tro l A n a lo g In p u t 7 9 man y d ig ital o r d ig ital/an alo g su b sy stems, th ere is also a clo ck in p u t, a co n tin u o u sly ru n n in g sq u are wav e, wh ich seq u en ces th e in tern al o p eratio n o f th e ADC. Th e freq u en cy set h ere d etermin es h o w rap id ly th e ADC o p erates. On ce we start wo rk in g with an ADC, we u su ally fin d th at we wan t to wo rk with mo re th an o n sig n al. We co u ld ju st u se mo re ADCs, b u t th is is co stly an d tak es u p semico n d u cto r sp ace In stead , th e u su al p ractice is to p u t an an alo g mu ltip lex er in fro n t o f th e ADC. Th is acts a a selecto r switch . Th e u ser can th en select an y o n e o f sev eral in p u ts to th e ADC. If th is is d o n q u ick ly en o u g h , it is as if all in p u ts are b ein g co n v erted at th e same time. Man y micro co n tro llers, in clu d in g th e NXP1 7 6 8 , in clu d e an ADC an d mu ltip lex er o n ch ip . Th e in p u ts to th e mu ltip lex er are co n n ected to micro co n tro ller p in s an d mu ltip le in p u ts can b e u s e d . T h is is a s s h o w n in F ig u r e 5 .1 f o r a 4 - b it m u ltip le x e r. We r e tu r n to s o m e o f th e d e ta il o F ig u r e 5 .1 in C h a p te r 1 4 . 5 .1 .2 e . s e f R a n g e , R e s o lu t io n a n d Q u a n t iz a t io n M a n y A D C s o b e y E q u a tio n 5 .1 , w h e r e Vi is th e in p u t v o lta g e , V r th e r e f e r e n c e v o lta g e , n th e n u mb er o f b its in th e co n v erter o u tp u t, an d D th e d ig ital o u tp u t v alu e. Th e o u tp u t b in ary n u mb er D is an in teg er, an d fo r an n -b it n u mb er can tak e an y v alu e fro m 0 to (2 n 1 ). Th e in te r n a l A D C p r o c e s s e ff e c tiv e ly r o u n d s o r tr u n c a te s th e c a lc u la tio n in E q u a tio n 5 .1 to p ro d u ce an in teg er o u tp u t. Clearly , th e ADC can n o t ju st co n v ert an y in p u t v o ltag e, b u t h as max imu m an d min imu m p ermissib le in p u t v alu es. Th e d ifferen ce b etween th is max imu m an d m in im u m is c a lle d th e r a n g e . O f te n th e m in im u m v a lu e is 0 V, s o th e r a n g e is th e n ju s t th e max imu m p o ssib le in p u t v alu e. An alo g in p u ts th at ex ceed th e max imu m o r min imu m p ermissib le in p u t v alu es are lik ely to b e d ig itized as th e max imu m an d min imu m v alu es r e s p e c tiv e ly , i.e . a lim itin g ( o r ‘ c lip p in g ’ ) a c tio n ta k e s p la c e . T h e in p u t r a n g e o f th e A D C is d irectly lin k ed to th e v alu e o f th e v o ltag e referen ce; in man y ADC circu its th e ran g e is actu ally eq u al to th e referen ce v o ltag e. D ¼ E q u a tio n 5 .1 is r e p r e s e n te d in v o ltag e is g rad u a lly in crea se d A D C ’s o u tp u t is in itia lly 0 0 0 . I w ill ta k e th e v a lu e 0 0 1 . A s th e s o m e p o in t it r e a c h e s 1 1 1 , i.e . v a lu e. T h e in p u t m ay b e in c re Vi 2 Vr n 5 .1 g r a p h ic a l f o r m in F ig u r e 5 .2 , f o r a 3 - b it c o n v e r te r. I f th e in p u fro m 0 V a n d th e c o n v e rter is ru n n in g c o n tin u o u s ly , th e n th e f th e in p u t s lo w ly in crea se s, th e re co me s a p o in t w h e n th e o u tp u in p u t in creases fu rth er, th e o u tp u t ch an g es to 0 1 0 , an d so o n . A 7 in d e c ima l, o r (2 3 1 ). T h is is th e m ax im u m p o s s ib le o u tp u as e d fu rth e r, b u t it c a n n o t fo rc e a n y in c re a s e in o u tp u t v a lu e. A s F ig u r e 5 .2 d e m o n s tr a te s , b y c o n v e r tin g a n a n a lo g s ig n a l to d ig ita l, w e r u n th e r is k o f ap p ro x imatin g it. Th is is b ecau se an y o n e d ig ital o u tp u t v alu e h as to rep resen t a small ran g e o f a n a lo g in p u t v o lta g e s , i.e . th e w id th o f a n y o f th e s te p s o n th e ‘ s ta ir c a s e ’ o f F ig u r e 5 .2 . F o r t t t t 8 0 Chapter 5 D (d ig ital o u tp u t) 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 0 1 0 0 0 1 0 0 0 V 0 V r i (an alo g in p u t) F ig u r e 5 .2 : A 3 - b it A D C c h a r a c t e r is t ic ex amp le, th e d ig ital o u tp u t 0 0 1 in th e fig u re mu st rep resen t a n y an alo g v o ltag e alo n g th e step th at it rep resen ts. If th e o u tp u t v alu e o f 0 0 1 is p recisely co rrect fo r th e in p u t v o ltag e at th e mid d le o f th e step , th en th e g reatest erro r o ccu rs at eith er en d o f th e step . Th is is called q u a n tiza tio n erro r. Fo llo win g th is lin e o f reaso n in g , th e g reatest q u an tizatio n erro r is o n e h alf o f th e s te p w id th , o r h a lf o f o n e le a s t s ig n ifi c a n t b it (L S B ) e q u iv a le n t o f th e v o lta g e s c a le . Clearly , th e mo re step s th ere are rep resen tin g th e ran g e, th e n arro wer th ey will b e, an d h en ce th e q u an tizatio n erro r is red u ced . Mo re step s are o b tain ed b y in creasin g th e n u mb er o f b its in th e ADC p ro cess. Th is in ev itab ly in creases th e co mp lex ity an d co st o f th e ADC, an d also o ften th e time it tak es to co mp lete a co n v ersio n . As an ex a d ig ital sig 3 .3 /2 5 6 ¼ is co n cern o f 3 .3 /2 1 2 mp le, if we wa n al, th en th ere 1 2 .8 9 m V, a n d e d , F ig u r e 2 .3 , o r 0 .8 m V; th n t to co n v ert an an alo g sig n al a r e 2 5 6 ( i.e . 2 8 ) d is tin c t o u tp th e wo rst case q u an tizatio n e sh o ws th at th e LPC1 7 6 8 ADC e wo rst case q u an tizatio n erro th at u t v rro r is 1 r is h a s a r a n g e 0 e3 . 3 V alu es. Each step h as is 6 .4 5 m V. A s f a r a 2 b it. Th is lead s to a th e r e f o r e 0 .4 m V. to an 8 -b it a wid th o f s th e mb ed step wid th Fo r man y ap p licatio n s an 8 , 1 0 o r 1 2 -b it ADC allo ws su fficien t reso lu tio n ; it all d ep en d s o n th e req u ired accu racy . In certain au d io ap p licatio n s listen in g tests h av e d emo n strated th at 1 6 b it reso lu tio n is ad eq u ate; imp ro v ed q u ality can , h o wev er, b e n o ticed u sin g 2 4 -b it co n v ersio n . All o f th is a referen ce v o h av e n o n -lin b rin g th eir u ssu mes th at all o th er asp ects o f th e ADC ar ltag e can b e in accu rate o r can d rift with temp earities. Fu rth ermo re, d ifferen t meth o d s o f n iq u e in accu racies to th e eq u atio n . Referen c e p er eratu an alo e 5 .1 fect, wh ich re, an d th e s g -to -d ig ital d iscu sses in th ey are taircase co n v ers d etail a n o t. Th e p attern can io n each n u mb er o f A n a lo g In p u t an alo g slo p e’ Discu s u n d ers 5 .1 .3 -to -d an d sin g tan d ig ‘d th th ital co n v ers elta-sig ma’ e sp ecific d e co n cep ts io n d meth esig n o f d a es o d o ta ig n s, in clu d in g , s, wh ich all h av f th e ADC sy ste co n v ersio n an d ‘s u c c e s s iv e a p p ro e th eir o wn ad v an m, h o wev er, is n o imp lemen tin g th e 8 1 x imatio n ’, ‘flash ’, ‘d u al tag es an d in accu racies. t n ecessary fo r u s to mb ed ’s ADC. S a m p lin g F r e q u e n c y Wh en co n v ertin g an th e accu racy d efin ed accu rate th e d ig ital d samp lin g freq u en cy . an alo g sig n al b y th e reso lu ata will b e. S Th is is illu str to d tio n amp ated ig ital, o f th e lin g is in Fig a ‘samp le’ is tak en rep eated ly an d q u an tized to ADC. Th e mo re samp les tak en , th e mo re g en erally d o n e at a fix ed freq u en cy , called th e u r e 5 .3 . Th e samp lin g freq u en cy d ep en d s o n th e max imu m freq u en cy o f th e sig n al b ein g d ig itized . If th e samp lin g freq u en cy is to o lo w th en rap id ch an g es in th e an alo g sig n al may n o t b e rep resen ted in th e resu ltin g d ig ital d ata. Th e Ny q u ist samp lin g criterio n states th at th e samp lin g freq u en cy mu st b e at least d o u b le th at o f th e h ig h est sig n al freq u en cy . Fo r ex amp le, th e h u man au d ito ry sy stem is k n o wn to ex ten d u p to ap p ro x imately 2 0 k Hz, so stan d ard au d io C D s a r e s a m p le d a n d p la y e d b a c k a t 4 4 .1 k H z in o r d e r to a d h e r e to th e N y q u is t s a m p lin g criterio n . If th e samp lin g criterio n is n o t satisfied , th en a p h en o men o n called a lia sin g o ccu rs ea n e w lo w e r f r e q u e n c y is g e n e r a te d . T h is is illu s tr a te d in F ig u r e 5 .4 a n d d e m o n s tr a te d la te r in th e ch ap ter. Aliasin g is v ery d amag in g to a sig n al an d mu st alway s b e av o id ed . A co mmo n V time samp les F ig u r e 5 .3 : D ig it iz in g a s in e w a v e reco n stru cted sig n al V time samp les o rig in al sig n al F ig u r e 5 .4 : T h e e ffe c t o f a lia s in g 8 2 Chapter 5 ap p ro ach is to u se an a n ti-a lia sin g fi lter, wh ich limits all sig n al co mp o n en ts to th o se th at satisfy th e samp lin g criterio n . 5 .1 .4 Fig p ro Tab (as u r g r le it 5 .2 A n a lo g In p u t w it h t h e m b e d e 2 .1 s h o w ammin g in 5 .1 . I t is u wo u ld b e s u s th at th e mb terface (API) s sefu l to n o te th at th e ADC o u ed h as u u mmary at th e A tp u t) o r p to six an alo , fo llo win g a DC o u tp u t is as a flo atin g g i n p u t s , o n p i n s 1 5 e2 0 . T h e a p p l i c a t i o n p attern th at is q u ite familiar, is sh o wn in av ailab le eith er in u n sig n ed b in ary fo rm p o in t n u mb er. C o m b in in g A n a lo g In p u t a n d O u t p u t Th e ADC is an in p u t d ev ice, wh ich tran sfers d ata in to th e micro co n tro ller. If we u se it o n its o wn , we will h av e n o id ea wh at v alu es it h as created . We n o w th erefo re g o o n to d o two th in g s to mak e th at d ata v isib le. We will first u se th e ADC o u tp u t v alu es to immed iately co n tro l an o u tp u t v ariab le, fo r ex amp le th e d ig ital-to -an alo g co n v erter (DAC) o r p u lse wid th mo d u latio n (PWM). We will later tran sfer its o u tp u t v alu es to th e PC screen , an d ex p lo re so me measu remen t ap p licatio n s. 5 .2 .1 Let u b rig h will u straig C o n t r o llin g L E D B r ig h t n e s s b y V a r ia b le V o lt a g e s star tn ess se a p h t to t with a simp le p o f a lig h t-emittin o ten tio meter to g th e an alo g o u tp u ro g ram wh ich read s th e an alo g in p u t, an d u ses it to co n tro l th e g d io d e (L E D ) b y v a ry in g th e v o lta g e d riv e to th e L E D . H e re , w e en erate th e an alo g in p u t v o ltag e, an d will th en p ass th e v alu e read t. Co n n ect u p th e circu it o p o ten tio meter b etween 0 a n ew p ro g ram an d co p y u p th e an alo g in p u t an d f Fig an d in to o u tp / * * / # i A n A n U s e s P r o g r a m E x a m p l e 5 . 1 : n c l u d e " m b e d . h " a l o g O u t A o u t ( p 1 8 ) ; a l o g I n A i n ( p 2 0 ) i n t m a i n ( ) { w h i l e ( 1 ) { A o u t = A i n ; u r e 5 .5 a . T h is u 3 .3 V. T h e L E D it th e v ery simp u t, an d th en co n a n a l o g / / d e f i n e s / / d e f i n e s / / t r a n s f e r i n p u t a n a l o g a n a l o g a n a l o g t o ses p is co le co tin u o in n n d e u s 2 0 as th e an alo ected to p in 1 8 o f Pro g ram Ex ly tran sfers th e c o n t r o l L E D g in p u t, co , th e an alo g a m p le 5 .1 . in p u t to th b r i g h t n e s s , n n ectin g th e o u tp u t. Start Th is ju st sets e o u tp u t. t h r o u g h D A C o u t p u t o u t p u t o n P i n 1 8 i n p u t o n P i n 2 0 i n v a l u e t o a n a l o g o u t , b o t h a r e } } P r o g r a m E x a m p le 5 .1 C o n t r o llin g L E D b r ig h t n e s s b y v a r ia b le v o lt a g e t y p e f l o a t A n a lo g In p u t 8 3 T a b le 5 .1 : A P I s u m m a r y f o r a n a lo g in p u t F u n c t io n U s a g e A n a l o g I n C r e a t e a n A n a lo g In o b je c t , c o n n e c t e d t o t h e s p e c ifi e d p in r e a d R e a d t h e i n p u t v o l t a g e , r e p r e s e n t e d a s a fl o a t i n t h e r a n g e ( 0 . 0 e1 . 0 ) r e a d _ u 1 6 R e a d t h e i n p u t v o l t a g e , r e p r e s e n t e d a s a n u n s i g n e d s h o r t i n t h e r a n g e ( 0 x 0 e0 x F F F F ) Co mp ile th e p ro g ram a p o ten tio meter sh o u ld co th ere is a ran g e o f th e p will b e fo llo win g th e cu d riv e v o lta g e is lo w. o wn lo l th e b tio me o f Fig ad rig ter u re to th e mb ed . With th e p ro g h tn e s s o f th e L E D . Yo u w ill ro tatio n wh ere th e LED is o 3 .3 a , a n d th e r e w ill b e v e r y ram ru n n p ro b ab ly ff. Reme little illu in g , th e fin d , h o wev er, th at mb er th at th e LED min atio n wh en th e E x e r c is e 5 .1 M e a s u r e t h e D A C o u t p u t v o lt a g e a t p in 1 8 , a s y o u a d ju s t t h e p o t e n t io m e t e r . Y o u w ill fi n d t h a t w h e n t h is is a b o v e a r o u n d 1 .8 V , t h e L E D w ill b e lit , w it h v a r y in g le v e ls o f b r ig h t n e s s . W h e n it is b e lo w 1 .8 V , t h e L E D n o lo n g e r c o n d u c t s , a n d t h e r e is n o illu m in a t io n . n ( a ) c ir c u it d ia g r a m 1 0 k G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 ( b ) c o n s tr u c tio n d e ta il m b e d M ic r o c o n tr o lle r n n d d n tro o ten rv e V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 5 .5 : A p o t e n t io m e t e r c o n t r o llin g L E D b r ig h t n e s s 8 4 Chapter 5 5 .2 .2 C o n t r o llin g L E D B r ig h t n e s s b y P W M We c an u se th e p o te n tio d id fo r th e an alo g o u tp u b e co n n ected to th e PW E x a m p le 5 .2 . H e r e , w e / * * / # i P w A n P r o g r a m E x a m p l e meter in p u t to a t. T h e c irc u it o f M o u tp u t o n p in see th e an alo g 5 . 2 : U s e s n c l u d e " m b e d . h " m O u t P W M 1 ( p 2 1 ) ; a l o g I n A i n ( p 2 0 ) ; i n t m w h i P P w a i l e W M W M a i n ( ( 1 1 . 1 = t ( a n a l o g i n p u t / / d e f i n e s { ) { p e r i o d ( 0 . 0 1 0 ) ; A i n ; 0 . 1 ) ; lte r th F ig u r 2 1 .C in p u t a n a l o g e PWM d u ty cy cle, u sin g th e same ap p ro ach a e 5 .5 is u s e d a g a in , e x c e p t th a t th e L E D s h o u ld re a te a n ew p ro g ra m , a n d e n te r th e c o d e o f P ro g v alu e b ein g tran sferred to th e PWM d u ty cy c t o c o n t r o l i n p u t o n P W M P i n d u t y c y c l e , f i x e d p e r i o d t y p e f l o a t s we n o w ram le. 2 0 ) / / s e t P W M p e r i o d / / A n a l o g i n v a l u e t o 1 0 m s b e c o m e s P W M d u t y , b o t h a r e } } P r o g r a m E x a m p le 5 .2 C o n t r o llin g P W M p u ls e w id t h w it h a p o t e n t io m e t e r Th e LED b rig h tn ess sh v ery similar to th e p rev we wo u ld n o rmally n o t we wo u ld b e mo re read 5 .2 .3 o u ld io u s wish y to ag p r to co ain b e co n tro lled o g ram, th e mean co mmit a wh o le mmit a (simp ler b y th e p o s o f d o in g DAC to co an d mo re ten tio meter. Wh ile th e o it is q u ite d ifferen t. In p n tro llin g th e b rig h tn ess o read ily av ailab le) PWM u tco me is ractice, f an LED; so u rce. C o n t r o llin g P W M F r e q u e n c y In stead o f u sin g th e p o ten tio meter to co n tro l th e PWM d u ty cy cle, it can b e u sed to co n tro l th e PWM freq u en cy . Leav e th e LED co n n ected to Pin 2 1 . Create a n ew p ro g ram an d en ter th e c o d e o f P r o g r a m E x a m p le 5 .3 . N o e x tr a c o m p o n e n ts n e e d b e c o n n e c te d to th e m b e d . No tice th at th e PWM p erio d is calcu lated in th e lin e: P W M 1 . p e r i o d ( A i n / 1 0 + 0 . 0 0 1 ) ; / / s e t P W M p e r i o d It is first wo rth n o tin g th at a calcu latio n is p laced wh ere o n e mig h t h av e ex p ected a simp le p arameter to b e p laced . Th is is n o t a p ro b lem fo r C. Th e p ro g ram will first ev alu ate th e ex p ressio n in sid e th e b rack ets, an d th en call th e p e r io d ( ) fu n ctio n . T h is c a lc u la tio n in v o k e s fo r th e fi rs t tim e th e d iv id e o p e ra to r, /. It a ls o ra is e s th e th o rn y little q u estio n , wh ich all ch ild ren face wh en th ey learn arith metic, o f th e o rd er in wh ich o p erato rs s h o u ld b e e v a lu a te d . I n C th is is v e r y c le a r ly d e fi n e d , a n d c a n b e s e e n b y c h e c k in g Ta b le B .5 in Ap p en d ix B. Th is sh o ws a p reced en ce fo r each o p erato r, with / h av in g p reced en ce 3 , an d þ h a v in g p re c e d e n c e 4 . T h e re fo re , th e d iv is io n w ill b e e v a lu a te d b e fo re th e a d d itio n , a n d th e re will b e n o u n certain ty in ev alu atin g th e ex p ressio n . Th e v alu es u sed mean th at th e min imu m p e r io d , w h e n A in is z e r o , is 0 .0 0 1 s ( i.e . 1 0 0 0 H z ) . T h e m a x im u m is w h e n A in is 1 , le a d in g to a p e r io d o f 0 .1 0 1 s , i.e . a r o u n d 1 0 H z . C c o d e fe a tu re A n a lo g In p u t / * * / # i P w A n P r o g r a m E x a m p l e 5 . 3 : U s e s a n a l o g i n p u t t o c o n t r o l P W M 8 5 p e r i o d n c l u d e " m b e d . h " m O u t P W M 1 ( p 2 1 ) ; a l o g I n A i n ( p 2 0 ) ; i n t m w h i P P w a i l e W M W M a i n ( ( 1 1 . 1 = t ( ) ) { p e 0 . 0 . { r i o d ( A i n / 1 0 + 0 . 0 0 1 ) ; 5 ; 5 ) ; / / / / s e t s e t P W M p e r i o d d u t y c y c l e } } P r o g r a m E x a m p le 5 .3 C o n t r o llin g P W M f r e q u e n c y w it h a p o t e n t io m e t e r O b s e r v e th e w a v e f o r m o n a n o s c illo s c o p e , s e ttin g th e tim e b a s e in itia lly to 5 m s /d iv . Yo u sh o u ld b e ab le to see th e freq u en cy ch an g e as th e p o ten tio meter is ad ju sted . n E x e r c is e 5 .2 1 . A d ju s t t h e v a lu e s in o u tp u t. 2 . A t w h a t fre q u e n c y o n ? M e a s u r e t h is a b e t w e e n d iffe r e n t p u s to k n o w a t w h a im a g e is c o n t in u o u o s c illo s c o p e t r a c e s t h e P W M p e r io d c a lc u la t io n t o g iv e d iffe r e n t r a n g e s o f fr e q u e n c y d o e s th e L E D a p p e a r n o t to fl a s h s c a r e fu lly a s y o u c a n , a n d s e e if e o p le . T h is is a n im p o r t a n t q u e s t t fr e q u e n c y w e c a n ‘t r ic k ’ t h e e y e s , fo r e x a m p le in c o n v e n t io n a l r a a n d m u lt ip le x e d L E D d is p la y s . , b u t th e p io n , a in t o s te r s s e e m s t o b e c o n t in e r c e iv e d fr e q u e n c y s k n o w in g it s v a lu e t h in k in g t h a t a fl a s c a n t e le v is io n s c r e e u o u s ly v a r ie s a llo w s h in g n s , n T h e 0 .5 s d e la y in P r o g r a m E x a m p le 5 .3 is a d d e d to th e lo o p s o th a t e a c h n e w P W M p erio d is allo wed to b e imp lemen ted b efo re th e n ex t u p d ate. If it was o mitted th en th e PWM wo u ld p o te n tially b e u p d ated rep e ated ly with in e a c h cy c le , wh ich wo u ld le ad to a larg e amo u n t o f jitter in th e o u tp u t (try re mo v in g th e d elay to s ee th e effect). No tice th at th e re c an b e d is co n tin u itie s in th e PWM o u tp u t a s th e fre q u e n cy v a lu es are u p d ate d . With care (an d esp ecially if y o u are u sin g a sto rag e o scillo sco p e) y o u can see th is as th e PWM is u p d a te d e v e r y 0 .5 s . T h is is o n e r e a s o n w h y it is g o o d to fi x th e f r e q u e n c y f o r a P W M sig n al. n E x e r c is e 5 .3 C o n c o n s e rv th e n e c t th n e c te d o p o s it fu ll r a n e s e a s in io n . g e o rv o F ig S c a f s e to th e m b e d a s u r e 5 .5 a . W r it e le v a lu e s s o t h a r v o p o s it io n c h in d ic a p ro t th e a n g e s a t e d in F ig u r e 4 .1 0 a , w it h t h e p o t e n t io m e t e r g r a m w h ic h a llo w s t h e p o t e n t io m e t e r t o c o n t r o l fu ll r a n g e o f p o t e n t io m e t e r a d ju s t m e n t le a d s t o . n 8 6 Chapter 5 5 .3 P r o c e s s in g D a t a fr o m A n a lo g In p u t s 5 .3 .1 D is p la y in g V a lu e s o n t h e C o m p u t e r S c r e e n We tu rn n o w to th e seco n d way o f mak in g u se o f th e ADC o u tp u t, p ro mised at th e b eg in n in g o f S e c tio n 5 .2 . I t is p o s s ib le to r e a d a n a lo g in p u t d a ta th r o u g h th e A D C , a n d th e n p r in t th e v a lu e to th e P C s c r e e n . T h is is a v e r y im p o r ta n t s te p f o r w a r d , a s it g iv e s th e p o s s ib ility o f d isp lay in g an y d ata we are wo rk in g with o n th e co mp u ter screen . To d o th is, we n eed to c o n fi g u re b o th m b e d a n d h o s t c o m p u te r to b e re a d y to s e n d a n d re c e iv e d a ta , a n d w e n e e d th e h o st co mp u ter to b e ab le to d isp lay th at d ata. Fo r th e co mp u ter a termin al emu lato r is req u ired . Th e mb ed site reco mmen d s u se o f Tera Term fo r th is p u rp o se; Ap p en d ix E d escrib es h o w to set th is u p . Th e mb ed can b e mad e to ap p ear to th e co mp u ter as a serial p o rt, c o m m u n ic a tin g th ro u g h th e u n iv e rs a l s e ria l b u s (U S B ) c o n n e c tio n . It lin k s u p w ith th e USB th ro u g h o n e o f its o wn asy n ch ro n o u s serial p o rts. Th is is set u p simp ly b y ad d in g th is p ro g ram lin e: S e r i a l p c ( U S B T X , U S B R X ) ; W r itin g to th e c o m p u te r s c r e e n is th e n a c h ie v e d w ith th e p c .p r in t f ( ) f u n c tio n . E x p la n a tio n s f o r th is a r e g iv e n in S e c tio n 7 .9 .3 . Start a n ew mb e p o ten tio meter co fu n ctio n fo r th e sp ecifiers. Ch eck Sectio n B C c o d e fe a tu re / * P r o g r a m E x a m p l e * / # i n c l u d e " m b e d . h " 5 . 4 : d p ro ject an d n n ected as in first time, alo .9 in A p p e n d R e a d s i n p u t e n te r th e c o d e o f P r o g r a m E x a m p le 5 .4 . L e a v e th e F ig u r e 5 .5 a . N o te th a t th e p r o g r a m u s e s th e p r in t f ( ) n g with so me o f its far-fro m-frien d ly fo rmat ix B fo r so me b ack g ro u n d o n th is. v o l t a g e S e r i a l p c ( U S B T X , U S B R X ) ; A n a l o g I n A i n ( p 2 0 ) ; f l o a t A D C d a t a ; i n t m a i n ( ) { p c . p r i n t f ( " A D C D a t a V a l u e s . \ n \ r " ) ; w h i l e ( 1 ) { A D C d a t a = A i n ; w a i t ( 0 . 5 ) ; p c . p r i n t f ( " % 1 . 3 f \ n \ r " , A D C d a t a ) ; } } t h r o u g h t h e A D C , a n d t r a n s f e r s t o P C t e r m i n a l / / e n a b l e s e r i a l p o r t w h i c h l i n k s t o U S B / / s e n d a n o p e n i n g t e x t m e s s a g e / / s e n d t h e d a t a t h e t e r m i n a l t o P r o g r a m E x a m p le 5 .4 L o g g in g d a t a t o t h e P C Yo u s h o u ld n o w b e a b le to c o m p ile a n d r u n y o u r c o d e to g iv e a n o u tp u t o n Te r a Te r m . I f y o u h a v e p ro b le m s, c h e c k fro m A p p e n d ix E o r th e m b ed s ite th a t y o u h av e s e t u p Te ra Te rm c o rre c tly . A n a lo g In p u t 5 .3 .2 S c a lin g A D C O u t p u t s t o R e c o g n iz e d U n it s Th e d ata d isp lay ed th ro u g h Pro g ram E v o ltag e in p u t. Th ese v alu es can read ily 3 .3 . S u b s titu te th e c o d e lin e s b e lo w in th is, an d to p lace a u n it after th e v o lta A D C w a i p c . p c . d a t t ( 0 p r i p r i 8 7 a = A . 5 ) n t f n t f x a m p le 5 .4 is ju s t a s e t o f n u m b e r s p r o p o r tio n a l to th e b e s c a le d to g iv e a v o lta g e r e a d in g , b y m u ltip ly in g b y to th e w h ile lo o p o f P r o g r a m E x a m p le 5 .4 to d o ju s t g e v alu e. i n * 3 . 3 ; ; ( " % 1 . 3 f " , A D C d a t a ) ; ( " V \ n \ r " ) ; R u n th e a d ju s te d p r o g r a m ; its o u tp u t s h o u ld a p p e a r s im ila r to F ig u r e 5 .6 . Vie w th e m e a s u r e d v o ltag e o n th e PC screen , an d read th e actu al in p u t v o ltag e o n a d ig ital v o ltmeter. Ho w well d o th ey co mp are? 5 .3 .3 A p p ly in g A v e r a g in g t o R e d u c e N o is e I f y o u le a v e P r o g r a m E x a m p le 5 .4 r u n n in g , w ith a fi x e d in p u t a n d v a lu e s d is p la y e d o n Te r a Term, y o u may b e su rp rised to see th at th e measu red v alu e is n o t alway s th e same, b u t v aries a r o u n d s o m e a v e r a g e v a lu e . Yo u m a y a lr e a d y h a v e n o tic e d th a t th e P W M v a lu e in S e c tio n 5 .2 .2 o r 5 .2 .3 a ls o a p p e a r e d to v a r y , e v e n w h e n th e p o te n tio m e te r w a s n o t b e in g m o v e d . Sev eral effects may b e at p lay h ere, b u t almo st certain ly y o u are seein g th e effect o f so me in terferen ce, an d all th e p ro b lems it can b rin g . If y o u lo o k with th e o scillo sco p e at th e ADC in p u t ( i.e . th e ‘ w ip e r ’ o f th e p o te n tio m e te r ) y o u a r e lik e ly to s e e s o m e h ig h - f r e q u e n c y n o is e su p erimp o sed o n th is; ex actly h o w mu ch will d ep en d o n wh at eq u ip men t is ru n n in g n earb y , h o w lo n g y o u r in terco n n ectin g wires are, an d a n u mb er o f o th er th in g s. F ig u r e 5 .6 : L o g g e d d a ta o n T e ra T e rm 8 8 Chapter 5 A v ery simp le first step to imp ro v e th is situ atio n is to av erag e th e in co min g sig n al. Th is sh o u ld h elp to fin d th e u n d erly in g av erag e v alu e an d remo v e th e h ig h -freq u en cy n o ise elemen t. Try in sertin g th e fo r lo o p sh o wn b elo w, rep lacin g th e A D C d a t a = A i n ; lin e in Pro g ram E x a m p le 5 .4 . Yo u w ill s e e th a t th is c o d e f r a g m e n t s u m s 1 0 A D C v a lu e s a n d ta k e s th e ir av erag e. Try ru n n in g th e rev ised p ro g ram an d see wh eth er a mo re stab le o u tp u t resu lts. No te th a t w h ile th is s o rt o f a p p ro a c h g iv e s s o m e b e n e fi t, th e a c tu a l m e a s u re m e n t n o w ta k e s 1 0 times as lo n g . Th is is a v ery simp le ex amp le o f d ig ital sig n al p ro cessin g . f o r ( i n t i = 0 ; i < = 9 ; i + + ) { A D C d a t a = A D C d a t a + A i n * 3 . 3 ; / / s u m 1 0 s a m p l e s } A D C d a t a = A D C d a t a / 1 0 ; / / d i v i d e b y 5 .4 S o m e S im p le A n a lo g S e n s o r s No w sen so o u tp u acro s th at we are eq rs. Th ese ten d t v o ltag e th at s sen so rs th at 5 .4 .1 u ip to can can p ed b e b e co with th e s co n n mmu 1 0 an alo g in p u t, it is ap p ro p imp ler an d mo re trad itio n ected to th e mb ed ADC in n icate with th e mb ed v ia riate to ex p lo re so me simp le an alo g al o n es, wh ich h av e an an alo g p u t. Later in th e b o o k we will co me a d ig ital in terface. T h e L ig h t -D e p e n d e n t R e s is t o r Th e lig h t-d ep en d en t resisto r Wh en lig h t falls o n it, its en b rig h ter th e lig h t, th e mo re co n d u ct electricity , with th e remo v ed th e electro n s p o p b effect is th at as illu min atio n (LDR) is mad e fro m a erg y flip s so me electro electro n s are released . resu lt th at th e resistan ack in to th eir p lace an d in creases, th e LDR re p iece o f ex p o sed semico n d u cto r material. n s o u t o f th e cry stallin e stru ctu re; th e Th ese electro n s are th en av ailab le to ce o f th e material falls. If th e lig h t is th e resistan ce g o es u p ag ain . Th e o v erall sistan ce falls. T h e N O R P 1 2 L D R , m a d e b y S ilo n e x ( R e f e r e n c e 5 .2 ) , is r e a d ily a v a ila b le a n d in e x p e n s iv e . I ts s u m m a r y d a ta is s h o w n in F ig u r e 5 .7 . T h is s h o w s th a t it h a s a r e s is ta n c e w h e n c o m p le te ly d a r k o f a t le a s t 1 .0 M U , f a llin g to a f e w h u n d r e d o h m s w h e n v e r y b r ig h tly illu m in a te d . A n e a s y w a y to c o n n e c t s u c h a s e n s o r is in a s im p le p o te n tia l d iv id e r, g iv in g a v o lta g e o u tp u t; th is is a ls o s h o w n in F ig u r e 5 .7 . T h e v a lu e o f th e s e r ie s r e s is to r, s h o w n h e r e a s 1 0 k U , is c h o s e n to g iv e a n o u tp u t v a lu e o f a p p ro x im a te ly m id -ra n g e fo r n o rm a l ro o m lig h t lev e ls . It c a n b e ad ju sted to mo d ify th e o u tp u t v o ltag e ran g e. Pu ttin g th e LDR at th e b o tto m o f th e p o ten tial d iv id e r, a s s h o w n h e re , g iv e s a lo w o u tp u t v o lta g e in b rig h t illu m in a tio n a n d a h ig h o n e in lo w illu m in a tio n . T h is c a n b e r e v e r s e d b y p u ttin g th e L D R a t th e to p o f th e d iv id e r. T h e L D R is a s im p le , e ffe c tiv e a n d lo w -c o s t lig h t s e n s o r. Its o u tp u t is n o t, h o w ev e r, lin e a r, a n d e a c h d ev ic e te n d s to g iv e s lig h tly d iffe re n t o u tp u t fro m a n o th e r. H e n c e , it is n o t u s u a lly u s e d fo r p recisio n measu remen ts. A n a lo g In p u t 8 9 3 .3 V 1 0 k Vo RL D R 0 V Illu m in a tio n (lu x ) RL D R Vo (W) D a rk ≥ 1 .0 M ≥ 3 .2 7 V 1 0 9 k 1 .5 6 V 1 ,0 0 0 4 0 0 0 .1 3 V F ig u r e 5 .7 : T h e N O R P S 1 2 L D R c o n n e c t e d in a p o t e n t ia l d iv id e r , w it h in d ic a t iv e o u t p u t v a lu e s n E x e r c is e 5 .4 U s in g t h e c ir c u it o f F ig u r e 5 .7 , c o n n e c t a N O R P 1 2 L D R t o t h e m b e d . W r it e a p r o g r a m t o d is p la y lig h t r e a d in g s o n t h e T e r a T e r m s c r e e n . Y o u w ill n o t b e a b le t o s c a le t h e s e in t o a n y u s e fu l u n it . T r y r e v e r s in g r e s is t o r a n d L D R , a n d n o t e t h e e ffe c t . n 5 .4 .2 In t e g r a t e d C ir c u it T e m p e r a t u r e S e n s o r Semico n d u cto r actio n is h ig h ly d e p en d e n t o n temp eratu re, so it is n o t su rp risin g th a t semico n d u cto r temp eratu re sen so rs are mad e . A v ery u sefu l fo rm o f se n so r is o n e wh ic h is c o n ta in e d in a n in te g r a te d c ir c u it, s u c h a s th e L M 3 5 ( F ig u r e 5 .8 ) . T h is a llo w s th e o u tp u t to b e sca led to an imme d ia tely u se fu l v a lu e . Th is d ev ice h as an o u tp u t o f 1 0 mV / C, with o p eratin g temp eratu re fro m 5 5 C to 1 5 0 C. It is th u s immed iately u sefu l fo r a ra n g e o f temp e ratu re-s en sin g a p p lica tio n s. Th e simp lest co n n ectio n fo r th e LM3 5 , wh ic h ca n b e u s e d w ith th e m b e d , is s h o w n in F ig u r e 5 .8 . A r a n g e o f m o r e a d v a n c e d c o n n e c tio n s , f o r ex amp le to o b tain an o u tp u t fo r te mp era tu re s b elo w 0 C, is s h o wn in th e d a tash ee t ( R e f e r e n c e 5 .3 ) . n E x e r c is e 5 .5 D e s ig n , b u ild a n d p r o g r a m a s im p le e m b e d d e d s y s t e m u s in g a n L M 3 5 s e n s o r , w h ic h d is p la y s t e m p e r a t u r e o n t h e c o m p u t e r s c r e e n a n d fl a s h e s a n L E D w h e n e v e r t h e 9 0 Chapter 5 4 V to 2 0 V O u tp u t 1 0 .0 m V / ° C L M 3 5 V s V o G ro u n d F ig u r e 5 .8 : T h e L M 3 5 in t e g r a t e d c ir c u it t e m p e r a t u r e s e n s o r te m p e ra tu re e x c e e d s 3 0 C . T m b e d . W h e n c o n n e c t in g t h e in t h e m b e d b r e a d b o a r d . E a t h a t r e m o t e s e n s in g c a n b e ( e .g . w it h s ilic o n e r u b b e r a t liq u id t e m p e r a t u r e s . H o w w m b e d A D C ? h e V S p in o f s e n s o r , it c a c h t e r m in a l u n d e rta k e n . th e s e n s o r e e ll d o e s t h is t h e s e n s o r c a n b e c o n n e c t e d t o p in n b e p lu g g e d d ir e c t ly in t o a s u it a b le c a n , h o w e v e r , a ls o b e s o ld e r e d t o a If t h e s e w ir e s a r e in s u la t e d a p p r o p n d ), th e n th e s e n s o r c a n b e u s e d to a r r a n g e m e n t e x p lo it t h e in p u t r a n g 3 9 o f th e lo c a t io n w ir e , s o r ia t e ly m e a s u re e o f th e n 5 .5 E x p lo r in g D a t a C o n v e r s io n T im in g Ny q u ist’s samp lin g th eo freq u en cy sig n als. Wh en to k n o w h o w lo n g each d mb ed ADC an d DAC co 5 .5 .1 rem s d esig ata co n v ers u g g n in n v e io n ests th at a slo w ADC will o n ly b e ab le to co n v ert lo wg a carefu lly sp ecified sy stem it is th erefo re v ery imp o rtan t rsio n tak es. Fo r th is reaso n , we will mak e a measu remen t o f times, an d th en p u t Ny q u ist to th e test. E s t im a t in g C o n v e r s io n T im e a n d A p p ly in g N y q u is t P r o g r a m E x a m p le 5 .5 p r o v id e s a v e r y s im p le m e c h a n is m f o r m e a s u r in g c o n v e r s io n tim e s a n d th e n v ie w in g N y q u is t’s s a m p lin g th e o r e m in a c tio n . I t a d a p ts P r o g r a m E x a m p le 5 .1 , b u t p u lses a d ig ital o u tp u t b etween each stag e. En ter th is as a n ew p ro g ram, co mp ile an d ru n . / * P o s c A D C * / # i n A n a A n a D i g f l o r o g r a m E x a m p l e 5 . 5 : I n p u t s s i g n a l t h r o u g h A D C , a n d o u t p u t s t o D A C . V i e w D A C o u t p u t o n i l l o s c o p e . T o d e m o n s t r a t e N y q u i s t , c o n n e c t v a r i a b l e f r e q u e n c y s i g n a l g e n e r a t o r t o i n p u t . A l l o w s m e a s u r e m e n t o f c o n v e r s i o n t i m e s , a n d e x p l o r e s N y q u i s t l i m i t . c l u l o g l o g i t a a t d e " m O u t A I n A i l O u t A D C d a b e o u n ( t e t a ; d . t ( p 2 s t h " p 1 8 ) ; 0 ) ; ( p 5 ) ; / / d e f i n e s / / d e f i n e s a n a l o g a n a l o g o u t p u t o n P i n 1 8 i n p u t o n P i n 2 0 A n a lo g In p u t i n t m a w h i l A t t A t t t t / i n e ( D C e s e s o u e s e s e s e s / w ( ) 1 ) d a t = t = t = t = t = t = t = a i 9 1 { { t a = A i n ; 1 ; 0 ; A D C d a t a ; 1 ; 0 ; 1 ; 0 ; t ( 0 . 0 0 1 ) ; / / s t a r t s A - D c o n v e r s i o n , a n d a s s i g n s a n a l o g / / s w i t c h t e s t o u t p u t , a s t i m e m a r k e r v a l u e / / t r a n s f e r s s t o r e d v a l u e / / a d o u b l e p u l s e , t o m a r k t o D A C , t h e e n d a n d f o r c e s a D - A o f c o n v e r s i o n / / o p t i o n a l e x p l o r e d i f f e r e n t w a i t s t a t e , t o c y c l e t o A D C d a t a c o n v e r s i o n t i m e s } } P r o g r a m E x a m p le 5 .5 E s t im a t in g d a t a c o n v e r s io n t im e s Th is p ro g ram allo ws u s to mak e a n u mb er o f measu remen ts wh ich are o f v ery g reat imp o rtan ce, an d wh ich req u ire carefu l u se o f th e o scillo sco p e. Th e measu remen ts are p r e s e n te d a s E x e r c is e s 5 .6 a n d 5 .7 . n E x e r c is e 5 .6 R u n n in g P r o g r a m E x a o u t p u t ( i.e . p in 5 ) o n r e s u lt s . T h is m a y r e q u t h e p u ls e s if n e c e s s a r y y o u d o n o t n e e d a n y t Y o u w ill b a n d th e d t o - d ig it a l o n th e s e ? o f th e A D t h e s e v a lu m p le 5 .5 , o a n o s c illo s c ir e s o m e p a b y in s e r t in g h in g c o n n e c b s e rv e c a r o p e ea d t ie n c e , a s a w a it w h te d to th e e fu lly t h e w a v e fo r m ig it a l s t o r a g e o s c illo th e y a re v e ry n a rro w ile t h e o u t p u t is h ig h A D C in p u t . d is p la y e s c o p e w p u ls e s . . N o te t d b y th ill g iv e Y o u c a h a t fo r e ‘te s t’ th e b e s t n w id e n t h is t e s t e a b le t o d e t e c t t h e s in g le p u ls e a t t h e e n d o f t h e a n a lo g - t o - d ig it a l c o n v e r s io o u b le o n e a t t h e e n d o f t h e lo o p . M e a s u r e t h e t im e d u r a t io n o f t h e a n a lo g c o n v e r s io n , a n d t h e d ig it a l- t o - a n a lo g c o n v e r s io n . W h a t c o m m e n t c a n y o u m a N o t e t h a t t h e c o n v e r s io n t im e s y o u m e a s u r e a r e n o t t h e a c t u a l c o n v e r s io n t im C a n d D A C ; t h e y in c lu d e a ll a s s o c ia t e d p r o g r a m m in g o v e r h e a d s . K e e p a n o t e e s a s w e a im t o a c c o u n t fo r t h e m la t e r , in E x e r c is e s 5 .7 a n d 1 4 .8 . n , k e e s o f n n E x e r c is e 5 .7 A r m e d w it h t h e k n o w le d g e o f t h e c o n v e r s io n t im e s , c o n n e c t a s ig n a l g e n e r a t o r a s a n in p u t t o t h e A D C . S e t t h e s ig n a l a m p lit u d e s o t h a t it is ju s t u n d e r 3 .3 V p e a k t o p e a k , a n d a p p ly a D C o ffs e t s o t h a t t h e v o lt a g e v a lu e n e v e r g o e s b e lo w 0 V . T h is fa c ilit y is a v a ila b le o n m o s t s ig n a l g e n e r a t o r s . In s e r t t h e w a it ( 0 .0 0 1 ) ; lin e a t t h e e n d o f t h e lo o p ( ‘c o m m e n t e d o u t ’ in P r o g r a m E x a m p le 5 .5 ) . T h is w ill g iv e a s a m p lin g fr e q u e n c y o f a lit t le b e lo w 1 k H z . N y q u is t ’s s a m p lin g t h e o r e m p r e d ic t s t h a t t h e m a x im u m s ig n a l fr e q u e n c y t h a t c a n b e d ig it iz e d w ill b e 5 0 0 H z , fo r t h is s a m p lin g fr e q u e n c y . L e t ’s t e s t it . 9 2 Chapter 5 S t a r t w it h a n in p u t s ig n a l o f a r o u n t h e t w o b e a m s o f t h e o s c illo s c o p e . v e r s io n o f it , s o m e t h in g lik e F ig u r e m illis e c o n d . N o w g r a d u a lly in c r e a s a p p r o a c h N y q u is t ’s lim it t h e o u t p u e q u a ls s a m p lin g fr e q u e n c y , a s t r a ig p r a c t ic e it m a y b e d iffi c u lt t o fi n d t h f u r t h e r , a n a lia s s ig n a l ( a s illu s t r a t e d 2 0 0 H z . O b s e r v e in p u t s ig n a l a n d D A C o u t p u t o n Y o u s h o u ld s e e t h e in p u t s ig n a l a n d a r e c o n s t r u c t e d 5 .3 , w it h a n e w c o n v e r s io n a p p r o x im a t e ly e v e r y e t h e s ig n a l fr e q u e n c y t o w a r d s 5 0 0 H z . A s y o u t b e c o m e s a s q u a r e w a v e . W h e n in p u t fr e q u e n c y h t lin e o n t h e o s c illo s c o p e s h o u ld o c c u r , a lt h o u g h in is c o n d it io n e x a c t ly . A s t h e in p u t fr e q u e n c y in c r e a s e s d in F ig u r e 5 .4 ) a p p e a r s a t t h e o u t p u t . D e c r e a s e t h e d u r a t io n o f t h e w a it fr e q u e n c y . F in a lly , r e m o v e t h e w a it t a k in g p la c e a t t h e fa s t e s t p o s s ib le e a r lie r m e a s u r e m e n t . T h e N y q u is t h a r d w a r e / s o ft w a r e c o n fi g u r a t io n . s ta te , s ta te ra te , lim it t a n d a lt o g w it h h a t y p re e th c o o u d ic e r. n v e n o t a n d T h e d r s io n w fi n d o b s e a ta c t im e is t h rv e th e n e w N y o n v e r s io n s h o u c o r r e s p o n d in g e lim it fo r t h is q u ld to p a is t n o w b e y o u r r t ic u la r n 5 .6 M in i-P r o je c t : T w o -D im e n s io n a l L ig h t T r a c k in g Lig h t-track in g d ev ices are v ery imp o rtan t fo r th e cap tu re o f so lar en erg y . Often th ey o p erate in th ree d imen sio n s, an d tilt a so lar p an el so th at it is facin g th e su n as accu rately as p o ssib le. To start rath er mo re simp ly , create a two -d imen sio n al lig h t track er b y fittin g two LDRs, an g led away fro m each o th er b y aro u n d 9 0 , to a serv o . Co n n ect th e LDRs u sin g th e circu it o f F ig u r e 5 .7 to tw o A D C in p u ts . W r ite a p r o g r a m th a t r e a d s th e lig h t v a lu e s e n s e d b y th e tw o L D R s a n d ro ta te s th e s e rv o s o th a t e a c h is re c e iv in g e q u a l lig h t. T h e s e rv o c a n o n ly ro ta te 1 8 0 . Th is is n o t, h o wev er, u n reaso n ab le, as a su n -track in g sy stem will b e lo cated to track th e s u n f r o m s u n r is e to s u n s e t, i.e . n o t m o r e th a n 1 8 0 . C a n y o u th in k o f a w a y o f m e e tin g th is n eed u sin g o n ly o n e ADC in p u t? C h a p t e r R e v ie w • • • • • An ADC is av ailab le in th e mb ed ; it can b e u sed to It is imp o rtan t to u n d erstan d ADC ch aracteristics, in co n v ersio n time. Ny q u ist’s samp lin g th eo rem mu st b e u n d ersto o d , an d sig n als. Th e samp lin g freq u en cy mu st b e at least tw co mp o n en t in th e samp led an alo g sig n al. Aliasin g o ccu rs wh en th e Ny q u ist criterio n is n o t me to th e d ata. Aliasin g can b e av o id ed b y in tro d u cin g sig n al b efo re it is samp led . Data g ath ered b y th e ADC can b e fu rth er p ro cessed d ig itize an alo g in p u t sig n als. terms o f in p u t ran g e, reso lu tio n an d ap p lied with care wh en samp lin g AC ice th at o f th e h ig h est freq u en cy t; th is can in tro d u ce false freq u en cies an an ti-aliasin g filter to th e an alo g , an d d isp lay ed o r sto red . A n a lo g In p u t • 9 3 Th ere are man y sen so rs av ailab le wh ich h av e an an alo g o u tp u t; in man y cases th is o u tp u t can b e d irectly co n n ected to th e mb ed ADC in p u t. Q u iz 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 1 0 . G iv e th re e ty p e s o f a n a lo g s ig n a l w h ic h m ig h t b e s a m p le d th ro u g h a n A D C . A n id e a l 8 - b it A D C h a s a n in p u t r a n g e o f 5 .1 2 V. W h a t is its r e s o lu tio n , a n d w h a t is its g reatest q u an tizatio n erro r? G iv e a n e x a m p le o f h o w a s in g le A D C c a n b e u s e d to s a m p le fo u r d iffe re n t a n a lo g sig n als. A n id e a l 1 0 - b it A D C h a s a r e f e r e n c e v o lta g e o f 2 .0 4 8 V a n d b e h a v e s a c c o r d in g to E q u a tio n 5 .1 . F o r a p a r tic u la r in p u t its o u tp u t r e a d s 1 0 1 1 1 0 0 0 0 1 . W h a t is th e in p u t v o ltag e? W h a t w ill b e th e r e s u lt if a n m b e d is r e q u ir e d to s a m p le a n a n a lo g in p u t v a lu e o f 4 .2 V ? An u ltraso u n d sig n al o f 4 0 k Hz is to b e d ig itized . Reco mmen d th e min imu m samp lin g freq u en cy . T h e c o n v e r s io n tim e o f a n A D C is f o u n d to b e 7 .5 m s . T h e A D C is s e t to c o n v e r t rep eated ly , with n o o th er p ro g rammin g req u iremen ts. Wh at is th e max imu m freq u en cy sig n al it can d ig itize? Th e ADC in Qu estio n 7 is n o w u sed with a mu ltip lex er, so th at fo u r in p u ts are rep eated ly d ig itized in tu rn . A fu rth er time o f 2 5 0 0 n s p er samp le is req u ired to sav e th e d ata an d switch th e in p u t. Wh at is th e max imu m freq u en cy sig n al th at can n o w b e d ig itized ? An LM3 5 temp eratu re sen so r is co n n ected to an mb ed ADC in p u t, an d sen ses a temp eratu re o f 3 0 C. Wh at is th e b in ary o u tp u t o f th e ADC? W h a t w ill b e th e v a lu e o f in te g e r x f o r 1 .5 V a n d 2 .5 V s ig n a ls s a m p le d o n th e m b e d u s in g th e fo llo win g p ro g ram co d e? # i n c l u d e “ m b e d . h ” A n a l o g I n A i n ( p 2 0 ) ; i n t m a i n ( ) { i n t x = A i n . r e a d _ u 1 6 ( ) ; } References 5 .1 . 5 .2 . 5 .3 . H o r o w itz , P. Th e Silo n ex LM3 5 Precis h ttp ://w w w.n a n d H ill, W. ( 1 9 8 9 ) . T h e A r t o f E le c tr o n ic s . 2 n d e d itio n . C a m b r id g e U n iv e r s ity P r e s s . h o m e s ite . h ttp ://w w w.s ilo n e x .c o m / io n Cen tig rad e Temp eratu re Sen so rs. No v emb er 2 0 0 0 . Natio n al Semico n d u cto r Co rp o ratio n . a tio n a l.c o m / C H A P T E R 6 F u r t h e r P r o g r a m m in g T e c h n iq u e s C h a p t e r O u t lin e 6 .1 T h e B e n e f it s o f C o n s id e r e d P r o g r a m D e s ig n a n d S t r u c t u r e 6 .2 F u n c t io n s 9 6 6 .3 P r o g r a m D e s ig n 9 7 6 .3 .1 U s in g F lo w c h a r t s t o D e fin e C o d e S t r u c t u r e 6 .3 .2 P s e u d o c o d e 9 9 6 .4 W o r k in g w it h F u n c t io n s o n t h e m b e d 9 7 1 0 0 6 .4 .1 Im p le m e n t in g a S e v e n - S e g m e n t D is p la y C o u n t e r 6 .4 .2 F u n c t io n R e u s e 1 0 2 6 .4 .3 A M o r e C o m p le x P r o g r a m U s in g F u n c t io n s 1 0 3 6 .5 U s in g M u lt ip le F ile s in C / C þ þ 6 .5 6 .5 6 .5 6 .5 .1 O v e .2 T h e .3 T h e .4 U s in rv C # g ie w / C þ ifn d m b o f þ e f e d th e C / C þ þ P re p ro c e sso D ir e c t iv e 1 O b je c t s G lo 6 .6 M o d u la r P r o g r a m E x a m p le C h a p t e r R e v ie w 1 1 3 Q u iz 1 1 3 6 .1 • • • • 1 0 0 1 0 5 P r o g r a m C o m p ila t io n P r o c e s s r a n d P r e p r o c e s s o r D ir e c t iv e s 0 8 b a lly 1 0 9 1 0 6 1 0 7 1 0 9 T h e B e n e fi t s o f C o n s id e r e d P r o g r a m D e s ig n a n d S t r u c t u r e Th ere are n u mero u s ch allen u su ally wise first to co n sid e mu lti-fu n ctio n al p ro jects. It lo o p , so th e ap p ro ach fo r b r th o u g h t o u t. In p articu lar, it • 9 5 th th th th th a a a a a t co d e is t co d e ca t d ev elo p t co d e d e t fu tu re u g es wh en tack lin g r th e so ftware d es is n o t p o ssib le to eak in g u p co d e in h elp s to en su re th read ab le, stru ctu red n b e tested fo r p erfo men t reu ses ex istin g sig n su p p o rts mu ltip p g rad es to co d e can an emb ed d ed sy stem d esig n p ro ject. It is ig n stru ctu re, p articu larly with larg e an d p ro g ram all fu n ctio n ality in to a sin g le co n tro l to u n d erstan d ab le featu res sh o u ld b e well at th e fo llo win g can b e ach iev ed : an d d o cu men ted rman ce in a mo d co d e u tilities to le en g in eers wo r b e imp lemen ted u lar fo rm k eep d ev elo p men t time sh o rt k in g o n a sin g le p ro ject efficien tly . Th ere are v ario u s C/Cþ þ p ro g rammin g tech n iq u es th at en ab le th ese d esig n req u iremen ts to b e co n sid ered , as d iscu ssed in th is ch ap ter. F a s t a n d E f f e c t iv e E m b e d d e d S y s t e m s D e s ig n . D O I : 1 0 .1 0 1 6 /B 9 7 8 - 0 - 0 8 - 0 9 7 7 6 8 - 3 .0 0 0 0 6 - 4 Co p y rig h t Ó2 0 1 2 Elsev ier Ltd . All rig h ts reserv ed . 9 5 9 6 Chapter 6 6 .2 F u n c t io n s A fu n c tio n is a p o rtio n o f c o d e w ith in a la rg er p ro g ram . T h e fu n c tio n p e rfo rm s a s p ec ifi c tas k a n d is re la tiv e ly in d e p e n d e n t o f th e m a in c o d e . F u n c tio n s c a n b e u s e d to m a n ip u la te d a ta ; th is is p a rticu la rly u s efu l if s ev e ral s im ilar d ata m a n ip u la tio n s a re re q u ired in th e p ro g ra m. D a ta v a lu e s c a n b e in p u t to th e fu n ctio n a n d th e fu n c tio n c a n retu rn th e re su lt to th e m a in p ro g ram . F u n c tio n s, th erefo re , a re p artic u larly u s efu l fo r c o d in g m a th em a tica l a lg o rith ms , lo o k -u p tab le s a n d d ata c o n v e rs io n s , a s w e ll a s c o n tro l fe atu res th at m a y o p erate o n a n u mb er o f d iffe re n t p a ra lle l d ata s trea ms . It is a lso p o ss ib le to u se fu n c tio n s w ith n o in p u t o r o u tp u t d ata, s imp ly to r e d u c e c o d e s iz e a n d to im p r o v e r e a d a b ility o f c o d e . F ig u r e 6 .1 illu s tr a te s a f u n c tio n c a ll. T h e re a re s ev e ral a d v a n tag e s w h en u s in g fu n ctio n s . F irst, a fu n ctio n is w ritte n o n c e a n d c o m p ile d in to o n e a r e a o f m e m o r y , ir re s p e c tiv e o f th e n u m b e r o f tim e s th a t it is c a lle d f r o m th e main p ro g ram, so p ro g ram memo ry is red u ced . Fu n ctio n s also allo w clean an d man ag eab le c o d e to b e d e s ig n e d , a llo win g s o ftwa re to b e w e ll s tru c tu re d a n d re a d a b le a t a n u mb er o f lev e ls o f a b s tra c tio n . T h e u s e o f fu n c tio n s a ls o e n a b le s th e p ra c tic e o f m o d u la r c o d in g , w h e re te a ms o f s o ftwa re e n g in e e rs a re o ften re q u ired to d ev e lo p la rg e a n d a d v a n c ed a p p lic atio n s . W ritin g c o d e w ith fu n c tio n s th e re fo re a llo w s o n e e n g in e e r to d ev e lo p a p a rtic u la r s o ftw a re fe a tu re , w h ile a n o th e r e n g in e e r m a y ta k e re s p o n sib ility fo r s o me th in g e ls e . Usin g fu n ctio n s is n o t o v erh ead in sto rin g p r th is sh o u ld o n ly b e an it is p o ssib le to ‘n est’ ch allen g in g to fo llo w. fro m th e fu n ctio n , an d alway s co mp letely b en eficial, h o wev er. Th ere is a small ex ecu tio n time o g ram p o sitio n d ata an d ju mp in g an d retu rn in g fro m th e fu n ctio n , b u t issu e fo r co n sid eratio n in th e mo st time-critical sy stems. Fu rth ermo re, fu n ctio n s with in fu n ctio n s, wh ich can so metimes mak e so ftware A limitatio n o f C fu n ctio n s is th at o n ly a sin g le v alu e can b e retu rn ed array s o f d ata can n o t b e p assed to o r fro m a fu n ctio n (o n ly sin g le-v alu e F ig u r e 6 .1 : A fu n c t io n c a ll F u r t h e r P r o g r a m m in g T e c h n iq u e s 9 7 v ariab les can b e u sed ). Wo rk in g with fu n ctio n s an d mo d u lar tech n iq u es th erefo re req u ires a co n sid ered so ftware stru ctu re to b e d esig n ed an d ev alu ated b efo re p ro g rammin g is started . 6 .3 P r o g r a m D e s ig n 6 .3 .1 U s in g F lo w c h a r t s t o D e fi n e C o d e S t r u c t u r e It is o ften u sefu l to u se a flo wch art to in d icate th e o p eratio n o f p ro g ram flo w an d th e u se o f f u n c tio n s . C o d e fl o w c a n b e d e s ig n e d u s in g a fl o w c h a r t p r io r to c o d in g . F ig u r e 6 .2 s h o w s so me o f th e flo wch art sy mb o ls th at are u sed . Fo r ex amp le, tak e th e fo llo win g so ftware d esig n sp ecificatio n : Desig n a p ro g ram to lig h t-emittin g d io d e u s e d in S e c tio n 3 .5 ) co u n tin g . Th is in clu • • • • in cremen t co n tin u o u sly th e o u tp u t o f a sev en -seg men t n u merical ( L E D ) d is p la y ( a s s h o w n in F ig u r e 6 .3 , a n d s im ila r to th e o n e th ro u g h th e n u mb ers 0 to 9 , th en reset b ack to 0 to co n tin u e d es: Use a fu n ctio n to co n v ert a h ex ad ecimal c seg men t LED o u tp u t b y te B. Ou tp u t th e LED o u tp u t b y te to lig h t th e co r If th e co u n t v alu e is g reater th an 9 , th en res D elay fo r 5 0 0 ms to e n su re th a t th e L ED o u tp u o u n ter b y te A to th e relev an t sev en rect seg men t LEDs. et to zero . t c o u n ts u p a t a ra te th a t is e a s ily v is ib le . Th e o u tp u t o f th e sev en -seg men t d isp lay h as b een d iscu ssed p rev io u sly in Ch ap ter 3 an d in p a r tic u la r in Ta b le 3 .4 . A f e a s ib le s o f tw a r e d e s ig n is s h o w n in F ig u r e 6 .4 . Flo wch arts allo w u s to v isu alize th e o rd er o f o p eratio n s o f co d e an d to mak e ju d g men ts o n wh ich sectio n s o f a p ro g ram may req u ire th e mo st atten tio n o r tak e th e mo st effo rt to d ev elo p . F ig u r e 6 .2 : E x a m p le fl o w c h a r t s y m b o ls 9 8 Chapter 6 A F B G E C D D P F ig u r e 6 .3 : S e v e n - s e g m e n t d is p la y F ig u r e 6 .4 : E x a m p le fl o w c h a r t d e s ig n fo r a s e v e n - s e g m e n t d is p la y c o u n t e r F u r t h e r P r o g r a m m in g T e c h n iq u e s 9 9 Th ey also h elp with co mmu n icatin g a p o ten tial d esig n with n o n -en g in eers, wh ich may h o ld th e k ey to d esig n in g a sy stem th at meets a v ery d etailed sp ecificatio n . 6 .3 .2 Pseudocode Pseu d o co Id eally , p Pseu d o co sh o w lo o p seu d o co Writin d ev elo So me a co m d e c seu d d e s p in g d e. o n sists o f o co d e sh h o u ld b e p ro cesse g p seu d o co d p men t an d a p ro jects may b in atio n o f b sh o rt, En g lish p h rases o u ld n o t in clu d e k ey w written as a list o f co n s. In d en tatio n can b e u u sed o rd s secu sed to in tiv to ex p lain sp ecific ta an y sp ecific co mp e p h rases; we can sh o w th e lo g ical p sk s with u ter lan ev en d r ro g ram in a p ro g ram. g u ag e. aw arro ws to flo w in e sav es time later d u rin g th e co d in g an d testin g stag e o f a p ro g ram’s lso h elp s co mmu n icatio n amo n g d esig n ers, co d ers an d p ro ject man ag ers. u se p seu d o co d e fo r d esig n , o th ers may u se flo wch arts, an d so me o th . T h e s o f tw a r e d e s ig n s h o w n b y th e fl o w c h a r t in F ig u r e 6 .4 c o u ld a ls o b e d e s c r ib e d in p s e u d o c o d e a s s h o w n in F ig u r e 6 .5 . N o te th a t th e fu n c tio n s S e g C o n v e r t( ) a n d D e la y ( ) a re d efi n e d e lsew h e re, fo r ex a mp le in a s ep a ra te ‘u tilitie s ’ fi le, a u th o re d b y a d iffe re n t e n g in e e r. F u n ctio n S e g C o n v e r t( ) c o u ld im p le me n t a s imp le lo o k -u p ta b le o r n u m b er o f if s tate me n ts th a t a ss ig n s th e s u itab le v a lu e to B . F ig u r e 6 .5 : E x a m p le p s e u d o c o d e fo r s e v e n - s e g m e n t d is p la y c o u n t e r 1 0 0 6 .4 Chapter 6 W o r k in g w it h F u n c t io n s o n t h e m b e d Th e imp le me n tatio n an d sy n tax o f fu n ctio n s in C/Cþ þ are d iscu s sed in d eta il in S e c tio n B .4 o f A p p e n d ix B w ith s o m e s im p le e x a m p le s . I t is im p o r ta n t to rememb er th at, as with v ariab les, all fu n ctio n s (ex cep t th e m a in () fu n ctio n ) mu st b e d eclared at th e start o f a p ro g ram. T h e d ec laratio n stateme n ts fo r fu n ctio n s are ca lled p ro to typ es. So each fu n ctio n in th e co d e mu st h av e an asso cia ted p ro to ty p e fo r it to c o mp ile a n d ru n . Th e a c tu a l fu n c tio n co d e n e e d s d e fi n in g with in a C/Cþ þ file a ls o , in o rd e r fo r it to b e calle d fro m with in th e ma in co d e. Th is is d o n e b y s p e cify in g th e fu n ctio n in th e same way as th e p ro to ty p e, fo llo wed b y th e ac tu a l fu n ctio n co d e. A n u mb er o f ex a mp les will b e p resen ted d u rin g th is ch ap ter, so in each case ma k e a p o in t o f id en tify in g th e fu n ctio n p ro to ty p e an d th e actu al fu n ctio n d efin itio n . A fu rth er p o in t to n o te is th at if a fu n ctio n is d efin e d in co d e p rio r to th e m a in ( ) C fu n ctio n , th en its d efin itio n serv es as its p ro to ty p e als o . C c o d e fe a tu re 6 .4 .1 Im p le m e n t in g a S e v e n -S e g m e n t D is p la y C o u n t e r P r o g r a m E x a m p le 6 .1 s h o w s a p r o g r a m w h ic h im p le m e n ts th e d e s ig n s d e s c r ib e d b y th e fl o w c h a r t in F ig u r e 6 .4 a n d th e p s e u d o c o d e s h o w n in F ig u r e 6 .5 . I t a p p lie s s o m e o f th e te c h n iq u e s fi r s t u s e d in P r o g r a m E x a m p le 3 .5 , b u t g o e s b e y o n d th e s e . T h e m a in d e s ig n req u iremen t is th at a sev en -seg men t d isp lay is u sed to co u n t co n tin u o u sly fro m 0 to 9 an d lo o p b ack to 0 . Declaratio n s fo r th e B u s O u t o b ject an d th e A an d B v ariab les, as well as th e S e g C o n v e r t( ) fu n ctio n p ro to ty p e, ap p ear early in th e p ro g ram. It can b e seen th at th e m a in ( ) p ro g ram fu n ctio n is fo llo wed b y th e S e g C o n v e r t( ) fu n ctio n , wh ich is called reg u larly fro m with in th e main co d e. No tice in th e lin e B = S e g C o n v e r t ( A ) ; / / C a l l f u n c t i o n t o r e t u r n B th at B can immed iately tak e o n th e retu rn v alu e o f th e S e g C o n v e r t( ) fu n ctio n . C c o d e fe a tu re r e t u r n No tice in th e S e g C o n v e r t( ) fu n ctio n th e fin al lin e immed iately b elo w, wh ich ap p lies th e r e tu r n k ey wo rd : S e g B y t e ; Th is lin e cau ses p ro g ram carry in g th e v alu e S e g B y y o u start writin g fu n ctio n as p art o f th e fu n ctio n p r ex ecu tio te as its s th at p r o to ty p e n to retu rn to retu rn v alu e. o v id e retu rn v early in th e p th e p o in t fro m wh ich th e fu n ctio n was called , It is an imp o rtan t tech n iq u e to u se o n ce alu es. No tice th at S e g B y te h as b een d eclared ro g ram listin g . F u r t h e r P r o g r a m m in g T e c h n iq u e s / * P r o g r a m E x a m p l e # i n c l u d e " m b e d . h " B u c h c h c h i n s O u t a r S e a r A = a r B ; t m a i w h i l B = S e S e g 1 A + + ; i f ( A = 0 ; 6 . 1 : s e v e n - s e g m e n t d i s p l a y c o u n t e r * / S e g 1 ( p 5 , p 6 , p 7 , p 8 , p 9 , p 1 0 , p 1 1 , p 1 2 ) ; g C o n v e r t ( c h a r S e g V a l u e ) ; 0 ; / / / / / / A , B , C , D , E , F , G , D P f u n c t i o n p r o t o t y p e d e c l a r e v a r i a b l e s A n ( e g C = B / / / / / / / / / / m a i i n f C a l O u t i n c i f / / d e l a y / / f u n c t i o n ) { ( 1 ) { o n v e r t ( A ) ; ; / / A > 0 x 0 9 ) { } w a i t ( 0 . 5 ) ; } 1 0 1 n p i n i l f p u t r e m A > r o g r a t e l o u n c t i B e n t A 9 r e 5 0 0 m o p o n t o s e t a n d r e t u r n t o B B z e r o m i l l i s e c o n d s } c h a r S e g c h a r S s w i t c h c c c c c c c c c c } r e t u r n C o e g ( a s a s a s a s a s a s a s a s a s a s n v B y S e e e e e e e e e e e e r t ( t e = 0 g V a l 0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : c h x 0 u e S e S e S e S e S e S e S e S e S e S e a r 0 ; ) S e g V a l u e ) { { g B g B g B g B g B g B g B g B g B g B y t y t y t y t y t y t y t y t y t y t e = e = e = e = e = e = e = e e = e = = 0 x 3 0 x 0 0 x 5 0 x 4 0 x 6 0 x 6 0 x 7 0 x 0 0 x 7 0 x 6 F ; b 6 ; b B ; b F ; b 6 ; b D ; b D ; b 7 ; b F ; b F ; b r e a r e a r e a r e a r e a r e a r e a r e a r e a r e a / / D / / / / / / / / / / / / / / / / / / / / k ; k ; k ; k ; k ; k ; k ; k ; k ; k ; P 0 0 0 F E D C B 0 1 1 1 1 1 0 1 0 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 0 1 1 1 1 0 1 0 1 1 1 1 0 1 1 0 1 0 1 1 1 A 1 0 1 0 0 1 1 0 1 0 0 1 0 1 0 0 0 1 0 0 G 0 0 ’ S e g C o n v e r t ’ 1 1 1 1 1 b i b i b i b i b i b i b i b i b i b i n a n a n a n a n a n a n a n a n a n a r y r y r y r y r y r y r y r y r y r y S e g B y t e ; } P r o g r a m E x a m p le 6 .1 S e v e n - s e g m e n t d is p la y c o u n t e r Co n n ect a sev en d iag ram fo r a sev th e d isp lay o u tp u y o u u n d erstan d h p seu d o co d e d esig n seg men t en -seg m t co n tin u o w th e p n s sh o w d isp lay to th en t LED d isp o u sly co u n ts ro g ram wo rk n p rev io u sly . e mb ed lay wa fro m 0 s b y cr an d s sh o to 9 o ss-r im wn an efe p lemen p rev io d th en ren cin g t P r o g r a m 6 .1 . T h e u s ly in F ig u r e 3 .1 0 . resets b ack to 0 . En with th e flo wch art wirin g Ve r if y th a t su re th at an d E x e r c is e 6 .1 C h a n g e P r o g r a m E x a m p le 6 .1 s o t h a t t h e d is p la y c o u n t s u p in h e x a d e c im a l fr o m 0 t o F . Y o u w ill n e e d t o w o r k o u t t h e d is p la y p a t t e r n s fo r A t o F u s in g t h e s e v e n - s e g m e n t d is p la y . F o r a fe w y o u w ill n e e d lo w e r c a s e , fo r o t h e r s u p p e r c a s e . n 1 0 2 Chapter 6 6 .4 .2 F u n c t io n R e u s e No can we mb w th at we h av e a b u ild p ro jects u s can imp lemen t a ed B u s O u t d ecla It is p o ssib le to imp th e main p ro g ram c fu n ctio n p rev io u sly th is ex amp le. No te two fo r lo o p s to co / * P r o g r a m E x a m p l e fu n ctio n to co n v ert a d in g mu ltip le sev en -seg seco n d sev en -seg men ratio n an d callin g th e lemen t a co u n ter p ro o d e to th at sh o wn in d efin ed in Pro g ram also th at a slig h tly d u n t each o f th e ten s 6 . 2 : D i s p l a y ecimal v men t d is t d isp lay same S e alu e p lay s (see g C o n g ram th at co Pro g ram Ex E x a m p le 6 .1 ifferen t p ro g an d u n its v a c o u n t e r f o r to a sev en with little F ig u r e 6 .6 v e r t( ) fu n seg men t d isp lay b y te, we ex tra effo rt. Fo r ex amp le, ) b y simp ly d efin in g its ctio n as b efo re. u n ts fro m 0 0 to 9 9 a m p le 6 .2 . N o te th is also req u ired to rammin g ap p ro ach lu es. b y s at th b e c is u imp ly e S e g o p ied sed ; h mo d ify C o n v e r (reu sed ere we in g t( ) ) in u se 0 - 9 9 * / # i n c l u d e " m b e d . h " B u s O u t S e g 1 ( p 5 , p 6 , p 7 , p 8 , p 9 , p 1 0 , p 1 1 , p 1 2 ) ; B u s O u t S e g 2 ( p 1 3 , p 1 4 , p 1 5 , p 1 6 , p 1 7 , p 1 8 , p 1 9 , p 2 0 ) ; c h a r i n t m w h f o S e a i i l r g C n ( e ( c o n v e r t { ( 1 ) { h a r j = S e g 2 = S f o r ( c S e w a } ( c h a r S e g V a l u e ) ; 0 ; e g h a g 1 i t ; j e r 0 ; C o ) ; ) j < C o r = S ( 0 1 0 n v i = e g . 2 + + t ( i < n v ) j ) 1 0 e r { ; ; i + + ) t ( i ) ; { / / A , B , C , D , E , F , G , D P / / / / / / / / / / / / / / f u m a i n c o t e c o u n n c i n f i u n n s u n i t t i o p r n i t t e r c o t e r s c n p o g r e l l o l u m l o o l u r o t o t y p e a m o o p o p 1 n o p 2 m n } } } / / a d d S e g C o n v e r t f u n c t i o n h e r e . P r o g r a m E x a m p le 6 .2 T w o d ig it s e v e n - s e g m e n t d is p la y c o u n t e r Usin g tw Pro g ram an d th en meth o d u n o sev en -seg men t E x a m p le 6 .2 a n d resets b ack to 0 . sed to co u n t th e d isp v er Rev ten s lay s, w ify th at iew th e an d u n ith p in c o n n e c tio n s s h o w n in F ig u r e 6 .6 , im p le m e n t th e d isp lay o u tp u t co u n ts co n tin u o u sly fro m 0 0 to 9 9 p ro g ram d esig n an d familiarize y o u rself with th e its d ig its each fro m 0 to 9 . E x e r c is e 6 .2 W r s e g 1 . 2 . it e a n d t e s t m b e d p r o g r a m s t o p e m e n t d is p la y s e t u p : C o u n t 0 t o F F , in h e x a d e c im a l fo C r e a t e a o n e - m in u t e t im e r , c o u n t L E D e v e r y t im e t h e c o u n t o v e r fl o r fo r m t h e fo llo w in g a c t io n w it h a d u a l s e v e n rm a t 0 e5 9 , w i t h a p r e c i s e i n c r e m e n t r a t e o f 1 s . F l a s h a n w s b a c k t o z e r o ( i.e . e v e r y m in u t e ) F u r t h e r P r o g r a m m in g T e c h n iq u e s 1 0 3 3 . In t r o d u c e t w o L E D s t o m a k e a s im p le ‘1 ’ d ig it , a n d c o u n t 0 t o 1 9 9 . T h is is c a lle d a t w o a n d a h a lf d ig it d is p la y . In e a c h c a s e s e t t h e c o u n t r a t e t o a d iffe r e n t s p e e d a n d e n s u r e t h a t t h e p r o g r a m lo o p s b a c k t o 0 x 0 0 , s o t h a t t h e c o u n t e r o p e r a t e s c o n t in u o u s ly . n 6 .4 .3 A M o r e C o m p le x P r o g r a m U s in g F u n c t io n s A mo re ad v an ced p ro g ram co u ld read two n u merical v alu es fro m a h o st termin al ap p licatio n an d d isp lay th ese o n two sev en -seg men t d isp lay s co n n ected to th e mb ed . Th e p ro g ram can th erefo re d isp lay an y in teg er n u mb er b etween 0 0 an d 9 9 , as req u ired b y u ser k ey p resses. An ex amp le p ro g ram d esig n u ses fo u r fu n ctio n s to imp lemen t th e h o st termin al o u tp u t o n sev en -seg men t d isp lay s. Th e fo u r fu n ctio n s are as fo llo ws: S e g I n it( ) H o s tI n it( G e tK e y In S e g C o n v e b y te. eto set u p ) eto set u p u t( ) eto r t( ) efu n an d p an g et ctio n in itialize th e sev en -seg men t d d in itialize th e h o st termin al c k ey b o ard d ata fro m th e termin to co n v ert a d ecimal in teg er to 7 -s e g m e n t d is p la y p p to 7 -s e g m e n t d is p la y p p p in p in p in p in p in p in in 1 in 5 p in p in p in p in p in p in in 1 in 5 isp la o mm al ap to a y s u n icatio n p licatio n sev en -seg men t d isp lay d ata G n d V in V b n R p in s 3 ,8 7 , s e g . a 6 , s e g . b 4 , s e g . c 2 , s e g . d 1 , s e g . e 9 , s e g . f 0 , s e g . g , s e g . d p 7 , s e g . a 6 , s e g . b 4 , s e g . c 2 , s e g . d 1 , s e g . e 9 , s e g . f 0 , s e g . g , s e g . d p p in s 3 ,8 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 m b e d M ic r o c o n tr o lle r • • • • 1 7 1 8 1 9 2 0 G n d F ig u r e 6 .6 : T w o s e v e n - s e g m e n t d is p la y c o n t r o l w it h t h e m b e d 1 0 4 Chapter 6 We w ill u s e th e m b e d u n iv e rs a l s e ria l b u s (U S B ) in te rfa c e to c o m m u n ic a te w ith th e h o s t P C , a s w e d id in S e c tio n 5 .3 , a n d tw o s e v e n - s e g m e n t d is p la y s , a s in th e p r e v io u s e x e r c is e . Fo r th e first time n o w we co me acro ss a meth o d fo r co mmu n icatin g k ey b o ard d ata an d d isp lay ch aracters, u sin g ASCII co d es. Th e term ASCII refers to th e American Stan d ard Co d e fo r In fo rmatio n In terch an g e meth o d fo r d efin in g alp h an u meric ch aracters as 8 -b it v alu es. Each a l p h a b e t c h a r a c t e r ( l o w e r a n d u p p e r c a s e ) , n u m b e r ( 0 e9 ) a n d a s e l e c t i o n o f p u n c t u a t i o n c h a r a c te r s a r e a ll d e s c r ib e d b y a u n iq u e id e n tifi c a tio n b y te , i.e . th e ‘A S C I I v a lu e ’ . T h e r e f o r e , fo r ex amp le, wh en a k ey is p ressed o n a co mp u ter k ey b o ard , its ASCII b y te is co mmu n icated to th e PC. Th e same ap p lies wh en co mmu n icatin g with d isp lay s. Th e u se o f ASCII ch aracters will b e d ev elo p ed fu rth er in Ch ap ter 8 . Th e ASCII b y te fo r n u merical ch aracters h as th e h ig h er fo u r b its set to v alu e 0 x 3 an d th e lo wer fo u r b its rep resen t th e v alu e o f th e n u merical k ey wh ich is p ressed ( 0 x 0 t o 0 x 9 ) . N u m b e r s 0 e9 a r e t h e r e f o r e r e p r e s e n t e d i n A S C I I a s 0 x 3 0 t o 0 x 3 9 . To co n v ert th e ASCII b y te retu rn ed b y th e k ey b o ard to a reg u lar d ecimal d ig it, th e h ig h er fo u r b its n eed to b e remo v ed . We d o th is b y lo g ically ANDin g th e ASCII co d e with a b itmask , a n u mb er with b its set to 1 wh ere we wan t to k eep a b it in th e ASCII, an d set to 0 wh ere we wan t to fo rce th e b it to 0 . In th is case, we ap p ly a b itmask o f 0 x 0 F. Th e lo g ical AND ap p lies th e o p e r a to r ‘ & ’ f r o m Ta b le B .5 , a n d a p p e a r s in th e lin e : C c o d e fe a tu re r e t u r n ( c & 0 x 0 F ) ; / / a p p l y b i t m a s k t o c o n v e r t t o d e c i m a l , a n d r e t u r n E x a m p le f u n c tio n s a n d p r o g r a m c o d e a r e s h o w n in P r o g r a m E x a m p le 6 .3 . O n c e a g a in , th e f u n c tio n S e g C o n v e r t ( ) , a s s h o w n in P r o g r a m E x a m p le 6 .1 , s h o u ld b e a d d e d to c o m p ile th e p ro g ram. / * P r o g r a m E x a m p l e # i n S e r B u s B u s c l u d e i a l p c O u t S e O u t S e " m ( U g 1 g 2 b e S B ( p ( p d . T X 5 , 1 3 v o v o c h c h c h S e H o G e S e d a g I s t t K g C t a n i I n e y o n 1 , t ( i t I n v e d v o ( v p u r t a t a i g I s t i l t a g 2 t a g 1 n ( n i I n e 2 = S 1 = S ) t ( i t ( 1 = e g = e g { ) ; ( ) ) G e C o G e C o 6 . 3 : H o s t k e y p r e s s t o 7 - s e g d i s p l a y * / i n t i d i d a r a r a r m S e H o w h d a S e d a S e h " , U S B R X ) ; p 6 , p 7 , p 8 , p 9 , p 1 0 , p 1 1 , p 1 2 ) ; , p 1 4 , p 1 5 , p 1 6 , p 1 7 , p 1 8 , p 1 9 , p 2 0 ) ; / / / / / / c o m m s t o h o s t P C A , B , C , D , E , F , G , D P A , B , C , D , E , F , G , D P i d o i t ( ( c a 2 / / / / / / / / / / f u f u f u f u v a ) ; d ) ; v o i d ) ; h a r S e g V a l u e ) ; ; ; { t K n v t K n v e y e r e y e r I n t ( I n t ( p u t ( d a t a p u t ( d a t a ) ; 2 ) ; ) ; 1 ) ; / / m a i n p r o / / c a l l f u n / / c a l l f u / / / / / g r c t n c / / / / / n c n c n c n c r i a m i o t i i n c a c a c a c a t i t i t i t i a b o n o n o n o n l e p r p r p r p r d e o t o t o t o t c l o t o t o t o t a r n t o i n i t i a l o n t o i n i t i a f i n i t e l o o p l l f u n c t i o n l l f u n c t i o n l l f u n c t i o n l l f u n c t i o n y p e y p e y p e y p e a t i o n s i z e t h e 7 - s e g l i z e t h e h o s t t o t o t o t o g e c o g e c o t 1 n v e t 2 n v e s t r t n d r t k e a n k e a n d i s p l a y s t e r m i n a l y d y d p r o u p r o u e s t p e s t p s u t s u t F u r t h e r P r o g r a m m in g T e c h n iq u e s p c . p r i n t f ( " " ) ; / / d i s p l a y s p a c e s b e t w e e n 1 0 5 n u m b e r s } } / / f u n v o i d S S e g 1 = S e g 2 = c t e g S e S e i o I n g C g C n s i t ( v o i d ) { o n v e r t ( 0 ) ; o n v e r t ( 0 ) ; / / / / i n i t i a l i z e i n i t i a l i z e t o t o z e r o z e r o } v o i d H o s t I n i t ( v o i d ) { p c . p r i n t f ( " \ n \ r T y p e t w o d i g i t n u m b e r s t o b e d i s p l a y e d \ n \ r " ) ; } c h a c h p c r e r G e t K e y a r c = p . p r i n t f ( t u r n ( c & / / c o p y I n c . " % 0 x p u g e c " 0 F t ( v o i d ) t c ( ) ; , c ) ; ) ; { / / / / / / g e t k e y b o a r d d a t a ( a s c i i 0 x 3 0 - 0 x 3 9 ) p r i n t a s c i i v a l u e t o h o s t P C t e r m i n a l a p p l y b i t m a s k t o c o n v e r t t o d e c i m a l , a n d r e t u r n } S e g C o n v e r t f u n c t i o n h e r e t o o . P r o g r a m E x a m p le 6 .3 T w o d ig it s e v e n - s e g m e n t d is p la y b a s e d o n h o s t k e y p r e s s e s I m p le m e n t P r o g r a m E x a m p le 6 .3 a n d v e r if y th a t n u m e r ic a l k e y b o a r d p r e s s e s a r e d is p la y e d o n th e sev en -seg men t d isp lay s. Familiarize y o u rself with th e p ro g ram d esig n an d u n d erstan d th e in p u t an d o u tp u t featu res o f each p ro g ram fu n ctio n . 6 .5 U s in g M u lt ip le F ile s in C / C þ þ Larg e emb ed d ed p ro jects in C/Cþ þ b en efit fro m b ein g sp lit in to a n u mb er o f d ifferen t files, u su ally so th at a n u mb er o f en g in eers can tak e resp o n sib ility fo r d ifferen t p arts o f th e co d e. Th is ap p ro ach also imp ro v es read ab ility an d main ten an ce. Fo r ex amp le, th e co d e fo r a p ro cesso r in a v en d in g mach in e mig h t h av e o n e C/Cþ þ file fo r th e co n tro l o f th e actu ato rs d e liv e rin g th e ite m s a n d a d iffe re n t fi le fo r c o n tro llin g th e u s e r in p u t a n d liq u id c ry s ta l d isp lay . It d o es n o t mak e sen se to co mb in e th ese two co d e featu res in th e same so u rce file as th ey each relate to d ifferen t p erip h eral h ard ware. Fu rth ermo re, if a n ew b atch o f v en d in g mach in es were to b e b u ilt with an u p d ated k ey p ad an d d isp lay , o n ly th at p iece o f th e co d e wo u ld n eed to b e mo d ified . All th e o th er so u rce files co u ld b e carried o v er with o u t ch an g e. Mo d u lar co d in g u ses h ead er files to jo in mu ltip le files to g eth ( m a in .c o r m a in .c p p ) is u s e d to c o n ta in th e h ig h - le v e l c o d v ariab les (v ariab les th at are av ailab le to all fu n ctio n s) are d e is g o o d p ractice th erefo re fo r each C/Cþ þ featu re file to h a a .h e x te n s io n ) . H e a d e r fi le s ty p ic a lly in c lu d e d e c la r a tio n s d ire c tiv e s , v a ria b le d e c la ra tio n s a n d fu n c tio n p ro to ty p e s . er. In e, b u fin ed v e an o n ly , g en eral, a m t all fu n ctio n in featu re-sp asso ciated h fo r ex amp le ain C/Cþ þ file s an d g lo b al ecific C files. It ead er file (with co mp iler A n u mb er o f h ead er files also ex ist fro m with in C/Cþ þ , wh ich can b e u sed fo r mo re a d v a n c e d d a ta m a n ip u la tio n o r a rith m e tic . M a n y o f th e b u ilt-in C /Cþ þ h e a d e r fi le s a re 1 0 6 Chapter 6 a lr e a d y lin k e d to th r o u g h th e m b e d .h h e a d e r, s o w e d o n o t n e e d to w o r r y to o m u c h a b o u t th o s e h e r e . T h e y a r e d is c u s s e d in m o r e d e ta il in S e c tio n B .9 o f A p p e n d ix B . 6 .5 .1 O v e r v ie w o f t h e C / C þ þ P r o g r a m C o m p ila t io n P r o c e s s To u n d erstan d fu rth er th e d esig n ap p ro ach to mo d u lar co d in g , it h elp s to u n d erstan d th e way p ro g rams are p rep ro cessed , co mp iled an d lin k ed to create a b in ary ex ecu tio n file fo r th e m ic r o p r o c e s s o r. A s im p lifi e d v e r s io n o f th is p r o c e s s is s h o w n in F ig u r e 6 .7 a n d d e s c r ib e d in d e ta il th r o u g h S e c tio n 6 .6 . In su mmary , first a p rep ro cesso r lo o k s at a p articu lar so u rce file an d imp lemen ts an y p re p ro c e s s o r d ire c tiv e s a n d a s s o c ia te d h e a d e r fi le s . T h e c o m p ile r th e n g e n e ra te s a n o b je c t fi le fo r th e p articu lar so u rce co d e. In d o in g so , th e co mp iler en su res th at th e so u rce files d o n o t F ig u r e 6 .7 : C p r o g r a m c o m p ile a n d lin k p r o c e s s F u r t h e r P r o g r a m m in g T e c h n iq u e s 1 0 7 c o n tain an y s y n tax e rro rs en o te th a t a p ro g ra m ca n h av e n o s y n tax e rro rs , b u t s till b e q u ite u seless. Th e co mp iler th en g en erates co rrect o b ject co d e fo r each file an d en su res th at th e o b ject an d lib rary files are fo rmatted co rrectly fo r th e lin k er. Ob jec ( .b in ) allo ca lo cate may u t files an d b u ilt-in lib rary files are th en lin k ed to g eth e file, wh ich can b e d o wn lo ad ed to th e micro p ro cesso tio n o f memo ry fo r th e micro p ro cesso r ap p licatio n an d in to memo ry an d lin k ed to each o th er co rrectly . In n co v er p ro g rammin g fau lts asso ciated with memo ry 6 .5 .2 The C/Cþ þ r to g en erate an ex ecu tab le b in ary r. Th e lin k er also man ag es th e d it en su res th at all o b ject files are u n d ertak in g th e task , th e lin k er allo catio n an d cap acity . P r e p r o c e s s o r a n d P r e p r o c e s s o r D ir e c t iv e s Th e C/Cþ þ p rep ro cesso r mo d ifies co d e b efo re th e p ro g ram is co mp iled . P r e p r o c e s s o r d ir e c tiv e s a r e d e n o te d w ith a ‘ # ’ s y m b o l, a s d e s c r ib e d in S e c tio n B .2 o f A p p e n d ix B . T h e s e m a y a ls o b e c a lle d ‘c o m p ile r d ire c tiv e s ’ a s th e p re p ro c e s s o r is essen tially a su b p ro cess o f th e co mp iler. Th e # in c lu d e (u su ally referred to as ‘h ash -in clu d e’) d ire c tiv e is c o m m o n ly u s e d to te ll th e p re p ro c e s s o r to in c lu d e a n y c o d e o r s ta te m e n ts c o n ta in e d with in an ex tern al h ead er file. In d eed , we h av e seen th is u b iq u ito u s # in c lu d e statemen t in ev ery co mp lete p ro g ram ex amp le so far in th is b o o k , as th is is u sed to co n n ect o u r p ro g rams with th e co re mb ed lib raries. C c o d e fe a tu re F ig u r e 6 .8 s h o w s th r e e h e a d e r fi le s to e x p la in h o w th e # in c lu d e s ta te m e n t w o r k s . I t is imp o rtan t to n o te th at # in c lu d e essen tially ju st acts as a co p y -an d -p aste featu re. If we co mp ile F ig u r e 6 .8 : C p r e p r o c e s s o r e x a m p le w it h m u lt ip le d e c la r a t io n e r r o r fo r v a r ia b le ‘p e a r s ’ 1 0 8 Chapter 6 a fi le .h a n d b fi le .h w h e r e b o th fi le s a ls o # in c lu d e c fi le .h , w e w ill h a v e tw o c o p ie s o f th e c o n te n ts o f c fi le .h ( h e n c e v a r ia b le p e a r s w ill b e d e fi n e d tw ic e ) . T h e c o m p ile r w ill th e r e f o r e h ig h lig h t an erro r, as mu ltip le d eclaratio n s o f th e same v ariab les o r fu n ctio n p ro to ty p es are n o t allo wed . We can also u se # d e fi n e statemen ts (u su ally referred to as ‘h ash -d efin e’), wh ich allo w u s to u se mean in g fu l n ames fo r sp ecific n u merical v alu es th at n ev er ch an g e. Here are so me ex amp les: # d e f i n e # d e f i n e # d e f i n e S A M P L E F R E Q U E N C Y P I M A X _ S I Z E 4 4 1 0 0 3 . 1 4 1 5 9 2 2 5 5 Th e p rep ro cesso r rep laces # d e fi n e with th e actu al v alu e asso ciated with th at n ame, so u sin g # d e fi n e statemen ts d o es n o t actu ally in crease th e memo ry lo ad o n th e p ro cesso r. 6 .5 .3 T h e # if n d e f D ir e c t iv e We h n o t a featu th erefo re n ecess o n e o ccasio n . C c o d e fe a tu re av e ju st seen th at mu ltip le d ecla llo wed . Ho wev er, it is imp o rtan t res th at are req u ired fo r th e lin k ary to en su re th at all v ariab les an ratio fo r h er to d fu n n s o f a v ariab le o r ead er files to in clu b u ild th e p ro ject ctio n p ro to ty p es a fu n ctio n p ro to ty p e are d e all th e v ariab les an d su ccessfu lly . It is re p rep ro cessed o n ju st Wh en u sin g h ead er files it is th erefo re g o o d p ractice to u se a co n d itio n al statemen t to d efin e v ariab les an d p ro to ty p es o n ly if th ey h av e n o t p rev io u sly b een d efin ed . Fo r th is th e # ifn d e f d ire c tiv e , w h ic h m e a n s ‘if n o t d e fi n e d ’, c a n b e u s e d . In o rd e r to u s e th e # ifn d e f d ire c tiv e e ffe c tiv e ly , a c o n d itio n a l s ta te m e n t b a s e d o n th e e x is te n c e o f a # d e fi n e v a lu e is re q u ire d . If th e # d e fi n e v alu e h as n o t p rev io u sly b een d efin ed th en th at v alu e an d all o f th e h ead er file’s v ariab les an d p ro to ty p es are d efin ed . If th e # d e fi n e v alu e h as p rev io u sly b een d eclared th en th e h ead er file’s co n ten ts are n o t imp lemen ted b y th e p rep ro cesso r (as th ey mu st certain ly h av e alread y b een imp lemen ted ). Th is en su res th at all h ead er file d eclaratio n s are ad d ed o n ly o n c e to th e p r o je c t. T h e e x a m p le c o d e s h o w n in P r o g r a m E x a m p le 6 .4 r e p r e s e n ts a te m p la te h e a d e r fi le s tr u c tu r e u s in g th e # if n d e f c o n d itio n , a v o id in g th e e r r o r h ig h lig h te d in F ig u r e 6 .8 . / * * / P r o g r a m # i f n d e f # d e f i n e / / 6 . 4 : T e m p l a t e V A R I A B L E _ H V A R I A B L E _ H h e a d e r # e n d i f E x a m p l e d e c l a r a t i o n s f o r . h h e a d e r f i l e / / / / i f V A R I A B L E _ H d e f i n e i t n o w h a s n o t p r e v i o u s l y / / e n d d i r e c t i v e h e r e . o f t h e i f P r o g r a m E x a m p le 6 .4 E x a m p le h e a d e r fi le t e m p la t e b e e n d e f i n e d F u r t h e r P r o g r a m m in g T e c h n iq u e s 6 .5 .4 1 0 9 U s in g m b e d O b je c t s G lo b a lly All mb ed o b jects mu st b e d efin ed in an ‘o wn er’ so u rce file. Ho wev er, we m th o s e o b je c ts f r o m w ith in o th e r s o u r c e fi le s in th e p r o je c t, i.e . ‘ g lo b a lly ’ . T h b y also d efin in g th e mb ed o b ject in th e asso ciated o wn er’s h ead er file. Wh en is d efin ed fo r g lo b al u se, th e e x te r n sp ecifier sh o u ld b e u sed . Fo r ex amp le, c a lle d m y _ f u n c t io n s .c p p m a y d e fi n e a n d u s e a D ig it a lO u t o b je c t c a lle d ‘ R fo llo ws: D i g i t a l O u t ay wish to u se is can b e d o n e an mb ed o b ject a b esp o k e file e d L e d ’ as R e d L e d ( p 5 ) ; If an y o th er so u rce files n eed to man ip u late R e d L e d , th e o b ject mu st also b e d eclared in th e m y _ f u n c t io n s .h h e a d e r fi le u s in g th e e x t e r n s p e c ifi e r, a s f o llo w s : e x t e r n D i g i t a l O u t R e d L e d ; No te th at th e sp ecific mb ed p in s d o n o t n eed to b e red efin ed in th e h ead er file, as th ese will h a v e a lr e a d y b e e n s p e c ifi e d in th e o b je c t d e c la r a tio n in m y _ f u n c t io n s .c p p . 6 .6 M o d u la r P r o g r a m E x a m p le A mo d u lar Ex amp le 6 Th erefo re, created as • • • p ro g ra m e x a m p le c a n n o w b e b u ilt fro m th e n o n -m o d u la r c o d e g iv e n in P ro g ra m .3 . H e r e , th e f u n c tio n a l f e a tu r e s a r e s e p a r a te d to d iff e r e n t s o u r c e a n d h e a d e r fi le s . a k ey b o ard -co n tro lled sev en -seg men t d isp lay p ro ject with mu ltip le so u rce files is fo llo ws: m a in .c p p ec o n ta in s th e m a in p r o g r a m f u n c tio n H o s t I O .c p p ec o n ta in s f u n c tio n s a n d o b je c ts f o r h o s t te r m in a l c o n tr o l S e g D is p la y .c p p ec o n ta in s f u n c tio n s a n d o b je c ts f o r s e v e n - s e g m e n t d is p la y o u tp u t. Th e fo llo win g asso ciated h ead er files are also req u ired : • • H o s t I O .h S e g D is p la y .h N o te th a t, b y c o n v e n tio n , th e m a in .c p p fi le d o e s n o t n e e d a h e a d e r fi le . T h e p r o g r a m fi le s tr u c tu r e in th e m b e d c o m p ile r s h o u ld b e s im ila r to th a t s h o w n in F ig u r e 6 .9 . N o te th a t mo d u lar files can b e created b y rig h t-click in g o n th e p ro ject n ame an d selectin g ‘New File’. T h e m a in .c p p fi le h o ld s th e s a m e m a in f u n c tio n c o d e a s b e f o r e , b u t w ith # in c lu d e d ir e c tiv e s to th e n e w h e a d e r fi le s . P r o g r a m E x a m p le 6 .5 d e ta ils th e s o u r c e c o d e f o r m a in .c p p . / * P r o g r a m E x a m p l e * / # i n c l u d e # i n c l u d e " m b e d . h " " H o s t I O . h " 6 . 5 : m a i n . c p p f i l e f o r m o d u l a r 7 - s e g k e y b o a r d c o n t r o l l e r 1 1 0 Chapter 6 # i n c l u c h a r d i n t m a S e g I H o s t w h i l d a S e d a S e p c } } d e a t i n n i I n e t a g 2 t a g 1 . p " a 1 ( ) t ( i t ( 1 2 = 1 = r i S e , { ) ; ( ) ) = S = S n t g D i s p l a y . h " d a t a 2 ; ; { G e e g G e e g f ( t K C o t K C o " e y n v e y n v " ) I n e r I n e r p u t ( t ( d a p u t ( t ( d a ) ; t a 2 ) ; ) ; t a 1 ) ; ; / / v / / m / / c / / c / / i / / / / / / / / / / a r a i a l a l n f c c c c d i a b l n p r l i n l i n i n i t a l l a l l a l l a l l i s p l e d e c o g r a m i t f u i t f u e l o o t o g e t o c o t o g e t o c o a y s p l a r a t i o n s n c n c p t n v t n v a c t i o n t i o n 1 s e r 2 n e r e s t k e a n d k e t a n o n t y p r o u y p r d o u h o s t d e s t p e s t p s u t s u t P r o g r a m E x a m p le 6 .5 S o u r c e c o d e fo r m a in .c p p F ig u r e 6 .9 : F ile s t r u c t u r e fo r m o d u la r s e v e n - s e g m e n t d is p la y p r o g r a m T h e S e g I n it ( ) a n d S e g C o n v e r t ( ) f u n c tio n s a r e to b e ‘ o w n e d ’ b y th e S e g D is p la y .c p p s o u r c e fi le , a s a r e th e B u s O u t o b je c ts n a m e d ‘ S e g 1 ’ a n d ‘ S e g 2 ’ . T h e r e s u ltin g S e g D is p la y .c p p fi le is s h o w n in P r o g r a m E x a m p le 6 .6 . / * P * / # i n c B u s O B u s O r o g r a m E x a m p l e 6 . 6 : S e g D i s p l a y . c p p f i l e f o r l u d e " S e g D i s p l a y . h " u t S e g 1 ( p 5 , p 6 , p 7 , p 8 , p 9 , p 1 0 , p 1 1 , p 1 2 ) ; u t S e g 2 ( p 1 3 , p 1 4 , p 1 5 , p 1 6 , p 1 7 , p 1 8 , p 1 9 , p 2 0 ) ; v o i d S e g I n i t ( v o i d ) { S e g 1 = S e g C o n v e r t ( 0 ) ; S e g 2 = S e g C o n v e r t ( 0 ) ; / / / / i n i t i a l i z e i n i t i a l i z e t o t o m o d u l a r / / / / 7 - s e g k e y b o a r d A , B , C , D , E , F , G , D P A , B , C , D , E , F , G , D P z e r o z e r o } c h a r c h a s w i c c S e g C o n v e r S e g B y t e t c h ( S e g V a s e 0 : S a s e 1 : S r t ( = 0 a l e g e g c h x 0 u e B y B y a r S e g V a l u e ) { 0 ; ) { t e = 0 x 3 F ; b r e a k ; t e = 0 x 0 6 ; b r e a k ; / / f u n c t i o n / / D P / / 0 / / 0 G F 0 E 1 0 ’ S e g C o n v e r t ’ 0 1 D 0 1 C B 0 1 A 1 1 1 1 0 b i n a r y b i n a r y c o n t r o l l e r F u r t h e r P r o g r a m m in g T e c h n iq u e s c a s c a s c a s c a s c a s c a s c a s c a s e 2 : e 3 : S e g S e g e 4 : S e g e 5 : S e g e 6 : S e g e 7 : S e g e 8 : S e g e 9 : S e g B y t B y t B y t B y t B y t B y t B y t B y t e = e = 0 x 5 0 x 4 e = 0 x 6 e = 0 x 6 e = 0 x 7 e = 0 x 0 e = 0 x 7 e = 0 x 6 B ; b r e b r e 6 ; b r e D ; b r e D ; b r e 7 ; b r e F ; b r e F ; b r e F ; a k ; a k ; a k ; a k ; a k ; a k ; a k ; a k ; / / 0 1 0 1 1 0 1 1 / / 0 1 0 0 1 1 1 1 b i n b i n / / 0 1 1 0 0 1 1 0 b i n / / 0 1 1 0 1 1 0 1 b i n / / 0 1 1 1 1 1 0 1 b i n / / 0 0 0 0 0 1 1 1 b i n / / 0 1 1 1 1 1 1 1 b i n / / 0 1 1 0 1 1 1 1 b i n 1 1 1 a r y a r y a r y a r y a r y a r y a r y a r y } r e t u r n S e g B y t e ; } P r o g r a m E x a m p le 6 .6 S o u r c e c o d e fo r S e g D is p la y .c p p N o te th a t S e g D is p la y .c p p fi le h a s a n # in c lu d e d ir e c tiv e to th e S e g D is p la y .h h e a d e r fi le . T h is is g iv e n in P r o g r a m E x a m p le 6 .7 . / * P r o g r a m E x a m p l e 6 . 7 : * / # i f n d e f S E G D I S P L A Y _ H # d e f i n e S E G D I S P L A Y _ H # i n c l u d e e x t e r n e x t e r n v o i d c h a r S e g D i s p l a y . h f i l e f o r m o d u l a r 7 - s e g k e y b o a r d c o n t r o l l e r " m b e d . h " B u s O u t B u s O u t S e g 1 ; S e g 2 ; S e g I n i t ( v o i d ) ; S e g C o n v e r t ( c h a r / / / / a l l o w a l l o w S e g V a l u e ) ; S e g 1 S e g 2 / / / / t o b e t o b e m a n i p u l a t e d m a n i p u l a t e d f u n c t i o n f u n c t i o n b y o t h e r o t h e r b y f i l e s f i l e s p r o t o t y p e p r o t o t y p e # e n d i f P r o g r a m E x a m p le 6 .7 S o u r c e c o d e fo r S e g D is p la y .h T h e D is p la y S e t a n d G e t K e y I n p u t f u n c tio n s a r e to b e ‘ o w n e d ’ b y th e H o s t I O .c p p s o u r c e fi le , a s is th e s e r ia l U S B in te r f a c e o b je c t n a m e d ‘ p c ’ . T h e H o s t I O .c p p fi le s h o u ld th e r e f o r e b e a s s h o w n in P r o g r a m E x a m p le 6 .8 . / * P r o g r a m E x a m p l e 6 . 8 : H o s t I O . c p p c o d e f o r m o d u l a r 7 - s e g * / # i n c l u d e " H o s t I O . h " S e r i a l p c ( U S B T X , U S B R X ) ; / / c o m m u n i c a t i o n t o h o s t P C v o i d H o s t I n i t ( v o i d ) { p c . p r i n t f ( " \ n \ r T y p e t w o d i g i t n u m b e r s t o b e k e y b o a r d \ n \ r " ) ; } c h a r G e t K e y c h a r c = p c . p r i n t f r e t u r n ( c I n p c ( " & 0 p u . g % c x 0 t ( e t " , F ) v o i d ) c ( ) ; c ) ; ; { / / / / / / g e t k e y b o a r d a s c i i d a t a p r i n t a s c i i v a l u e t o h o s t r e t u r n v a l u e a s n o n - a s c i i } P r o g r a m E x a m p le 6 .8 S o u r c e c o d e fo r H o s t I O .c p p P C t e r m i n a l c o n t r o l l e r 1 1 2 Chapter 6 / * P r o g r a m E x a m p l e * / # i f n d e f H O S T I O _ H 6 . 9 : H o s t I O . h c o d e f o r m o d u l a r 7 - s e g k e y b o a r d c o n t r o l l e r # d e f i n e H O S T I O _ H # i n c l u d e " m b e d . h " e x t e r n S e r i a l p c ; v o i d H o s t I n i t ( v o i d ) ; c h a r G e t K e y I n p u t ( v o i d ) ; / / / / / / a l l o w p c f u n c t i o n f u n c t i o n t o b e m a n i p u l a t e d p r o t o t y p e p r o t o t y p e b y o t h e r f i l e s # e n d i f P r o g r a m E x a m p le 6 .9 S o u r c e c o d e fo r H o s t I O .h T h e H o s tI O h e a d e r fi le , H o s t I O .h , is s h o w n in P r o g r a m E x a m p le 6 .9 . Create th e mo will n eed to c rig h t click in g rep licates Fig d u lar s reate a o n th e u r e 6 .9 e v e n - s e g m e n t d i s p l a y p r o j e c t g i v e n b y P r o g r a m E x a m p l e s 6 . 5 e6 . 9 . Y o u n ew p ro ject in th e mb ed co mp iler an d ad d th e req u ired mo d u lar files b y p ro ject an d selectin g ‘New File’. Hen ce, create a file stru ctu re wh ich . Yo u s h o u ld n o w b e a b le to c o m p ile a n d r u n y o u r m o d u la r p r o g r a m . U s e th e c ir c u it o f F ig u r e 6 .6 . n E x e r c is e 6 .3 C r e a t e a n a d v a n c e d m o d u la r p r o je c t w h ic h u s e s a h o s t t e r m in a l a p p lic a t io n a n d a s e r v o . T h e u s e a s p e c ifi m o v e s t a r e la t iv r in e d h e e p p u ts a p o s it io s e rv o t o s it io n v a lu e b e n . A n in p o 9 0 d e g , fo r e x a tw e e n 1 u t o f 1 m r e e s r ig h m p le t h e a n d 9 f o v e s th t. N u m v a lu e 5 ro m th e e s e rv o t b e rs b e t p o in t s k e y b o 9 0 w e e n th e s o a rd w d e g re e s 1 a n d e rv o to h ic h le ft 9 m th e m o a n d o v e c e n v e s th e s e rv o to a u s e r in p u t o f 9 th e s e rv o to te r. Y o u c a n r e u s e t h e G e t K e y In p u t ( ) fu n c t io n fr o m t h e p r e v io u s e x a m p le s . Y o u m a y a ls o n e e d t o c r e a t e a lo o k - u p t a b le fu n c t io n t o c o n v e r t t h e n u m e r ic a l in p u t v a lu e t o a s u it a b le p u ls e w id t h m o d u la t io n ( P W M ) d u t y c y c le v a lu e a s s o c ia t e d w it h t h e d e s ir e d s e r v o p o s it io n . n Th is ch ap ter h as sh o co d e wh ile allo win g p ro g rams wh ich allo d ev elo p men t can als en ab les reu se o f co d wn th at man ip u w larg e o b e ma e an d a fu n ctio n latio n o f mu lti-fu n ag ed th simp le a s are u se d ata. Th n ctio n al ro u g h a p p ro ach fu l fo is, in p ro je team to u p r allo win g u s to write tu rn , h as en ab led u s cts to b e p ro g rammed o f en g in eers an d with d atin g an d u p g rad in g clean an d read to create mo d u . Th e p ro g ram a mech an ism so ftware featu ab le lar th at res. F u r t h e r P r o g r a m m in g T e c h n iq u e s 1 1 3 C h a p t e r R e v ie w • We u se fu n ctio n s to allo w co d e to b e reu sab le an d easier to read . Fu n ctio n s can tak e in p u t d ata v alu es an d retu rn a sin g le d ata v alu e as o u tp n o t p o ssib le to p ass array s o f d ata to o r fro m a fu n ctio n . Flo wch arts an d p seu d o co d e can b e u sed to assist p ro g ram d esig n . Th e tech n iq u e o f mo d u lar p ro g rammin g in v o lv es d esig n in g a co mp a n u mb er o f so u rce files an d asso ciated h ead er files. So u rce files h o ld th n itio n s, wh ereas h ead er files h o ld fu n ctio n an d v ariab le d eclaratio n s. Th e C/Cþ þ co mp ilatio n p ro cess co mp iles all so u rce an d h ead er files to g eth er with p red efin ed lib rary files to g en erate an ex ecu tab le p ro g ram P re p ro c e s s o r d ire c tiv e s a re re q u ire d to e n s u re th a t c o m p ila tio n e rro rs v ariab le d eclaratio n s are av o id ed . Mo d u lar p ro g rammin g en ab les a n u mb er o f en g in eers to wo rk o n a sin tak in g resp o n sib ility fo r a p articu lar co d e featu re. • • • • • • u t; h o wev er, it is lete p ro g ram as e fu n ctio n d efian d lin k s th o se b in ary file. d u e to mu ltip le g le p ro ject, each Q u iz 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 1 0 . List th e ad v an tag es o f u sin g fu n ctio n s in a C p ro g ram. Wh at are th e limitatio n s asso ciated with u sin g fu n ctio n s in a C p ro g ram? Wh at is p seu d o co d e an d h o w is it u sefu l at th e so ftware d esig n stag e? Wh at is a fu n ctio n ‘p ro to ty p e’ an d wh ere can it b e fo u n d in a C p ro g ram? Ho w mu ch d ata can b e in p u t to an d o u tp u t fro m a fu n ctio n ? Wh at is th e p u rp o se o f th e p rep ro cesso r in th e C p ro g ram co mp ilatio n p ro cess? At wh at stag e in th e p ro g ram co mp ilatio n p ro cess are p red efin ed lib rary files imp lemen ted ? Wh en wo u ld it b e n ecessary to u se th e e x te r n sto rag e class sp ecifier in an mb ed C p ro g ram? W h y is th e # ifn d e f p re p ro c e s s o r d ire c tiv e c o m m o n ly u s e d in m o d u la r p ro g ra m h e a d e r files? D raw a p ro g ra m fl o w c h a rt w h ic h d e s c rib e s a p ro g ra m th a t c o n tin u o u s ly re a d s a n a n a lo g temp eratu re sen so r o u tp u t o n ce p er seco n d an d d isp lay s th e temp eratu re in d eg rees Celsiu s o n a th ree-d ig it sev en -seg men t d isp lay . C H A P T E R 7 S t a r t in g w it h S e r ia l C o m m u n ic a t io n C h a p t e r O u t lin e 7 .1 In t r o d u c in g S y n c h r o n o u s S e r ia l C o m m u n ic a t io n 7 .2 S e r ia l P e r ip h e r a l In t e r f a c e 1 1 7 7 .2 7 .2 7 .2 7 .2 .1 In tro d u .2 S P I o n .3 S e t t in g .4 C r e a t in c in th e u p g a g S m a n S P P I 1 1 b e d 1 m b e d I D a ta 1 1 5 7 1 9 S P I M a ste r L in k 1 2 1 1 1 9 7 .3 In t e llig e n t In s t r u m e n t a t io n a n d a S P I A c c e le r o m e t e r 7 .3 .1 In t r o d u c in g t h e A D X L 3 4 5 A c c e le r o m e t e r 7 .3 .2 D e v e lo p in g a S im p le A D X L 3 4 5 P r o g r a m 7 .4 E v a lu a t in g S P I 1 2 9 7 .5 T h e In t e r - In t e g r a t e d C ir c u it B u s 1 2 5 1 2 5 1 2 5 1 2 9 2 7 .5 .1 In t r o d u c in g t h e I C B u s 1 2 9 7 .5 .2 I2 C o n th e m b e d 1 3 1 7 .5 .3 S e t t in g u p a n I2 C D a t a L in k 1 3 1 7 .6 7 .7 7 .8 7 .9 C U E A o m m u n ic s in g t h e v a lu a t in g s y n c h ro n a t S R I2 o u in g w it h a n I2 C T e m p e r a t u r e S e n s o r F 0 8 U lt r a s o n ic R a n g e F in d e r 1 3 8 C 1 4 0 s S e r ia l D a t a C o m m u n ic a t io n 1 4 0 1 3 5 7 .9 .1 In t r o d u c in g A s y n c h r o n o u s S e r ia l D a t a 1 4 0 7 .9 .2 A p p ly in g A s y n c h r o n o u s C o m m u n ic a t io n o n t h e m b e d 1 4 1 7 .9 .3 A p p ly in g S y n c h r o n o u s C o m m u n ic a t io n w it h t h e H o s t C o m p u t e r 7 .1 0 M in i- P r o je c t : M u lt i- N o d e I2 C B u s C h a p t e r R e v ie w 1 4 4 Q u iz 1 4 5 R e fe re n c e s 1 4 5 7 .1 1 4 4 1 4 4 In t r o d u c in g S y n c h r o n o u s S e r ia l C o m m u n ic a t io n T h e r e is a n u n e n d in g n e e d in c o m p u te r s y s te m s to m o v e d a ta a r o u n d elo ts o f it. I n C h a p te r s 1 an d 2 we came acro ss th e id ea o f d ata b u ses, o n wh ich d ata flies b ack ward s an d fo rward s b etween d ifferen t p arts o f a co mp u ter. In th ese b u ses, d ata is tran sferred in p a ra llel. Th ere is F a s t a n d E f f e c t iv e E m b e d d e d S y s t e m s D e s ig n . D O I : 1 0 .1 0 1 6 /B 9 7 8 - 0 - 0 8 - 0 9 7 7 6 8 - 3 .0 0 0 0 7 - 6 Co p y rig h t Ó2 0 1 2 Elsev ier Ltd . All rig h ts reserv ed . 1 1 5 1 1 6 Chapter 7 o n e wire fo r each b it o f d ata, an d o n e o r two mo re to p ro v id e sy n ch ro n izatio n a d ata is tran sferred a wh o le wo rd at a time. Th is wo rk s well, b u t it req u ires a lo t o a lo t o f co n n ectio n s o n each d ev ice th at is b ein g in terco n n ected . It is b ad en o u g h d ev ic e , b u t fo r 1 6 o r 3 2 b its th e s itu a tio n is fa r w o rs e . A n a lte rn a tiv e to p a ra lle l c o m m u n ic a tio n is s e r ia l. H e re , a s in g le w ire is e ffe c tiv e ly u s e d fo r d a ta tra n s fe r b ein g sen t in tu rn . A few ex tra co n n ectio n s are almo st in ev itab ly n eed ed , fo r ex earth retu rn , an d sy n ch ro n izatio n an d co n tro l. n d co n tro l; f wires an d fo r an 8 -b it , with b its amp le fo r On ce we start ap p ly in g th e serial co n cep t, a n u mb er o f ch allen g es arise. Ho w d o es th e re c e iv e r k n o w w h e n e a c h b it b e g in s a n d e n d s , a n d h o w d o e s it k n o w w h e n e a c h w o rd b e g in s an d en d s? Th ere are sev eral way s o f resp o n d in g to th ese q u estio n s. A straig h tfo rward ap p ro ach is to sen d a clo ck sig n al alo n g sid e th e d ata, with o n e clo ck p u lse p er d ata b it. Th e d ata is syn ch ro n ized to th e clo ck . Th is id ea, called sy n ch ro n o u s serial co mmu n icatio n , is r e p r e s e n te d in F ig u r e 7 .1 . W h e n n o d a ta is b e in g s e n t, th e r e is n o m o v e m e n t o n th e c lo c k lin e . Ev ery time th e clo ck p u lses, h o wev er, o n e b it is o u tp u t b y th e tran smitter an d sh o u ld b e read in b y th e re c e iv e r. In g e n e ra l, th e re c e iv e r s y n c h ro n iz e s its re a d in g o f th e d a ta w ith o n e e d g e o f th e clo ck . In th is ex amp le it is th e risin g ed g e, h ig h lig h ted b y a d o tted lin e. A s im p le s e r ia l d a ta lin k is s h o w n in F ig u r e 7 .2 . E a c h d e v ic e th a t c o n n e c ts to th e d a ta lin k is so metimes called a n o d e. In th is fig u re, No d e 1 is d esig n ated Ma ster; it co n tro ls wh at is g o in g o n , a s it c o n tro ls th e c lo c k . T h e S la v e is s im ila r to th e m a s te r, b u t re c e iv e s th e c lo c k s ig n a l fro m th e master. A n e s s e n tia l f e a tu r e o f th e s e r ia l lin k s h o w n , a n d in d e e d o f m o s t s e r ia l lin k s , is a s h ift re g is te r. Th is is mad e u p o f a strin g o f d ig ital flip -flo p s, co n n ected so th at th e o u tp u t o f o n e is co n n ected to th e in p u t o f th e n ex t. Each flip -flo p h o ld s o n e b it o f in fo rmatio n . Ev ery time th e sh ift reg ister is p u lsed b y th e clo ck sig n al, each flip -flo p p asses its b it o n to its n eig h b o r o n o n e s id e a n d re c e iv e s a n ew b it fro m its o th e r n e ig h b o r. T h e o n e a t th e in p u t e n d c lo c k s in d a ta re c e iv e d fro m th e o u ts id e w o rld , a n d th e o n e o f th e o u tp u t e n d o u tp u ts its b it. T h e re fo re , a s th e clo ck p u lses th e sh ift reg ister can b e b o th feed in g in ex tern al d ata an d o u tp u ttin g d ata. Th e d ata h eld b y all th e flip -flo p s in th e sh ift reg ister can , mo reo v er, b e read all at th e same time, as a p arallel wo rd , o r a n ew v alu e can b e lo ad ed in . In su mmary , th e sh ift reg ister is an in cred ib ly u sefu l su b sy stem: it can co n v ert serial d ata to p arallel d ata, an d v ice v ersa, an d it can act as a s e ria l tra n s m itte r a n d /o r a s e ria l re c e iv e r. b it 0 b it 1 b it 2 b it 3 b it 4 S e r ia l D a ta Clo ck F ig u r e 7 .1 : S y n c h r o n o u s s e r ia l d a t a b it 5 b it 6 b it 7 S t a r t in g w it h S e r ia l C o m m u n ic a t io n No d e 1 1 1 7 No d e 2 (M a s te r) (S la v e ) P arallel read /write P arallel read /write SDO SDI Sh ift reg ister msb SDI d ata d ir e c tio n SDO ls b clo ck so u rce Sh ift reg ister msb SCLK ls b SCLK F ig u r e 7 .2 : A s im p le s e r ia l lin k . S D I: s e r ia l d a t a in ; S D O : s e r ia l d a t a o u t ; S C L K : s e r ia l c lo c k A s a n e x a m p le , s u p p o s e b o th s h if t r e g is te r s in F ig u r e 7 .2 a r e 8 - b it, i.e . e a c h h a s e ig h t fl ip flo p s. Each reg ister is lo ad ed with a n ew wo rd , an d th e master th en g en erates eig h t clo ck p u lses. Fo r each clo ck cy cle, o n e n ew b it o f d ata ap p ears at th e o u tp u t en d o f each sh ift reg ister, in d icated b y th e SDO (serial d ata o u tp u t) lab el. Each SDO o u tp u t is, h o wev er, co n n ected to th e in p u t (SDI: serial d ata in p u t) o f th e o th er reg ister. Th erefo re as each b it is clo ck ed o u t o f o n e reg ister, it is clo ck ed in to th e o th er. After eig h t clo ck cy cles, th e wo rd th at was in th e master sh ift reg ister is n o w in th e slav e, an d th e wo rd th at was in th e slav e sh ift reg ister is n o w h eld in th e master. Th e circu itry fo r th e ma an o th er micro co n tro ller th at allo ws serial d ata to cen tral p ro cessin g u n it ( 7 .2 ster is u su o r so me o b e sen t a CPU) an d ally th er n d r th e p laced with in p erip h eral d ev e c e iv e d , a n d in o u tsid e wo rld , a micro co ice. In g e terfaces b is called n tro ller. Th n eral, th e h etween th e a serial p o r e slav e mig h t b e ard ware circu itry micro co n tro lle r t. S e r ia l P e r ip h e r a l In t e r fa c e To en su p laces, d ay s is may g o in terfac re th at serial d ata lin k s are reliab sev eral stan d ard s o r p ro to co ls h th e u n iv e rs a l s e ria l b u s (U S B ). o n to d efin e o th er th in g s, su ch e (SPI) is a simp le p ro to co l th a 7 .2 .1 In t r o d u c in g S P I le, an d can b e ap p lied b y d ifferen t d ev ices in av e b een d efin ed . On e th at is v ery wid ely u A p ro to co l d efin es d etails o f timin g an d sig as th e ty p e o f co n n ecto r u sed . Serial p erip h t h as h ad a larg e in flu en ce in th e emb ed d ed d ifferen t sed th ese n als, an d eral wo rld . In th e early d ay s o f micro co n tro llers, b o th Natio n al Semico n d u cto rs an d Mo to ro la started in tr o d u c in g s im p le s e r ia l c o m m u n ic a tio n , b a s e d o n F ig u r e 7 .2 . E a c h f o r m u la te d a s e t o f r u le s g o v ern in g h o w th eir micro co n tro llers wo rk ed , an d allo wed o th ers to d ev elo p d ev ices th at 1 1 8 co u ld in itia acted Natio Chapter 7 in lly as n a terface co rrectly . fo rmally d esig n e a fo rmal stan d ard l Semico n d u cto rs Th ese b ecame d e fa cto stan d ard d as stan d ard s, b u t were ad o p ted . Mo to ro la called its stan d ard S e called th eirs Micro wire. Th ey a s, in o th er wo rd s b y o th ers to th e ria l Perip h era l In re v ery similar to th ey were n ev er p o in t wh ere th ey terfa ce (S PI) an d each o th er. It was n o t lo n g b efo re b o th SPI an d Micro wire were ad o p ted b y man u factu rers o f o th er in teg rated circu its (ICs), wh o wan ted th eir d ev ices to b e ab le to wo rk with th e n ew g en eratio n o f micro co n tro llers. Th e SPI h as b eco me o n e o f th e mo st d u rab le stan d ard s in th e wo rld o f electro n ics, ap p lied to sh o rt-d istan ce co mmu n icatio n s, ty p ically with in a sin g le p iece o f eq u ip men t. Th ere is n o fo rmal d o cu men t d efin in g SPI, b u t d atash eets fo r th e Mo to ro la 6 8 H C 1 1 (n o w a n o ld m ic r o c o n tro lle r) e ffe c tiv e ly d e fi n e it in fu ll. G o o d re la te d te x ts a ls o d o , f o r e x a m p le R e f e r e n c e 7 .1 . I n S P I o n e m ic ro c o n tro lle r is d e s ig n a te d th e m a s te r; it c o n tr o ls a ll a c tiv ity o n th e s e r ia l in te rc o n n e c tio n . T h e m a s te r c o m m u n ic a te s w ith o n e o r m o re s lav e s . A m in im u m S PI lin k u s e s ju s t o n e m a s te r a n d o n e s la v e , a n d f o llo w s th e p a tte r n o f F ig u r e 7 .2 . T h e m a s te r g e n e r a te s a n d c o n tro ls th e c lo c k , a n d h e n c e a ll d a ta tra n s fe r. T h e S DO o f o n e d ev ic e is c o n n e c te d to th e S DI o f th e o th e r, a n d v ic e v e rs a . In ev e ry c lo c k c y c le o n e b it is m o v e d fro m m a s ter to s lav e , a n d o n e b it fro m s lav e to m a s te r; a fte r e ig h t c lo ck cy c le s a w h o le b y te h a s b e e n tra n s fe rre d . T h u s , d a ta is a c tu a lly tr a n s f e r r e d in b o th d ir e c tio n s ein o ld te r m in o lo g y th is is c a lle d fu ll d u p le x ea n d it is u p to th e d ev ic e s to d e c id e w h e th e r a r e c e iv e d b y te is in te n d e d f o r it o r n o t. I f d a ta tr a n s f e r in o n ly o n e d ire c tio n is w a n te d , th e n th e d a ta tra n s fe r lin e th a t is n o t n e e d e d c a n b e o mitte d . If mo re th an o n e slav e is n eed ed , th en th e ap p is a c tiv e a t a n y tim e , d e te rm in e d b y w h ic h S th a t w ritin g S S in d ic a te s th a t th e lin e is a c tiv e b e SS. Th e termin o lo g y Ch ip Select (CS) is c h a p te r. O n ly th e s la v e a c tiv a te d b y its S S in o n ly o n e s la v e is a c tiv a te d a t a n y o n e tim e . T h r o a c h o f F ig u r e 7 .3 c a n b e u s e d . O n ly o n e s la v e la v e S e le c t (S S ) lin e th e m a s te r a c tiv a te s . N o te w h e n lo w ; if it w e re a c tiv e h ig h it w o u ld s im p ly also u sed fo r th e same ro le, in clu d in g in th is p u t resp o n d s to th e clo ck sig n al, an d n o rmally e m a s te r th e n c o m m u n ic a te s w ith th e o n e a c tiv e Po rt B its SS M ic ro c o n tro lle r (SPI Ma s te r) SS S la v e 1 SCK SDO SS S la v e 2 SDI SCK SDO SS S la v e 3 SDI SCK SDO S la v e 4 SDI SCK SDI SDO F ig u r e 7 .3 : S P I in t e r c o n n e c t io n s fo r m u lt ip le s la v e s SCK SDO SDI S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 1 9 s la v e ju s t a s in F ig u r e 7 .2 . N o tic e th a t f o r n s la v e s , th e m ic r o c o n tr o lle r n e e d s to c o m m it (3 þ n ) lin es. On e o f th e ad v an tag es o f serial co mmu n icatio n , th e small n u mb er o f in terco n n ectio n s, is b eg in n in g to d isap p ear. 7 .2 .2 SPI on the mbed A s th e m b e d d ia g r a m o f F ig u r e 2 .1 s h o w s , th e m b e d h a s tw o S P I p o r ts , o n e a p p e a r in g o n p in s 5 , 6 an d 7 , an d th e o th er o n p in s 1 1 , 1 2 an d 1 3 . Th e ap p licatio n p ro g rammin g in terface (API) s u m m a r y a v a ila b le f o r S P I m a s te r is s h o w n in Ta b le 7 .1 . 7 .2 .3 S e t t in g u p a n m b e d S P I M a s t e r P r o g r a m E x a m p le 7 .1 s h o w s a v e r y s im p le s e tu p f o r a S P I m a s te r. T h e p r o g r a m in itia liz e s th e SPI p o rt, ch o o sin g fo r it th e n ame s e r _ p o r t, with th e p in s o f o n e o f th e p o ssib le p o rts b ein g selected . Th e fo r m a t( ) fu n ctio n req u ires two v ariab les: th e first is th e n u mb er o f b its an d th e s e c o n d is th e m o d e . T h e m o d e is a f e a tu r e o f S P I w h ic h is illu s tr a te d in F ig u r e 7 .4 , w ith a s s o c ia te d c o d e s in Ta b le 7 .2 . I t a llo w s th e c h o ic e o f w h ic h c lo c k e d g e is u s e d to c lo c k d a ta in to th e sh ift reg ister (in d icated as ‘Data stro b e’ in th e d iag ram), an d wh eth er th e clo ck id les h ig h o r lo w. F o r m o s t a p p lic a tio n s th e d e f a u lt m o d e , i.e . M o d e 0 , is a c c e p ta b le . T h is p r o g r a m s im p ly a p p lie s d e f a u lt v a lu e s , i.e . 8 b its o f d a ta , a n d M o d e 0 f o r m a t. O n th e m b e d , a s w ith man y SPI d ev ices, th e same p in is u sed fo r SDI if in master mo d e, o r SDO if slav e. Hen ce, th is p in g ets to b e called MISO (master in , slav e o u t). Its p artn er p in is MOSI. / * P r o b y t e * / # i n c l u S P I s e c h a r s i n t g r a m E x a m p l e 7 . 1 : d e " m b e d . h " r _ p o r t ( p 1 1 , p 1 2 , w i t c h _ w o r d ; m a i s e r _ p s e r _ p w h i l e s w i s e r w a i } n ( o r o r ( t c _ p t _ ) t . t . 1 ) h _ o r u s { f o f r { w o t . ( 5 S e t s p 1 3 ) ; u p t h e m b e d a s / / m o s i , m i s o , / / w o r d w e w i l l r m a t ( 8 , 0 ) ; e q u e n c y ( 1 0 0 0 0 0 0 ) ; r d = 0 x A 1 ; w r i t e ( s w i t c h _ w o r d ) ; 0 ) ; / / / / S e t u p C l o c k S P I m a s t e r , a n d c o n t i n u o u s l y s e n d s a s i n g l e s c l k s e n d t h e S P I f o r 8 b i t f r e q u e n c y i s 1 M H z / / s e t u p w o r d t o b e / / s e n d s w i t c h _ w o r d d a t a , M o d e 0 o p e r a t i o n t r a n s m i t t e d } P r o g r a m E x a m p le 7 .1 Co mp ile (p in 1 1 ) d ata are can read sig n ific a , d an ac th n t M in im a l S P I m a s te r a p p lic a tio n o wn lo ad an d ru n Pro g ram Ex amp d clo ck (p in 1 3 ) lin e s simu ltan e o tiv e a t th e s a m e tim e , a n d v e rif y e tran smitte d d ata b y te, 0 x A1 . Is b it (LS B) se n t first? le u s th th 7 .1 o n ly o n a e clo c k e mo st a sin g le mb e n o s cillo sco p d ata freq u en sig n ific an t b d , e. cy it an d See . Ch (MS o b se rv e th e d ata h o w clo c k an d e ck th at y o u B) o r least 1 2 0 Chapter 7 T a b le 7 .1 : m b e d S P I m a s t e r A P I s u m m a r y F u n c t io n U s a g e S P I C r e a t e a S P I m a s t e r c o n n e c t e d t o t h e s p e c ifi e d p in s f o r m a t C o n fi g u r e t h e d a t a t r a n s m is s io n m o d e a n d d a t a le n g t h f r e q u e n c y S e t t h e S P I b u s c lo c k fr e q u e n c y w r i t e W r it e t o t h e S P I s la v e a n d r e t u r n t h e r e s p o n s e SS SCK, Mo d e 0 SCK, Mo d e 1 SCK, Mo d e 2 SCK, Mo d e 3 Data Data stro b e F ig u r e 7 .4 : P o la r it y a n d p h a s e T a b le 7 .2 : S P I m o d e s M o d e P o la r it y P h a s e 0 0 0 1 0 1 2 3 1 1 0 1 S t a r t in g w it h S e r ia l C o m m u n ic a t io n n 1 2 1 E x e r c is e 7 .1 1 . In P ro g r c lo c k a n F ig u r e 7 2 . S e t th e S 0 x 8 A 1 a o s c illo s c a m E x a m p le d d a ta w a v e .4 . P I fo rm a t o f n d 0 x 8 A A 1 , o p e . 7 .1 , t r y in v o k in g e a c h o f t h e S P I m o d e s in t u r n . O b s e r v e b o t h fo r m s o n t h e o s c illo s c o p e , a n d c h e c k h o w t h e y c o m p a r e t o P r o g r a m E x a m p le 7 .1 t o 1 2 a n d t h e n 1 6 b it s , s e n d in g t h e w o r d s r e s p e c t iv e ly ( o r t o y o u r c h o ic e ) . C h e c k e a c h o n a n n 7 .2 .4 C r e a t in g a S P I D a t a L in k We will n o w d ev elo p tw o p ro g rams, o n e ma ster an d o n e slav e, an d g et tw o mb ed s to co mmu n icate. Each will h av e two switch es an d two lig h t-emittin g d io d es (LEDs); th e aim will b e to g et th e switch es o f th e ma ster to co n tro l th e LED s o n th e slav e, an d v ice v ersa. sh o wn p o rt as o r d , th re c e iv e S 1 S 2 c o n n e c t to s e c o n d m b e d m o s i, m is o , s c k , s s e l, to to to to p in p in p in p in 1 1 1 2 1 3 1 4 as Pro g ram b efo re, an d e wo rd th at d fro m th e s G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 E x a m p le 7 .2 . T h is is w r d efin es th e switch in p u will b e sen t to th e slav lav e. Fo r th is ap p licatio m b e d M ic r o c o n tr o lle r Th e p ro g ram fo r th e master is F ig u r e 7 .5 . I t s e ts u p th e S P I d eclares a v ariab le s w itc h _ w r e c d _ v a l, wh ich is th e v alu e V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 7 .5 : U s in g S P I t o lin k t w o m b e d s itten fo ts o n p e, an d n th e d r th in s th e efa e circu it o f 5 an d 6 . It v ariab le u lt settin g s 1 2 2 Chapter 7 o f th e SPI p o main lo o p , th reco g n izab le in p u ts are th e is set, b y AN s w itc h _ w o r d acco rd in g ly . rt are ch o sen , so th ere is n o f e v alu e o f s w itc h _ w o r d is es o n th e o scillo sco p e, th e u p p er n tested in tu rn ; if th ey are fo u Din g with 0 x 0 1 o r 0 x 0 2 . Th e is mad e. Th e retu rn v alu e o f / * P r o g r a m E x a m p l e 7 . 2 . s e n d i n g i t s o w n s w i t c h * / # i n c l u d e " m b e d . h " S P D i D i D i D i D i c h c h I s g i t g i t g i t g i t g i t a r a r i n t m w h i / / s i e r a l a l a l a l a l s w r e _ p O u O u O u I n I n i t c d o r t t t s s c h _ v a i l e / D / S w i f n ( ) ( 1 ) e f a u e t u t c h _ ( s w i s w i t i f ( s w i s w i t c s = 0 ; r e c d _ v a c s = 1 ; w a i t ( 0 . / / r e g r r e i f s e d _ e e c d ( r i f ( g i f ( r g t l l e d n _ l _ v a r e c e d _ r e c r e e r e c e d _ r e e t ( r e g r c s w i w i _ w a l p 1 d _ e e ( p t c t c o r ; 1 , l e n _ 1 4 h _ h _ d s t h r d h _ _ w h _ _ w e t e = 0 i p o r i p o r p 1 d ( p l e d ) ; i p 1 i p 2 ; u rth er in itializatio n in th e p ro g ram. On ce in th e ta b lis h e d . To g iv e a p a tte rn to th is th a t w ill b e fo u r b its are set to h ex ad ecimal A. Th e two switch n d to b e h ig h , th e ap p ro p riate b it in s w itc h _ w o r d c s lin e is set lo w, an d th e co mman d to sen d th is fu n c tio n is th e re c e iv e d w o rd , w h ic h is re a d S e t s t h e m b e d u p a s M a s t e r , a n d p o s i t i o n s , a n d d i s p l a y i n g t h o s e 2 , p 1 3 ) ; / / m o s 2 5 ) ; / / r e d ( p 2 6 ) ; / / g r e e / / t h i s ( p 5 ) ; ( p 6 ) ; / / w o r d w e w i / / v a l u e r e t u i , m i s o , l e d n l e d a c t s a s l l r n s e n d f r o m e x c h a n g e s d a t a o f t h e s l a v e . w i t h a s l a v e , s c l k “ s l a v e s e l e c t ” s l a v e { { l t p w o t c c h t c c h t i w o x a 1 = d = 2 = d = n g r d 0 ; = 1 s w = 1 s w s f o r S P I M a s t e r c h o s e n , n o n e e d f o r f u r t h e r c o n f i g u r a t i o n t o b e s e n t , b y t e s t i n g s w i t c h i n p u t s / / s e t u p a r e c o g n i z a b l e o u t p u t p a t t e r n ) i t c h _ w o r d j0 x 0 1 ; / / O R i n l s b i t c h _ w o r d j0 x 0 2 ; / / O R i n n e x t l s b / / s e l e c t s l a v e / / s e n d s w i t c h _ w o r d ) l = s e r _ p o r t . w r i t e ( s w i t c h _ w o r d ) ; a n d r e c e i v e d a t a 0 1 ) ; e d = 0 e d l = d _ l e d _ n _ d _ l e n _ s a c c o r d i n g t o ; = 0 ; r e c v a l d = 1 v a l l e d v a l d = 1 l e d d _ = = ; = = = 1 = = ; = 1 v a l & 0 x 0 3 ; 1 ) i n c o m i n g / / p r e s e t / / A N D o u t w o r d b o t h f r o m t o 0 u n w a n t e d s l a v e b i t s 2 ) ; 3 ) { ; } } } P r o g r a m E x a m p le 7 .2 T h e m b e d s e t u p a s a S P I m a s te r, w ith b id ir e c tio n a l d a ta tr a n s fe r S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 2 3 T a b le 7 .3 : m b e d S P I s la v e A P I s u m m a r y S P I S l a v e F u n c t io n U s a g e C r e a t e a S P I s la v e c o n n e c t e d t o t h e s p e c ifi e d p in s f o r m a t C o n fi g u r e t h e d a t a t r a n s m is s io n fo r m a t f r e q u e n c y S e t t h e S P I b u s c lo c k fr e q u e n c y r e c e i v e P o ll t h e S P I t o s e e if d a t a h a s b e e n r e c e iv e d r e a d R e t r ie v e d a t a fr o m r e c e iv e b u ffe r a s s la v e r e p l y F ill t h e t r a n s m is s io n b u ffe r w it h t h e v a lu e t o b e w r it t e n o u t a s s la v e o n t h e n e x t r e c e iv e d m e s s a g e fr o m t h e m a s t e r T h e s la v e p r o g r a m d r a w s u p o n th e m b e d f u n c tio n s s h o w n in Ta b le 7 .3 , a n d is s h o w n a s P r o g r a m E x a m p le 7 .3 . I t is a lm o s t th e m ir r o r im a g e o f th e m a s te r p r o g r a m , w ith s m a ll b u t k e y d ifferen ces. Th is emp h asizes th e v ery clo se similarity b etween th e master an d slav e ro le in SPI. Let u s ch eck th e d ifferen ces. Th e serial p o rt is in itialized with S P I S la v e . No w fo u r p in s mu st b e d efin ed , th e ex tra b ein g th e slav e select in p u t, s s e l. As th e slav e will also b e g en eratin g a wo rd to b e s e n t, a n d re c e iv in g o n e , it a ls o d e c la re s v a ria b le s s w itc h _ w o r d a n d r e c d _ v a l. C h a n g e th ese n ames if y o u wo u ld rath er h av e so meth in g d ifferen t. Th e slav e p ro g ram co n fig u res its s w itc h _ w o r d ju st lik e th e master. No w co mes a d ifferen ce. Wh ile th e master in itiates a tran smissio n wh en it wish es, th e slav e mu st wait. Th e mb ed lib rary d o es th is with th e r e c e iv e ( ) fu n c tio n . T h is re tu rn s 1 if d a ta h a s b e e n re c e iv e d , a n d 0 o th e rw is e . O f c o u rs e , if d a ta h a s b e e n re c e iv e d fro m th e m a s te r, th e n d a ta h a s a ls o b e e n s e n t fro m s la v e to m a s te r. If th e re is d ata, th en th e slav e read s th is an d sets u p th e LEDs acco rd in g ly . It also sets u p th e n ex t wo rd to b e sen t to th e master, b y tran sferrin g its s w itc h _ w o r d to th e tran smissio n b u ffer, u sin g r e p ly ( ). / * s e * / # i S P D i D i D i D i c h c h P r o g r a m E x a m p l e 7 . 3 : n d i n g i t s o w n s w i t c h n c l I S l g i t g i t g i t g i t a r a r i n t m / / d w h i / s i u d e a v e a l O a l O a l I a l I s w i r e c a i e f l e / s w i f d " m b s e r t r t g s w s w c h _ _ v a n ( a u ( 1 e t t c ( s s w ) { l t f ) { u p h _ w o w i t c i t c h u u n n t e d . _ p o e d _ r e e i t c i t c w o r l ; h " r t l e n _ h _ h _ d ( p 1 d ( p l e d i p 1 i p 2 1 , 2 5 ( p ( p ( p p 1 ) ; 2 6 5 ) 6 ) 2 , p 1 3 , p 1 4 ) ; ) ; ; ; ; i t = 0 i p o r / / m o s i , m i s o , / / r e d l e d / / g r e e n l e d s c l k , s s e l / / w o r d w e w i l l s e n d / / v a l u e r e c e i v e d f r o m o r m a t t i n g s w r d h _ _ w S e t s t h e m b e d u p a s S l a v e , a n d e x c h a n g e s d a t a w i t h a M a s t e r , p o s i t i o n s , a n d d i s p l a y i n g t h o s e o f t h e M a s t e r . a s S P I s l a v e . c h x a 1 = d = m a s t e r a p p l i e d _ w o r d f r o m s w i t c h e s 0 ; / / s e t u p a = 1 ) s w i t c h _ w o r d j0 x 0 1 ; t h a t a r e p r e s s e d r e c o g n i z a b l e o u t p u t p a t t e r n 1 2 4 Chapter 7 i f ( s s w i f ( s e r e s e } / / n o w . ( c o n t . w i i t r _ c d r _ t c c h p o _ v p o h _ _ w r t a l r t i p 2 o r d . r e = . r e s e t l e d s i n u e s a s = = = s c e s e p l 1 ) w i i v r _ y ( t c e ( p o s w h _ w o r d j0 x 0 ) ) { / / r t . r e a d ( ) i t c h _ w o r d a c c o r d i n g i n P r o g r a m t o 2 ; t e s t i f d a t a t r a n s f e r h a s o c c u r r e d ; / / R e a d b y t e f r o m m a s t e r ) ; / / M a k e t h i s t h e n e x t r e p l y r e c e i v e d E x a m p l e w o r d 7 . 2 ) } } P r o g r a m E x a m p le 7 .3 No w co n n each is p o i.e . p in 1 1 y o u d o n o master, an T h e m b e d s e t u p a s a S P I s la v e , w ith b id ir e c tio n a l d a ta tr a n s fe r ect two mb ed s to g eth er, carefu lly ap p ly in g th e circu it o f Fig u re w e re d in d iv id u a lly th ro u g h its o w n U S B c a b le . C o n n e c tio n s to g o es to p in 1 1 an d so o n , so it d o es n o t matter wh ich is ch o sen a t wan t to set u p th e fu ll circu it straig h t away , th en co n n ect ju st d ju st th e LEDs to th e slav e, o r v ice v ersa. C o m p ile a n d d o w n lo a d P r o g r a m E x a m p le 7 .2 in P r o g r a m E x a m p le 7 .3 in to th e o th e r. O n c e y o u p ressin g th e switch es o f th e master co n tro ls th e an o th er b ig step fo rward ; we are co mmu n icatin g fro m o n e sy stem to an o th er. n 7 .5 . I t is s im p le s t if b o th are id en tical, s master o r slav e. If th e switch es to th e to o n e mb ed (wh ich will b e th ru n th e p ro g rams, y o u sh o u ld LEDs o f th e slav e, an d v ice d ata fro m o n e micro co n tro lle e master), an d fin d th at v ersa. Th is is r to an o th er, o r E x e r c is e 7 .2 T ry tra n 1 . 2 . 3 . 4 . th e fo s m is s R e m o R e m o R e m o R e m o llo io n v e v e v e v e N o t ic e t h a t y o u m ig h t g a n e x a m p le in t e r p r e t e d w in g , a n fro m m t h e p in 1 t h e p in 1 t h e p in 1 t h e p in 1 in s e t o o f t b y a d b e a s te r 1 lin 2 lin 3 lin 4 lin o m e c a s e s d d in t e r m h e im p a c t n m b e d in s u to k , k , k , k , re y s la i.e . i.e . i.e . i.e . o v t t t t u u n d e rs ta n e , a n d fro m h e d a t a lin k h e d a t a lin k h e c lo c k . h e c h ip s e le c d t s la fro fro h e v e m m r e s u lt . In e a c h c a s e t e s t fo r d a t a to m a s te r. m a s t e r t o s la v e . s la v e t o m a s t e r . t lin e . if y o u d is c o n n e c t a w ir e , b u t le a v e it d a n g lin g in t h e a ir , it t e n t b e h a v io r w h ic h c h a n g e s if y o u t o u c h t h e w ir e . T h is is o f e le c t r o m a g n e t ic in t e r fe r e n c e , w h e r e in t e r fe r e n c e is b e in g p u t a s a c lo c k o r d a t a s ig n a l. n S t a r t in g w it h S e r ia l C o m m u n ic a t io n 7 .3 1 2 5 In t e llig e n t In s t r u m e n t a t io n a n d a S P I A c c e le r o m e t e r 7 .3 .1 In t r o d u c in g t h e A D X L 3 4 5 A c c e le r o m e t e r Desp ite (o r b ecau se o f ) its ag e, th e SPI stan d ard is wo n d erfu lly simp le, an d h en ce wid ely u s e d . It is e m b e d d e d in to a ll s o rts o f e le c tro n ic d ev ic e s , IC s a n d g a d g e ts . G iv e n a n u n d erstan d in g o f h o w SPI wo rk s, we can n o w co mmu n icate with an y o f th ese. With th e v ery h ig h lev el o f in teg ratio n fo u n d in mo d ern ICs, it is co mmo n to fin d a sen so r, sig n al co n d itio n in g , an an alo g -to -d ig ital co n v erter (ADC) an d a d ata in terface, all co mb in ed o n to a sin g le ch ip . Su ch d ev ices are p art o f th e n ew g en eratio n o f in tellig en t in stru men ta tio n . In stead o f ju st h av in g a stan d -alo n e sen so r, as we d id with th e lig h t-d ep en d en t resisto r in Ch ap ter 5 , we can n o w h av e a co mp lete measu remen t su b sy stem in teg rated with th e sen so r, with a co n v en ien t serial d ata o u tp u t. Th e ADXL3 4 5 accelero meter, mad e b y An alo g Dev ices, is an ex amp le o f an in teg rated ‘ in te llig e n t’ s e n s o r. I ts d a ta s h e e t a p p e a r s a s R e f e r e n c e 7 .2 . T h is is a ls o a n e x a m p le o f a micro electro mech a n ica l system (MEMS), in wh ich th e accelero meter mech an ics are actu ally fab ricated with in th e IC stru ctu re. Th e accelero meter o u tp u t is an alo g in n atu re, an d measu res acceleratio n in th ree ax es. Th e accelero meter h as an in tern al cap acito r mo u n ted in th e p lan e o f each ax is. Acceleratio n cau ses th e cap acito r p lates to mo v e, h en ce ch an g in g th e o u tp u t v o ltag e in p ro p o rtio n to th e acceleratio n o r fo rce. Th e ADXL3 4 5 accelero meter co n v erts th e an alo g v o ltag e flu ctu atio n s to d ig ital an d can o u tp u t th ese v alu es o v er a SPI serial lin k (o r I2 C; see later in th is ch ap ter). Co n Ex a mak reco mad 9 .8 1 tro l o f th e ADXL3 4 5 is d o n e b y writin g to a se t o f reg is te m p le s o f th e s e a r e s h o w n in Ta b le 7 .4 . I t is c le a r th a t th e d in g d irect me asu remen ts. It is p o ssib le to c alib rate it, ch an g n iz e certa in ev en ts , fo r ex amp le wh e n it is tap p ed o r in f e in terms o f g (wh ere 1 g is th e v alu e o f acceleratio n d u e ms 2). rs th ro u g h th e s eria l lin ev ic e g o es w e ll b ey o n d g e its ran g e an d en ab le ree fall. Measu remen ts to e a r th ’s g r a v ity , i.e . k . ju st it to are Th e ADXL3 4 5 IC is ex tremely small an d d esig n ed fo r su rface mo u n tin g o n a p rin ted circu it b o a r d ; th e r e f o r e , it is r e a d y - m o u n te d o n a ‘ b r e a k o u t’ b o a r d , a s s h o w n in F ig u r e 7 .6 . I t w o u ld o th erwise b e d ifficu lt to h an d le. 7 .3 .2 Pro g r o u tp u an d 1 Tab le D e v e lo p in g a S im p le A D X L 3 4 5 P r o g r a m a m E x a m p le 7 .4 a p p lie s th e A D X L 3 4 5 , r e a d in g a c c e le r a tio n in th r e e a x e s , a n d ttin g th e d a ta to th e h o s t c o m p u te r s c r e e n . T h e s e c o n d S P I p o r t ( i.e . p in s 1 1 , 1 2 3 ) is u sed fo r co n n ectin g th e accelero meter, ap p ly in g th e co n n ectio n s sh o wn in 7 .5 . 1 2 6 Chapter 7 T a b le 7 .4 : S e le c t e d A D X L 3 4 5 r e g is t e r s A d d re s s * N a m e D e s c r ip t io n 0 x0 0 D E V ID D e v ic e ID 0 x1 D T H R E S H _ T A P T a p t h r e s h o ld 0 x1 E / 1 F / 2 0 O F S X , O F S Y , O F S Z x , y , z -a x is o ffs e t s 0 x2 1 D U R T a p d u r a t io n 0 x2 D P O W E R _ C T L P o w e r - s a v in g fe a t u r e s c o n t r o l. D e v ic e p o w e r s u p in s t a n d b y m o d e ; s e t t in g b it 3 c a u s e s it t o e n t e r M e a s u r e m o d e 0 x3 1 D A T A _ F O R M A T D a ta fo rm a t c o n tro l B it s : 7 : fo r c e a s e lf- t e s t b y s e t t in g t o 1 6 : 1 ¼ 3 - w ir e S P I m o d e ; 0 ¼ 4 - w ir e S P I m o d e 5 : 0 s e t s in t e r r u p t s a c t iv e h ig h , 1 s e t s t h e m a c t iv e lo w 4 : a lw a y s 0 3 : 0 ¼ o u t p u t is 1 0 - b it a lw a y s ; 1 ¼ 2 : 1 ¼ le ft a lig n r e s u lt ; 0 ¼ 1 -0 : 0 0 ¼ 2 g; 0 1 ¼ o u t p u t d e p e n d s o n r a n g e s e t t in g r ig h t a lig n r e s u lt 4 g; 1 0 ¼ 8 g; 1 1 ¼ 2 g 0 x 3 3 :0 x 3 2 D A T A X 1 :D A T A X 0 x - a x is d a t a , fo r m a t t e d a c c o r d in g t o D A T A _ F O R M A T , in 2 ’s c o m p le m e n t . 0 x 3 5 :0 x 3 4 D A T A Y 1 :D A T A Y 0 y - a x is d a t a , a s a b o v e 0 x 3 7 :0 x 3 6 D A T A Z 1 :D A T A Z 0 z -a x is d a t a , a s a b o v e * I n a n y d a t a t r a n s f e r t h e r e g i s t e r a d d r e s s i s s e n t fi r s t , a n d f o r m e d : b i t 7 ¼ R =W ( 1 f o r r e a d , 0 f o r w r i t e ) ; b i t 6 : 1 f o r m u l t i p l e b y t e s , 0 fo r s in g le ; b it s 5 - 0 : t h e lo w e r 6 b it s fo u n d in t h e A d d r e s s c o lu m n . F ig u r e 7 .6 : T h e A D X L 3 4 5 a c c e le r o m e t e r o n b r e a k o u t b o a r d . ( Im a g e r e p r o d u c e d w it h p e r m is s io n o f S p a r k F u n E le c t r o n ic s ) S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 2 7 T a b le 7 .5 : A D X L 3 4 5 p in c o n n e c t io n s t o m b e d A D X L 3 4 5 s ig n a l n a m e m b e d p in V c c V o u t G n d G n d S C L 1 3 M O S I 1 1 M IS O 1 2 C S 1 4 Th e p ro g ram in itializes a master SPI p o rt, wh ich we h av e ch o sen to call a c c , an d sets u p th e USB lin k to th e h o st co mp u ter. It fu rth er d eclares two array s; o n e is a b u ffer th at will h o ld d ata read d irect fro m th e accelero meter’s reg isters, two fo r ax is. Th e seco n d array ap p lies th e in t1 6 _ t sp ecifier. Th is is fro m th e C stan d ard lib rary t; it tells th e co mp iler th at ex actly 1 6 -b it (sig n ed ) in teg er ty p e d ata is b ein g d eclared . Th is w ill h o ld th e fu ll a c c e le ro m e te r a x is v a lu e s , c o m b in e d fro m th e tw o b y te s re c e iv e d fro m eg isters. C c o d e fe a tu re each s td in array th e r Th e main fu n ctio n in itializes th e SPI p o rt in a man n er with wh ich we are familiar. It th en lo ad s two o f th e accelero meter reg isters, writin g th e ad d ress first, fo llo wed b y th e d ata b y te. It sh o u ld b e p o ssib le to wo rk o u t wh at is b ein g written b y lo o k in g at eith er th e d atash eet o r Ta b le 7 .4 . A c o n tin u o u s w h ile lo o p is th e n in itia te d . F o llo w in g a p a u s e , a m u lti- b y te r e a d is s e t u p , u s in g a n a d d r e s s w o r d f o r m e d f r o m in f o r m a tio n s h o w n in Ta b le 7 .4 . T h is fi lls th e b u f f e r a r r a y . T h e d a t a a r r a y is th e n p o p u la te d , c o n c a te n a tin g ( i.e . c o m b in in g to f o r m a s in g le n u mb er) p airs o f b y tes fro m th e b u ffe r array . Th ese v alu es are th en scaled to actu al g v alu es, u s in g th e c o n v e r s io n f a c to r f r o m th e d a ta s h e e t, o f 0 .0 0 4 g p e r u n it. R e s u lts a r e th e n d is p la y e d o n -screen . / * P r o g r a m E x a m p l e 7 . 4 : R e a d s v a l u e s c o n t i n u o u s l y t o t e r m i n a l s c r e e n . * / # i n S P I D i g S e r c h a i n t f l o i n t c l a i t i a r 1 6 a t u d c c a l l b u _ t x e ( p O u p c f f d , " m 1 1 t ( U e r a t y , b e , p c s S B [ 6 a [ z d . 1 2 ( p T X ] ; 3 ] ; h “ , p 1 3 ) ; 1 4 ) ; , U S B R X ) ; ; m a i n ( ) { c s = 1 ; a c c . f o r m a t ( 8 , 3 ) ; / / s / / u / / s / / r a / / 1 / / f e t s e e t w d 6 - b l o a f r o m a c c e l e r o m e t e r u p S P I i p i n 1 4 a u p U S B i a t a a r r a i t t w o s t i n g p o i n t s n t y c o n t e r c h e r t y m p d f a i p f a p e l e a t / / i n i t i a l l y A D X L 3 4 5 / / 8 b i t d a t a , M o d e t h r o u g h c e o n p s e l e c t c e t o h c h a r m e n t i n a , t o b i s 3 n o t S P I , a n d i n s 1 1 , 1 2 , 1 3 o s t t e r m i n a l t e g e r d a t a e d i s p l a y e d a c t i v a t e d o u t p u t s o n - s c r e e n 1 2 8 Chapter 7 a c c s a c a c c s c s a c a c c s w h c . = 0 c . c . = 1 = 0 c . c . = 1 i l w a c s a c f o f r e q u e n c y ( 2 0 0 0 0 0 0 ) ; / / / / / / / / / / / / / / / / / / / / ; w r w r ; ; w r w r ; e i t = 0 c . i t e ( 0 x 3 1 ) ; i t e ( 0 x 0 B ) ; i t e ( 0 x 2 D ) ; i t e ( 0 x 0 8 ) ; ( 1 ( 0 ; w r r ( i b u f f ) { 2 s e d f e n s t p m e n i M H l e a t o r d a r o w e a d n f z c t a m a o f t e r s u o f i n c l t f o t t a c r e t i t o c h e r m + / r a n e t r m r a e k a r d e t 1 6 s m t r d e s m o o n w l o n l a t v i r e g , i s r a e g e c e g i 0 s i n s i s s t . 0 o n m i t e e r 0 4 g / L S B s s i o n r i s s i o n p . 2 ) ; / / s t a r t a t r a n s m i s s i o n i t e ( 0 x 8 0 j0 x 4 0 j0 x 3 2 ) ; / / R W b i t h i g h , M B b i t h i g h , n t i = 0 ; i < = 5 ; i + + ) { e r [ i ] = a c c . w r i t e ( 0 x 0 0 ) ; / / r e a d b a c k 6 d a t a p l u s a d d r e s s b y t e s } c s d a d a d a x = = 1 t a t a t a 0 . ; [ 0 [ 1 [ 2 0 0 ] = b u ] = b u ] = b u 4 * d a t a f f f f f f [ 0 p c . p r i n t f ( " x = e r [ 1 e r [ 3 e r [ 5 ] ; y ] < ] < ] < = 0 < 8 < 8 < 8 . 0 0 j b j b j b 4 * % + 1 . 2 f g \ t y u f u f u f d a 0 ] 2 ] 4 ] ] ; / / e n d o f t r a n s m i s s i o n / / c o m b i n e M S B a n d L S B f e f e f e t a r [ r [ r [ [ 1 ; = % + 1 . 2 f g \ t ; ; z = 0 . 0 0 4 * d a t a [ 2 ] ; z = / / c o n v e r t t o f l o a t , / / a c t u a l g v a l u e % + 1 . 2 f g \ n \ r " , x , y , z ) ; / / p r i n t } } P r o g r a m E x a m p le 7 .4 sc r e e n A c c e le r o m e te r c o n tin u o u s ly o u tp u ts th r e e -a x is d a ta to te r m in a l C a r e f u lly m a k e th e c o n n e c tio n s o f Ta b le 7 .5 , a n d c o m p ile , d o w n lo a d a n d r u n th e c o d e o n y o u r mb ed . Op en a Tera Term screen (as d escrib ed in Ap p en d ix E) o n y o u r co mp u ter. A c c e le r o m e te r r e a d in g s s h o u ld b e d is p la y e d to th e s c r e e n . Yo u w ill s e e th a t w h e n th e accelero meter is flat o n a tab le th e z-ax is sh o u ld read ap p ro x imately 1 g , with th e x- an d y-ax es ap p ro x imately 0 g . As y o u ro tate an d mo v e th e d ev ice th e g read in g s will ch an g e. If th e accelero meter is sh ak en o r d isp laced at a q u ick rate, g v alu es in ex cess o f 1 g can b e o b serv ed . No te th at th ere are so me in accu racies in th e accelero meter d ata, wh ich can b e red u ced in a real ap p licatio n b y d ev elo p in g co n fig u ratio n /calib ratio n ro u tin es an d d ata av erag in g fu n ctio n s. Alth o u g h we h av e n o t u sed it h ere, th e mb ed site p ro v id es an ADXL3 4 5 lib rary , lo cated in th e Co o k b o o k . Th is simp lifies u se o f th e accelero meter, an d sav es wo rry in g ab o u t reg ister ad d resses an d b it v alu es. n E x e r c is e 7 .3 R e w r it e P r o g r a m E x a m p le 7 .4 u s in g t h e lib r a r y fu n c t io n s a v a ila b le o n t h e m b e d s it e C o o k b o o k . n S t a r t in g w it h S e r ia l C o m m u n ic a t io n 7 .4 1 2 9 E v a lu a t in g S P I T h e S P I s ta n d a r d is e x tre m e ly e ffe c tiv e . T h e e le c tro n ic h a rd w a re is s im p le a n d th e r e fo re ch eap , an d d ata can b e tran sferred rap id ly . It d o es h av e its d isad v an tag es, h o wev er. Th ere is n o a c k n o w le d g m e n t fro m th e re c e iv e r, s o in a s im p le s y s te m th e m a s te r c a n n o t b e s u re th a t d a ta h a s b e e n re c e iv e d . A ls o th e re is n o a d d re s s in g . In a s y s te m w h e re th e re a re m u ltip le s la v e s , a s e p a r a te S S lin e m u s t b e r u n to e a c h s la v e , a s s h o w n in F ig u r e 7 .3 . T h e r e f o r e , w e b e g in to lo s e th e a d v a n ta g e th a t s h o u ld c o m e f r o m s e r ia l c o m m u n ic a tio n s , i.e . a lim ite d n u mb er o f in terco n n ect lin es. Fin ally , th ere is n o erro r ch eck in g . Su p p o se so me electro mag n etic in terferen ce was ex p erien ced in a lo n g d ata lin k ; th e d ata o r clo ck wo u ld b e c o r r u p te d , b u t th e s y s te m w o u ld h a v e n o w a y o f d e te c tin g th is o r c o r r e c tin g f o r it. Yo u m a y h a v e e x p e r ie n c e d th is in a s m a ll w a y in E x e r c is e 7 .2 . O v e r a ll, S P I c o u ld b e g r a d e d a s : s im p le , co n v en ien t an d lo w co st, b u t n o t ap p ro p riate fo r co mp lex o r h ig h -reliab ility sy stems. 7 .5 7 .5 .1 T h e In t e r -In t e g r a t e d C ir c u it B u s In t r o d u c in g t h e I2 C B u s Th e in ter-in teg rated circu it (I2 C) stan d ard was d ev elo p ed b y Ph ilip s to reso lv e so me o f th e p e rc e iv e d w e a k n e s s e s o f S P I a n d its e q u iv a le n ts . A s its n a m e s u g g e s ts , it is a ls o in te n d e d fo r in terco n n ectio n o v er sh o rt d istan ces an d g en erally with in a p iece o f eq u ip men t. It u ses o n ly P o w e r s u p p ly P u ll-u p re s is to rs M ic ro c o n tro lle r 1 's t r a y ' c a p a c ita n c e S CL to o th e r p e rip h e ra ls a n d m ic ro c o n tro lle rs S DA P e rip h e ra l 1 P e rip h e ra l 2 F ig u r e 7 .7 : A n I C -b a se d sy ste m 2 P e rip h e ra l 3 1 3 0 Chapter 7 two in terco n n ect wires, b u t man y d e (serial clo ck ) an d SDA (serial d ata). s h o w n in F ig u r e 7 .7 . T h e S D A lin e o n ly o n e d irectio n at an y o n e time. a sy n ch ro n o u s serial stan d ard . v ices All d is b id In th are co n n ecte ev ices o n th e irectio n al, so e jarg o n th is d to th e b b u s are c d ata can is called u s. T o n n e trav h a lf h ese lin es cted to th e el in eith e d u p lex. L are called SCL se two lin es, as r d irectio n , b u t ik e SPI, it is On e o f th e in terestin g featu res o f I2 C, an d o n e th at mak es it v ersatile, is th at an y n o d e co n n ected to it can o n ly p u ll d o wn th e SCL o r SDA lin e to Lo g ic 0 ; it can n o t fo rce th e lin e u p to Lo g ic 1 . Th is ro le is p lay ed b y a sin g le p u ll-u p resisto r co n n ected to each lin e. Wh en a n o d e p u lls a lin e to Lo g ic 0 an d th en releases it, it is retu rn ed to Lo g ic 1 b y th e actio n o f th e p u ll-u p resisto r. Th ere is, h o wev er, cap acitan ce asso ciated with th e lin e. Alth o u g h th is is lab eled ‘stray ’ cap acitan ce in F ig u r e 7 .7 , it is in r e a lity m a in ly u n a v o id a b le c a p a c ita n c e th a t e x is ts in th e s e m ic o n d u c to r stru ctu res co n n ected to th e lin e. Th is cap acitan ce is th u s h ig h er if th ere are man y n o d es co n n ected , an d lo wer o th erwise. Th e h ig h er th e cap acitan ce an d /o r p u ll-u p resistan ce, th e lo n g er th e rise time o f th e lo g ic tran sitio n fro m 0 to 1 . Th e I2 C stan d ard req u ires th at th e rise tim e o f a s ig n a l o n S C L o r S DA m u s t b e le s s th a n 1 0 0 0 n s . G iv e n a k n o w n b u s s e tu p , it is p o ssib le to p erfo rm reaso n ab ly p recise calcu latio n s o f p u ll-u p resisto r req u ired (see Referen ce 1 .1 ) , p a r tic u la r ly if y o u n e e d to m in im iz e p o w e r c o n s u m p tio n . F o r s im p le a p p lic a tio n s d e f a u lt p u l l - u p r e s i s t o r v a l u e s , i n t h e r a n g e 2 . 2 e4 . 7 k U , a r e q u i t e a c c e p t a b l e . Th e I2 C p ro to co l h as b een th ro u g h sev eral rev isio n s, p o ssib le sp eed s an d reflect tech n o lo g ical ch an g es, fo o p eratin g v o ltag es. Th e o rig in al v ersio n , stan d ard mo Ve r s io n 1 .0 , in 1 9 9 2 , in c r e a s e d th e m a x im u m d a ta r a estab lish ed an d still p ro b ab ly acco u n ts fo r mo st I2 C in c r e a s e d th e p o s s ib le b it r a te to 3 .4 M b it/s . Ve r s io n m a n n e r in R e f e r e n c e 7 .3 , a n d f o r m s th e b a s is o f th e wh ich h av e d ramatically in creased th e r ex amp le in red u ced min imu m d e, allo wed d ata rates u p to 1 0 0 k b it/s. te to 4 0 0 k b it/s. Th is latter is v ery well im p le m e n ta tio n . Ve r s io n 2 .0 , in 1 9 9 8 , 3 is d efin ed in a su rp risin g ly read ab le fo llo win g d escrip tio n . No d es o n an I2 C b u s can act as master o r slav e. Th e master in itiates an d termin ates tran sfers, an d g en erates th e clo ck . Th e slav e is an y d ev ice ad d ressed b y th e master. A sy stem may h av e m o re th a n o n e m a s te r, a lth o u g h o n ly o n e m a y b e a c tiv e a t a n y tim e . T h e re fo re m o re th a n o n e micro co n tro ller co u ld b e co n n ected to th e b u s, an d th ey can claim th e master ro le at d ifferen t times, wh en n eed ed . An arb itratio n p ro cess is d efin ed if mo re th an o n e master attemp ts to co n tro l th e b u s. A d ata tran sfer is mad e u p o f th e master sig n alin g a sta rt co n d itio n , fo llo wed b y o n e o r two b y te s c o n ta in in g a d d r e s s a n d c o n tr o l in f o r m a tio n . T h e s ta r t c o n d itio n ( F ig u r e 7 .8 a ) is d e fi n e d b y a h ig h to lo w tran sitio n o f SDA wh en SCL is h ig h . All su b seq u en t d ata tran smissio n f o llo w s th e p a tte r n o f F ig u r e 7 .8 b . O n e c lo c k p u ls e is g e n e r a te d f o r e a c h d a ta b it, a n d d a ta may o n ly ch an g e wh en th e clo ck is lo w. Th e b y te fo llo win g th e start co n d itio n is mad e u p o f s e v e n a d d r e s s b its a n d o n e d a ta d ir e c tio n b it, a s s h o w n in F ig u r e 7 .8 c . E a c h s la v e h a s a p red efin ed d ev ice ad d ress; th e slav es are th erefo re resp o n sib le fo r mo n ito rin g th e b u s an d S t a r t in g w it h S e r ia l C o m m u n ic a t io n (a ) (b ) start an d stop con d ition s S D A S D A S C L S C L clock an d d ata timin g D a ta V a lid S ta rt S to p (c ) 1 3 1 D a ta m a y c h a n g e a comp lete tran sfer of on e b yte S C L S D A 1 -7 S ta rt 8 A d d re ss R /W 1 -7 A c k 8 D a ta A c k S to p F ig u r e 7 .8 : I2 C d a ta tra n s fe r resp o n d in g o n ly to co mman d s asso ciated with th eir o wn ad d ress. A slav e d ev ice th at re c o g n iz e s its a d d re s s w ill th e n b e re a d ie d e ith e r to re c e iv e d a ta o r to tra n s m it it o n to th e b u s . A 1 0 -b it ad d ressin g mo d e is also av ailab le. All d ata tran sferred o n e messag e. Each d u rin g wh ich time wh ile SCL is h ig h a sin g le b y te. 7 .5 .2 is in b y te th e tr d efin u n its o f o mu st b e an smitter es a sto p n e b y te, with n o limit o n th e n u mb er o f b y tes tran sferred in fo llo w e d b y a 1 -b it a c k n o w le d g m e n t fro m th e re c e iv e r, relin q u ish es SDA co n tro l. A lo w to h ig h tran sitio n o f SDA c o n d itio n . F ig u r e 7 .8 c illu s tr a te s th e c o m p le te tr a n s f e r o f I2 C o n th e m b e d F ig u r e 2 .1 s h o w s u s th a t th e m b e d o ff e r s tw o I 2 C p o r ts , o n p in s 9 a n d 1 0 , o r 2 7 a n d 2 8 . T h e ir u se fo llo ws th e p attern o f o th er mb ed p erip h erals, with av ailab le fu n ctio n s sh o wn in Tab les 7 .6 a n d 7 .7 . 7 .5 .3 S e t t in g u p a n I2 C D a t a L in k We w ill n o w r e p lic a te th e a c tio n o f S e c tio n 7 .2 .4 , b u t u s in g I 2 C a s th e c o m m u n ic a tio n lin k , r a th e r th a n S P I . We w ill u s e th e I 2 C p o r t o n p in s 9 a n d 1 0 . P r o g r a m E x a m p le 7 .5 , th e m a s te r, 1 3 2 Chapter 7 T a b le 7 .6 : m b e d I2 C m a s t e r A P I s u m m a r y F u n c t io n U s a g e 2 I 2 C C r e a t e a n I C m a s t e r in t e r fa c e , c o n n e c t e d t o t h e s p e c ifi e d p in s f r e q u e n c y S e t t h e fr e q u e n c y o f t h e I2 C in t e r fa c e r e a d R e a d fr o m a n I2 C s la v e w r i t e W r it e t o a n I2 C s la v e s t a r t C r e a t e s a s t a r t c o n d it io n o n t h e I2 C b u s s t o p C r e a t e s a s t o p c o n d it io n o n t h e I2 C b u s T a b le 7 .7 : m b e d I2 C s la v e A P I s u m m a r y F u n c t io n U s a g e I 2 C S l a v e C r e a t e a n I2 C s la v e in t e r fa c e , c o n n e c t e d t o t h e s p e c ifi e d p in s f r e q u e n c y S e t t h e fr e q u e n c y o f t h e I2 C in t e r fa c e r e c e i v e C h e c k s t o s e e if t h is I2 C s la v e h a s b e e n a d d r e s s e d r e a d R e a d fro m a n I2 C m a s te r w r i t e W r it e t o a n I2 C m a s t e r a d d r e s s S e t s t h e I2 C s la v e a d d r e s s s t o p R e s e t t h e I2 C s la v e b a c k in t o t h e k n o w n r e a d y r e c e iv in g s t a t e f o llo w s e x a c tly th e p a tte r n o f P r o g r a m E x a m p le 7 .2 , e x c e p t th a t S P I - r e la te d s e c tio n s a r e rep laced b y th o se th at relate to I2 C. Early in th e p ro g ram an I2 C serial p o rt is co n fig u red u sin g th e mb ed u tility I 2 C . Th e n ame i2 c _ p o r t is ch o sen fo r th e p o rt n ame, an d lin k ed to th e p o rt o n p in s 9 an d 1 0 . An arb itrary slav e ad d ress is ch o sen , 0 x 5 2 . Fo llo win g d etermin atio n o f th e v ariab le s w itc h _ w o r d , th e I2 C tran smissio n can b e seen . Th is is created fro m th e sep arate c o m p o n e n ts o f a s in g le - b y te I 2 C tr a n s m is s io n , i.e . s ta r t es e n d a d d r e s s es e n d d a ta es to p , a s allo wed b y th e mb ed fu n ctio n s. A way o f g ro u p in g th ese to g eth er is p resen ted later in th e ch ap ter. Fu rth er d o wn th e p ro g ram we see a req u est fo r a b y te o f d ata fro m th e slav e, with s i m i l a r m e s s a g e s t r u c t u r e . N o w t h e s l a v e a d d r e s s i s O R e d w i t h 0 x 0 1 , w h i c h s e t s t h e R =W b i t in th e a d d re s s w o rd to in d ic a te R e a d . T h e re c e iv e d w o rd is th e n in te rp re te d in o rd e r to s e t th e LEDs, ju st as we d id in th e SPI p ro g ram earlier. / * s l * / # i I 2 D i P r o g r a m E x a m p l e 7 . 5 : I 2 C M a s t e r , t r a n s f e r s s w i t c h s t a t e t o a v e , a n d d i s p l a y s s t a t e o f s l a v e ’ s s w i t c h e s o n i t s l e d s . n c l u d e " m b e d . h " C i 2 c _ p o r t ( p 9 , p 1 0 ) ; g i t a l O u t r e d _ l e d ( p 2 5 ) ; / / C o n f i g u r e / / r e d l e d a s e r i a l p o r t , p i n s 9 s e c o n d m b e d a n d a r e 1 0 a c t i n g s d a , s c l a s S t a r t in g w it h S e r ia l C o m m u n ic a t io n D i g i t a l O u t g r e e n _ l e d ( p 2 6 ) ; D i g i t a l I n s w i t c h _ i p 1 ( p 5 ) ; D i g i t a l I n s w i t c h _ i p 2 ( p 6 ) ; c h a r s w i t c h _ w o r d c h a r r e c d _ v a l ; c o n s t i n t a d d r = i n t m w h i s i i / i i i i w / i i r i / r a i l e w i f s f s / s 2 c 2 c 2 c 2 c a i / r 2 c 2 c e c 2 c / s e d n ( ( 1 t c ( s w i ( s w i e n _ p _ p _ p _ p t ( e c _ p _ p d _ _ p e t _ l ) ) ; / / g r e e n / / i n p u t l e d s w i t c h / / w o r d w e w i l l s e n d / / v a l u e r e c e i v e d f r o m s l a v e / / t h e I 2 C s l a v e a d d r e s s , a n 0 x 5 2 ; 1 3 3 a r b i t r a r y e v e n n u m b e r { { h _ w i t c w i t c d o r o r o r o r 0 . e i o r o r v a o r l e d w o t c h _ t c h _ a t . t . t . t . 0 0 v e t . t . l = t . e d = 0 r d h _ w o h _ w o s i s t w r w r s t 2 ) a s t w r i 2 s t s ; = 0 i p r d i p r d n g a r i t i t o p ; s a r i t c _ o p a c x a 1 = = s 2 = = s l e t ( e ( e ( ( ) 0 ; = 1 w i = 1 w i b ) ; a d s w ; / / s e t i n t ( e ( p o ( ) c o g l e b y t e o f d a t a , ) ; a d d r j0 x 0 1 ) ; r t . r e a d ( a d d r ) ; u p a r e c o g n i z a b l e o u t p u t p a t t e r n ) t c h _ w o r d j0 x 0 1 ; / / O R i n l s b ) t c h _ w o r d j0 x 0 2 ; y t e o f d a t a , i n d r ) ; i t c h _ w o r d ) ; ; r d i n g t o w o r d c o / / / / / / / / / / r f s s f i n / / / / / / r e c e i v / / O R r e o r e n e n o r i n c t c e d t d o c e n e I 2 C a s h e n e a s c o r r e c t s e R e f o e d p r n d a a d a r c e f r o e s e t x t p t a a d b y t o l s b a c k a g e r t c o n d i t i o n d r e s s t e o f d a t a , i e p c o n d i t i o n I 2 C d d r e n d s a s t m s l b o t s s a v o p a v h s w i t c h _ w o r d p a c k a g e , e w i t h R / W b i t t h e r e c e i v e d c o n d i t i o n s e t t o b y t e R e a d e t o 0 . ( c o n t i n u e s a s i n P r o g r a m E x a m p l e 7 . 2 ) . } } P r o g r a m E x a m p le 7 .5 I 2 C d a ta lin k m a s te r T h e s la v e p r o g r a m is s h o w n in P r o g r a m E x a m p le 7 .6 , a n d is s im ila r to P r o g r a m E x a m p le 7 .3 , w ith S PI fe atu res rep la ce d b y I2 C . A s in S PI, th e I2 C s la v e ju st res p o n d s to c alls fro m th e m a s te r. T h e s la v e p o rt is d efi n e d w ith th e m b ed u tility I 2 C s la v e , w ith s la v e c h o s en a s th e p o rt n am e . J u s t w ith in th e m a in fu n c tio n th e s lav e a d d res s is d efi n e d , imp o rtan tly th e s a me 0 x 5 2 a s w e s a w in th e m a ster p ro g ra m. A s b efo re, th e s w itc h _ w o r d v a lu e is s e t u p fro m th e s ta te o f th e s witc h e s; th is is th e n s av e d u s in g th e w r ite fu n c tio n , in re a d in es s fo r a re q u e st fro m th e m a ster. T h e r e c e iv e ( ) f u n c tio n is u s e d to te s t w h e th e r a n I2 C tra n s m is s io n h a s b e e n re c e iv e d . T h is re tu rn s a 0 if th e s la v e h as n o t b e en ad d res se d , a 1 if it h a s b ee n a d d re ss ed to rea d , a n d a 3 if ad d res se d to w rite. If a re ad h as b ee n in itiated , th en th e v a lu e a lre ad y s to re d is a u to m a tic ally s en t. If th e v a lu e is 3 , th e n th e p ro g r a m s to re s th e r e c e iv e d v a lu e a n d s e ts u p th e L E D s o n th e m a s te r a c c o rd in g ly . / * P M a s * / # i n I 2 C D i g r o g r a m E x a m p l e 7 . 6 : I 2 C t e r , a n d d i s p l a y s s t a t e c l u d e < m b e d . h > S l a v e s l a v e ( p 9 , p 1 0 ) ; i t a l O u t r e d _ l e d ( p 2 5 ) ; S l a v e , w h e n o f M a s t e r ’ s c a l l e d t r a n s f e r s s w i t c h s w i t c h e s o n i t s l e d s . / / C o n f i g u r e / / r e d l e d I 2 C s l a v e s t a t e t o m b e d a c t i n g a s 1 3 4 D i g D i g D i g c h a c h a i n t Chapter 7 i t a l i t a l i t a l r s w r r e m s l a w h i / s i i s / i i a i v e l e / s w i f s f s l a / t n t f r O u t I n I n i t c c d _ g r s w i s w i h _ w v a l n ( . a ( e t t c ( s w i ( s w i v e e s i ( i e c { r e { p w o t c h _ t c h _ r i f o s = v a / n ) d d 1 ) u h _ w i t c w i t c . w t = = d _ / e e t c t c o r n _ l e d ( p 2 6 ) ; h _ i p 1 ( p 5 ) ; h _ i p 2 ( p 6 ) ; d ; / / g r e e n l e d / / w o r d w e w i l l s e n d / / v a l u e r e c e i v e d f r o m ; m a s t e r s s ( 0 x 5 2 ) ; s w r d h _ w o h _ w o t e r l a 3 ) l = o w i t = 0 i p r d i p r d ( s I 2 v e { s s c h x a 1 = = s 2 = = s w i C , . r _ w 0 ; = 1 w i = 1 w i t c a e c o r d / / ) t c h ) t c h h _ w n d e i v / / l a v e . r e e t l e d s f r o m s w i t c h e s t h a t a r e p r e s s e d s e t u p a r e c o g n i z a b l e o u t p u t p a t t e r n _ w o r d j0 x 0 1 ; _ w o r a c e ( s l a d a o r d ) t ) ; a v ( ) c c d j0 x 0 2 ; ; / / l o a d u p a c c o r d i n g l y e i s w o r d a d d r e s s e d , t o s e n d M a s t e r w i l l w r i t e ; o r d i n g t o r e c e i v e d w o r d . ( c o n t i n u e s . a s i n P r o g r a m E x a m p l e 7 . 2 ) } } P r o g r a m E x a m p le 7 .6 I 2 C d a ta lin k s la v e C o n n e c t tw o m b e d s to g e th e r w ith a n I 2 C lin k , a p p ly in g th e c ir c u it d ia g r a m o f F ig u r e 7 .9 . T h is is v e r y s im ila r to F ig u r e 7 .5 , e x c e p t th a t th e S P I c o n n e c tio n is r e m o v e d , a n d r e p la c e d b y th e I 2 C c o n n e c tio n . I t is e s s e n tia l to in c lu d e th e p u ll- u p r e s is to r s ; v a lu e s o f 4 .7 k U a r e s h o w n , b u t th e y c a n b e a n y w h e r e i n t h e r a n g e 2 . 2 e4 . 7 k U . N o t e t h a t e a c h m b e d s h o u l d h a v e t w o s w i t c h e s a n d two LEDs co n n ected , b u t th ere sh o u ld ju st b e o n e p air o f p u ll-u p resisto rs b etween th em. C o m p ile a n d d o w n lo a d P r o g r a m E x a m p le 7 .5 in to e ith e r m b e d , a n d E x a m p le 7 .6 in to th e o th e r. Yo u s h o u ld fi n d th a t th e s w itc h e s o f o n e m b e d c o n tr o l th e L E D s o f th e o th e r, a n d v ic e v e r s a . Mo n ito r SCL an d SDA lin e trig g erin g . With ap p ro p riate two messag es b ein g sen t b e in clu d in g th e id le h ig h co n d R / W b i t e m b e d d e d . n s o n an o scillo sco p e. Th is settin g o f th e o scillo sco p e tween th e mb ed s. Id en tify itio n , th e start an d sto p co may req u ire carefu l time b ase y o u sh o u ld as man y featu res o f n d itio n s, an d th e ad d o scillo sco p e b e ab le to see th e I2C as y o u can , ress b y te with th e E x e r c is e 7 .4 In P r o g r a m E x a m p le 7 .6 , r e p la c e t h e lin e i f ( i = = 3 ) w it h i f ( i = = 4 ) ; in o t h e r w o r d s , t h e c o n d it io n c a n n o t b e s a t is fi e d . C o m p ile , d o w n lo a d a n d r u n . N o t ic e t h a t t h e s la v e s t ill S 1 c o n n e c t to s e c o n d m b e d S 2 4 k 7 s d a , to p in 9 s c l, to p in 1 0 4 k 7 G n d V in V b n R 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 m b e d M ic r o c o n tr o lle r S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 3 5 V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 7 .9 : L in k in g t w o m b e d s w it h I2 C c o n t in u e s t o w r it e t o t h e m a s t e r , b u t is n o w u n a b le t o r e s p o n d t o t h e m a s t e r ’s m e s s a g e . W h y is t h is ? n 7 .6 C o m m u n ic a t in g w it h a n I2 C T e m p e r a t u r e S e n s o r Ju st as we d id with th e SPI p o rt an d th e accelero meter, we can u se th e mb ed I2 C p o rt to co mmu n icate with a v ery wid e ran g e o f p erip h eral d ev ices, in clu d in g man y in tellig en t s e n s o r s . T h e Te x a s I n s tr u m e n ts T M P 1 0 2 te m p e r a tu r e s e n s o r ( R e f e r e n c e 7 .4 ) h a s a n I 2 C d a ta lin k . T h is is s im ila r to th e a c c e le r o m e te r in tr o d u c e d in S e c tio n 7 .3 , in th a t a n a n a lo g s e n s in g d ev ice is in teg rated with an ADC an d a serial p o rt, p ro d u cin g an id eal an d easy -to -u se sy stem elemen t. No te fro m th e d atash eet th at th e TMP1 0 2 actu ally mak es u se o f th e sy stem man ag emen t b u s (SMb u s). Th is was d efin ed b y In tel in 1 9 9 5 , an d is b ased o n I2 C. In simp le ap p licatio n s th e two stan d ard s can b e mix ed ; fo r mo re ad v an ced ap p licatio n s it is wo rth ch eck in g th e small d ifferen ces b etween th em. Th e TMP u sed mo u sh o wn in I2C. On c 1 0 2 is n ted o Tab le o n n ec a tin y d n a sma 7 .8 . C o to r JP2 ev ice, as req u ired o f a ll b reak o u t b o ard , seen n n ectio n s o n co n n ecto th e sen so r h as an ad d r temp eratu re sen in F ig u r e 7 .1 0 a r JP1 are th e ess ess p in , ADD0 ; so r. Lik e th . It h as six p en tial o n es th is is u sed e accelero meter, it is o ssib le co n n ectio n s, o f p o wer su p p ly an d to select th e ad d ress 1 3 6 Chapter 7 (a ) (b ) c o n n e c te d to th e m b e d 4 3 2 1 J P 1 2 1 J P 2 s e n s o r o n b re a k o u t b o a rd F ig u r e 7 .1 0 : T h e T M P 1 0 2 t e m p e r a t u r e s e n s o r ( Im a g e r e p r o d u c e d w it h p e r m is s io n o f S p a r k F u n E le c t r o n ic s ) o f th e d ev ice, as seen in th e tab le. Th is allo ws fo u r d ifferen t ad d ress o p tio n s, h en ce fo u r o f th e same sen so r can b e u sed o n th e same I2 C b u s. P r o g r a m E x a m p le 7 .7 c a n b e a p p lie d to lin k th e m b e d to th e s e n s o r. I t d e fi n e s a n I 2 C p o r p in s 9 a n d 1 0 , a n d n a m e s th is te m p s e n s o r . T h e s e ria l lin k to b e u s e d to c o m m u n ic a te w ith P C is s e t u p . A s s e n s o r p in A D D 0 is tie d to g r o u n d , Ta b le 7 .8 s h o w s th a t th e s e n s o r a d d r e s s b e 0 x 9 0 ; th is is d efi n e d in th e p ro g ram , w ith n a m e a d d r . Tw o s ma ll a rra y s a re a ls o d efi n e d , to h o ld th e s e n s o r c o n fi g u ra tio n d a ta, a n d th e o th e r to h o ld th e raw d ata rea d fro m th e s e n so f u r th e r v a r ia b le t e m p w ill h o ld th e s c a le d d e c im a l e q u iv a le n t o f th e r e a d in g . t o n th e w ill o n e r. A T a b le 7 .8 : C o n n e c t in g t h e T M P 1 0 2 s e n s o r t o t h e m b e d S ig n a l T M P 1 0 2 p in V c c ( 3 .3 V ) JP 1 : 1 S D A JP 1 : 2 S C L JP 1 : 3 G n d (0 V ) JP 1 : 4 A le r t JP 2 : 1 A D D 0 JP 2 : 2 m b e d p in N o te s 4 0 9 2 .2 k U p u ll- u p t o 3 .3 V 1 0 2 .2 k U p u ll- u p t o 3 .3 V 1 1 1 C o n n e c t to S la v e a d d r e s s 0 V 0 x9 0 V c c 0 x9 1 S D A 0 x9 2 S C L 0 x9 3 S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 3 7 Th e co n fig u ratio n o p tio n s can b e fo u n d fro m th e TMP1 0 2 d atash eet. To set th e co n fig u ratio n reg ister we first n eed to sen d a d ata b y te o f 0 x 0 1 to sp ecify th at th e p o in ter reg ister is set to ‘Co n fig u ratio n Reg ister’. Th is is fo llo wed b y two co n fig u ratio n b y tes, 0 x 6 0 an d 0 x A0 . Th ese select a simp le co n fig u ratio n settin g , in itializin g th e sen so r to n o rmal mo d e o p eratio n . Th ese v alu es are sen t at th e start o f th e m a in fu n ctio n . No te th e fo rmat o f th e write co mman d u sed h ere, wh ich is ab le to sen d mu lti-b y te messag es. Th is is d ifferen t fro m th e ap p ro ach u sed in P r o g r a m E x a m p le 7 .5 , w h e r e o n ly a s in g le b y te w a s s e n t in a n y o n e m e s s a g e . U s in g th e I 2 C w r ite ( ) fu n ctio n , we n eed to sp ecify th e d ev ice ad d ress an d th e array o f d ata, fo llo wed b y th e n u mb er o f b y tes to sen d . Th e s e n s o r will n o w o p e ra te a n d a c q u ire temp e ra tu re d ata , s o we s imp ly n e e d to re a d th e d ata reg ister. To d o th is we n eed first to set th e p o in ter reg ister v alu e to 0 x 0 0 . In th is co mman d we h av e o n ly sen t o n e d ata b y te to set th e p o in ter reg ister. Th e p ro g ram n o w s ta rts a n in fin ite lo o p to re ad c o n tin u o u s ly th e 2 -b y te temp e ra tu re d a ta. Th is d ata is th en co n v erted fro m a 1 6 -b it read in g to an actu al temp eratu re v alu e. Th e co n v ersio n req u ired (as sp ecified b y th e d atash eet) is to sh ift th e d ata rig h t b y 4 b its (it is actu ally o n ly 1 2 -b it d ata h eld in two 8 -b it reg is ters) an d to mu ltip ly b y th e sp ecifie d c o n v e r s io n f a c to r, 0 .0 6 2 5 d e g r e e s C p e r L S B . T h e v a lu e is th e n d is p la y e d o n th e P C screen . / * d i * / # i I 2 S e c o c h c h f l P r o g r a m E x a m p l e s p l a y s r e a d i n g s n c l C t r i a n s t a r a r o a t i n t c o c o c o t e c o t e w h u d e m l i c o t e t m a n f n f n f m p n f m p i l w a t e t e p c e p s p c n t n f m p e m i n i g i g i g s e i g s e e ( i t m p m p . p " m e n ( U a i g _ r p ; ( ) _ t _ t _ t n s _ t n s 1 ) ( 1 s e = r i b e s o S B d d _ t e a { [ 0 [ 1 [ 2 o r [ 0 o r { ) ; n s 0 n t ] ] ] . . ] d . r ( T X r [ 3 d [ h “ p 9 , p 1 0 ) ; , U S B R X ) ; = 0 x 9 0 ; ] ; 2 ] ; = 0 x 0 x = 0 x w r i t e = 0 x w r i t e = 7 . 7 : M b e d c o m m u n i c a t e s t o s c r e e n . 0 1 6 0 A 0 ( a 0 0 ( a T M P 1 0 2 t e m p e r a t u r e s e n s o r , a n d s c a l e s a n d / / s d a , s c 1 / / t x , r x ; / / s e t p o i n t e r r e g t o / / c o n f i g d a t a b y t e 1 / / c o n f i g d a t a b y t e 2 ; ; d d r , ; d d r , w i t h c o n f i g _ t , 3 ) ; c o n f i g _ t , 1 ) ; / / s e t p o i n t e r r e g / / s e n d t o p o i n t e r ’ c o n fig r e g i s t e r ’ t o ’ d a t a r e g i s t e r ’ ’ r e a d t e m p ’ o r . r e a d ( a d d r , t e m p _ r e a d , 2 ) ; / / r e a d t h e t w o - b y t e t e m p d a t a . 0 6 2 5 * ( ( ( t e m p _ r e a d [ 0 ] < < 8 ) + t e m p _ r e a d [ 1 ] ) > > 4 ) ; / / c o n v e r t f ( " T e m p = % . 2 f d e g C \ n \ r " , t e m p ) ; d a t a } } P r o g r a m E x a m p le 7 .7 C o m m u n ic a tin g b y I 2 C w ith th e T M P 1 0 2 te m p e r a tu r e s e n s o r 1 3 8 Chapter 7 C o n n e c t th e s e n s o r a c c o r d in g to th e in f o r m a tio n in Ta b le 7 .8 , le a d in g to a c ir c u it th a t lo o k s s o m e th in g lik e F ig u r e 7 .1 0 b . O n c e a g a in , th e S DA a n d S C L lin e s e a c h n e e d to b e p u lle d u p to 3 .3 V th r o u g h a r e s is to r, o f v a lu e b e tw e e n 2 .2 a n d 4 .7 k U . C o m p ile , d o w n lo a d a n d r u n th e c o d e o f P r o g r a m E x a m p le 7 .7 . Te s t th a t th e d is p la y e d te m p e r a tu r e in c r e a s e s w h e n y o u p r e s s y o u r fi n g e r a g a in s t th e s e n s o r. Yo u c a n tr y p la c in g th e s e n s o r o n so meth in g warm, fo r ex amp le a rad iato r, in o rd er to ch eck th at it resp o n d s to temp eratu re ch an g es. If y o u h av e a calib rated temp eratu re sen so r, try to co mp are read in g s fro m b o th so u rces. n E x e r c is e 7 .5 R e w r it e P r o g r a m E x a m p le 7 .5 u s in g t h e I2 C m a s t e r r e a d ( ) a n d w r it e ( ) fu n c t io n s , a s s e e n in P r o g r a m E x a m p le 7 .7 . C o m p ile , d o w n lo a d a n d t e s t t h a t it w o r k s a s e x p e c t e d . n U s in g t h e S R F 0 8 U lt r a s o n ic R a n g e F in d e r T h e S R F 0 8 u ltr a s o n ic r a n g e fi n d e r, a s s h o w n in F ig u r e 7 .1 1 , c a n b e u s e d to m e a s u r e th e d is ta n c e b e tw e e n th e s e n s o r a n d a n a c o u s tic a lly re fl e c tiv e s u rfa c e o r o b je c t in fro n t o f it. mak es th e measu remen t b y tran smittin g a p u lse o f u ltraso u n d fro m o n e o f its tran sd u cers, a th en measu rin g th e time fo r an ech o to retu rn to th e o th er. If th ere is n o ech o it times o u t. T d is ta n c e to th e re fl e c tin g o b je c t is p ro p o rtio n a l to th e tim e ta k e n fo r th e e c h o to re tu rn . G iv k n o wled g e o f th e sp eed o f so u n d in air, th e actu al d istan ce can b e calcu lated . Th e SRF0 8 h (b ) + 3 ,3 V c o n n e c tio n s to th e m b e d + 5 V IC 7 + 5 V G n d V in V b n R 5 1 k 8 R 1 + 5 V 6 7 V C S D S C N G N C A L C D V C S D S C N C G N C A L 8 9 1 0 1 1 D 1 2 1 3 1 4 1 5 1 6 1 7 U S R F 1 1 8 1 9 2 0 m b e d M ic r o c o n tr o lle r th e s e n s o r 1 k 8 R 2 (a ) It n d h e en as V o u t V u IF IF + R D R D + T D T D + D D + 3 0 2 9 2 8 2 7 2 6 2 5 2 4 2 3 2 2 2 1 F ig u r e 7 .1 1 : T h e S R F 0 8 u lt r a s o n ic r a n g e fi n d e r . ( Im a g e r e p r o d u c e d w it h p e r m is s io n o f S p a r k F u n E le c t r o n ic s ) + 5 V 7 .7 S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 3 9 a n I 2 C in te r f a c e . D a ta is r e a d ily a v a ila b le f o r it, f o r e x a m p le R e f e r e n c e 7 .5 , a lth o u g h a t th e time o f writin g n o t as a fo rmalized d o cu men t. T h e S R F 0 8 c a n b e c o n n e c te d to th e m b e d a s s h o w n in F ig u r e 7 .1 1 b . I t m u s t b e p o w e r e d f r o m 5 V, w ith I 2 C p u ll- u p r e s is to r s c o n n e c te d to th a t v o lta g e . T h e m b e d r e m a in s p o w e r e d f r o m 3 .3 V, a n d is a b le to to le r a te th e h ig h e r v o lta g e b e in g p r e s e n te d a t its I 2 C p in s . Hav in g wo rk ed th ro u g h th e p reced in g p ro g rams, it sh o u ld b e easy to g rasp h o w Pro g ram E x a m p le 7 .8 w o r k s . N o te th e f o llo w in g in f o r m a tio n , ta k e n f r o m th e d e v ic e d a ta : • SRF0 8 I2C ad d ress p o in ter v alu e fo r th ata v alu e o f 0 x 5 1 to rn d ata in cm. o in ter v alu e o f 0 x 0 2 Th e Th e A d retu A p • • • / * f i * / # i I 2 S e c o c h c h f l is 0 x E0 . e co mman d reg ister is 0 x 0 0 . th e co mman d reg ister in itializes th e ran g e fin d er to o p erate an d p r e p a r e s f o r 1 6 - b it d a ta ( i.e . tw o b y te s ) to b e r e a d . P r o g r a m E x a m p l e 7 . 8 : C o n f i g u r e s a n d n d e r , a n d d i s p l a y s t h e m o n s c r e e n . n c l C r r i a n s t a r a r o a t i n t m w h i c c r w c r r r p w u d a n l i c o r a r e " m f i ( U a i g e _ g e g e p c n t n f n g a n a i l e o n o n a n a i o n a n a n a n c . a i n ( ) ( 1 ) f i g _ f i g _ g e f i t ( 0 . f i g _ g e f i g e f i g e = p r i n t ( 0 . b e n d S B d d _ r r e ; d . e r T X r [ 2 a d h " ( p 9 , U = 0 ] ; [ 2 ] t a k e s r e a d i n g s f r o m t h e S R F 0 8 u l t r a s o n i c r a n g e , p 1 0 ) ; / / s d a , s c 1 S B R X ) ; / / t x , r x x E 0 ; ; { { r [ 0 r [ 1 n d e 0 7 ) r [ 0 n d e n d e ( ( t f ( 0 5 ) ] = 0 x 0 0 ; 0 x 5 1 ; r . w r i t e ( a d d r , ] = c o n f i g _ r , / / s e t p o i n t e r / / i n i t i a l i z e , r e g t o r e s u l t / / / / [ / o n ‘ c m d r e g i s t e r ’ i n c m 2 ) ; ; ] r . r . r a " R = w r r e n g a n 0 x i t a d e _ g e 0 2 e ( ( a r e = ; a d d r , c d d r , r a a d [ 0 ] < % . 2 f c o n n g < m \ f i g _ r , 1 ) ; / e _ r e a d , 2 ) ; / 8 ) + r a n g e _ r e a d n \ r " , r a n g e ) ; / s e s e r e 1 ] p r t p o i n t e n d t o p o a d t h e t ) ; i n t r a n g r r e g t o ’ d a t a r e g i s t e r ’ i n t e r ’ r e a d r a n g e ’ w o - b y t e r a n g e d a t a e s c r e e n ; } } P r o g r a m E x a m p le 7 .8 Co n n ect th e circu it m b e d . Ve r if y c o r r e c su rface. Th en ex p lo h an d le) an d d istan t o f t o re o b C o m m u n ic a tin g b y I 2 C w ith th e S R F 0 8 r a n g e fi n d e r F ig u r e 7 .1 1 b . C o m p ile P r o g r a m E x a m p le 7 .8 a n d d o w n lo a d to th e p eratio n b y p lacin g th e ran g e fin d er a k n o wn d istan ce fro m a h ard , flat its a b ility to d e te c t ir r e g u la r s u r f a c e s , n a r r o w o b je c ts ( e .g . a b r o o m jects. 1 4 0 Chapter 7 E v a lu a t in g I2 C 7 .8 As we h av e seen , th e I2 C p ro to co l is well estab lish ed an d v ersatile. Lik e SPI, it is wid ely ap p lied to sh o rt d istan ce d ata co mmu n icatio n . Ho wev er, it g o es well b ey o n d SPI in its ab ility to s e t u p m o re c o m p le x n e tw o rk s , a n d to a d d a n d s u b tra c t n o d e s w ith c o m p a ra tiv e e a s e . Alth o u g h we h av e n o t really ex p lo red it h ere, it p ro v id es fo r a mu ch mo re reliab le sy stem. If an ad d ressed d ev ice d o es n o t sen d an ack n o wled g men t, th e master can act u p o n th at fau lt. Do es th is mean th at I2 C is g o in g to meet all o u r n eed s fo r serial co mmu n icatio n , in an y ap p licatio n ? Th e an swer is a clear No , fo r at least two reaso n s. On e is th at th e b an d wid th is c o m p a ra tiv e ly lim ite d , ev e n in th e fa s te r v e rs io n s o f I2 C . T h e s e c o n d is th e s e c u rity o f th e d ata. Wh ile fin e in , say , a d o mestic ap p lian ce, I2 C is still su scep tib le to in terferen ce an d d o es n o t ch eck fo r erro rs. Th erefo re, o n e wo u ld b e u n lik ely to co n sid er u sin g it in a med ical, mo to r v eh icle o r o th er h ig h -reliab ility ap p licatio n . 7 .9 A s y n c h r o n o u s S e r ia l D a t a C o m m u n ic a t io n Th e sy SPI an h o wev allo ws n ch ro n o u s serial co mmu n icatio n p ro to co ls d escrib ed so far th is ch d I2 C, are ex tremely u sefu l way s o f mo v in g d ata aro u n d . Th e q u er: d o we really n eed to sen d th at clo ck sig n al wh erev er th e d ata an easy way o f sy n ch ro n izin g th e d ata, it d o es h av e th ese d isad v • • • An ex tra (clo ck ) Th e b an d wid th n th erefo re, it is th Ov er lo n g d istan 7 .9 .1 lin e n eed s eed ed fo r e d eman d s ces, clo ck to th e o f an d g o clo th e d a ap ter, in th e fo rm o f estio n remain s, g o es? Alth o u g h it an tag es: to ev ery d ata n o d e. ck is alway s twice th e b an d wid th n eed ed fo r th e d ata; clo ck th at limit th e o v erall d ata rate. ta th emselv es co u ld lo se sy n ch ro n izatio n . In t r o d u c in g A s y n c h r o n o u s S e r ia l D a t a Fo r th e reaso n s ju st stated , sev eral serial stan d ard s h av e b een d ev elo p ed th a clo ck sig n al to b e sen t with th e d ata. Th is is g en erally called a syn ch ro n o c o m m u n ic a tio n . It is n o w u p to th e re c e iv e r to e x tra c t a ll tim in g in fo rm a tio sig n al itself. Th is h as th e effect o f lay in g n ew an d d ifferen t d eman d s o n th e tra n s m itte r a n d re c e iv e r n o d e s s o m ew h a t m o re c o m p le x th a n c o m p a ra b le s at d o n o t u s serial n d irectly sig n al, an y n ch ro n o req u ire fro m th e d mak in g u s n o d es. A co mmo n ap p ro ach to ach iev in g asy n ch ro n o u s co mmu n icatio n is b ased o n th is: • Data rate d ata rate. rate can b acco mmo i s p r e d e t e r m i n e d eb o t h t r a n s m i t t e r a n d r e c e iv e r a r e p r e s e t t o r e c o g n i z e t h e s a m e Hen ce, each n o d e n eed s an accu rate an d stab le clo ck so u rce, fro m wh ich th e d ata e g en erated . Small v ariatio n s fro m th e th eo retical v alu e can , h o wev er, b e d ated . S t a r t in g w it h S e r ia l C o m m u n ic a t io n Idle State Start bit First Data bit Start synchronization Last Data bit Stop bit Extra “parity” bit could be inserted here 1 4 1 Idle State Earliest possible new Start Bit F ig u r e 7 .1 2 : A c o m m o n a s y n c h r o n o u s s e r ia l d a t a fo r m a t • Each b y te o r wo rd is fra med with a Start an d Sto p b it. Th ese allo w sy n ch ro n izatio n to b e in itiated b efo re th e d ata starts to flo w. An asy n ch ro n o u s d ata fo rmat, o f th e so rt u sed b y su ch stan d ard s as RS-2 3 2 , is sh o wn in F ig u r e 7 .1 2 . T h e r e is n o w o n ly o n e d a ta lin e . T h is id le s in a p r e d e te r m in e d s ta te , in th is ex amp le at Lo g ic 1 . Th e start o f a d ata wo rd is in itiated b y a S ta rt b it, wh ich h as p o larity o p p o site to th at o f th e id le state. Th e lead in g ed g e o f th e Start b it is u sed fo r sy n ch ro n izatio Eig h t d ata b its are th en clo ck ed in . A n in th b it, fo r p arity ch eck in g , is also so metimes u se Th e lin e th en retu rn s to th e id le state, wh ich fo rms a Sto p b it. A n ew wo rd o f d ata can b e se immed iately , fo llo win g th e co mp letio n o f a sin g le Sto p b it, o r th e lin e may remain in th e id state u n til it is n eed ed ag ain . n . d . n t le An a s y n ch ro n o u s s erial p o rt in teg rate d in to a mic ro c o n tro ller o r p e rip h e ra l d ev ice is g e n erally c a lle d a UA RT, s ta n d in g f o r u n iv e r s a l a s y n c h ro n o u s re c e iv e r /tr a n s m itte r. I n its s im p le s t f o r m , a UA RT h a s o n e c o n n e c tio n fo r tra n s m itte d d a ta , u s u a lly c a lle d T X , a n d a n o th e r fo r re c e iv e d d ata, called RX. Th e p o rt sh o u ld sen se wh en a start b it h as b een in itiated , an d au to matically clo ck in an d sto re th e n ew wo rd . It can in itiate a tran smissio n at an y time. Th e d ata rate th at re c e iv e r a n d tra n s m itte r w ill o p e ra te a t m u s t b e p re d e te rm in e d ; th is is s p e c ifi e d b y its b a u d r a te . F o r th e p r e s e n t p u r p o s e s b a u d r a te c a n b e v ie w e d a s b e in g e q u iv a le n t to b it r a te ; f o r m o r e ad v an ced ap p licatio n s o n e sh o u ld ch eck th e d istin ctio n s b etween th ese two terms. 7 .9 .2 A p p ly in g A s y n c h r o n o u s C o m m u n ic a t io n o n t h e m b e d I f w e lo o k b a c k a t F ig u r e 2 .3 . w e s e e th a t th e L P C 1 7 6 8 h a s f o u r UA RT s . T h r e e o f th e s e ap p ear o n th e p in o u t o f th e mb ed , simp ly lab eled ‘Serial’, o n p in s 9 an d 1 0 , 1 3 an d 1 4 , an d 2 7 a n d 2 8 . T h e ir n o t in s ig n ifi c a n t A P I s u m m a r y is g iv e n in Ta b le 7 .9 . We mb Fig slig will n o w rep eat w ed s to d emo n strate u r e 7 .1 3 , th e b u ild h tly simp ler th an e h at we h av e alrea a serial lin k , b u t we will u se, as a ith er o f th ese. We d y d o n e with SPI an d I2 C, th is time an asy n ch ro n o u s v a r ia tio n o n F ig u r e s 7 .5 a n will ap p ly Pro g ram Ex amp wh ich is o n e . Yo u d 7 .9 ; n o le 7 .9 . I t to c can tice will o n n ect two v iew th at it is b e th e same 1 4 2 Chapter 7 T a b le 7 .9 : S e r ia l ( a s y n c h r o n o u s ) A P I s u m m a r y F u n c t io n U s a g e S e r i a l C r e a t e a s e r ia l p o r t , c o n n e c t e d t o t h e s p e c ifi e d t r a n s m it a n d r e c e iv e p in s b a u d S e t t h e b a u d r a t e o f t h e s e r ia l p o r t f o r m a t S e t t h e t r a n s m is s io n fo r m a t u s e d b y t h e s e r ia l p o r t p u t c W r it e a c h a r a c t e r g e t c R e a d a c h a ra c te r p r i n t f W r it e a fo r m a t t e d s t r in g s c a n f R e a d a fo r m a t t e d s t r in g r e a d a b l e D e t e r m in e if t h e r e is a c h a r a c t e r a v a ila b le t o r e a d w r i t e a b l e D e t e r m in e if t h e r e is s p a c e a v a ila b le t o w r it e a c h a r a c t e r a t t a c h A t t a c h a fu n c t io n t o c a ll w h e n e v e r a s e r ia l in t e r r u p t is g e n e r a t e d p r o g r a m w e lo a d in to b o th m b e d s . I t f o llo w s a s im ila r p a tte r n to P r o g r a m E x a m p le 7 .2 , b u t rep laces all SPI co d e with UART co d e. Th e co d e itself ap p lies a n u mb er o f fu n ctio n s fro m Ta b le 7 .9 , a n d er e a d in g th e c o m m e n ts es h o u ld n o t b e to o d if fi c u lt to f o llo w. F ig u r e 7 .1 3 : L in k in g t w o m b e d U A R T s S t a r t in g w it h S e r ia l C o m m u n ic a t io n / * P r a s i * / # i n c S e r i D i g i D i g i D i g i D i g i D i g i c h a r c h a r i n t o g r a m m i l a r l u d a l t a l t a l t a l t a l t a l s w r e m a a s y n / / a c w h i l / / s w i f i f s t w a s t a s i f e a s O u O u O u I n I n i t c d i n c _ c e e S e i t ( s w ( s w r o i t r o y n ( r e E x a m p l e 7 . 9 : S e t s t h e m b e d u p n o d e , s e n d i n g i t s o w n s w i t c h " m b y n c t r t g t s s w s w c h _ _ v a ( ) p o p t ( 1 t c h s w i t s w i t b e _ u b e c _ a s c d e d _ p e d r e t r i t i t w o l ; { r t . d e ) { u p _ w o i t c c h _ i t c c h _ = 1 s ( 1 = 0 ; p o r y n c _ v a . h o r _ l e n o b c h c h r d " t ( e d _ l e ( _ i _ i ; p 9 ( p e d p 7 p 1 p 2 , 2 5 ( p ) ; ( p ( p p 1 0 ) ; ) ; 2 6 ) ; e = 0 i p r d i p r d w o x a 1 = = s 2 = = s f o r a s y n c c o m m u n i c a t i o n , a n d e x c h a n g e s d a t a w i t h p o s i t i o n s , a n d d i s p l a y i n g t h o s e o f t h e o t h e r . / / s e t u p T X a n d R X o n / / r e d l e d / / g r e e n l e d / / a s t r o b e t o t r i g g e r / / t h e / / t h e r d 0 ; = 1 w i = 1 w i p i n s t h e 9 a n d 1 0 s c o p e 5 ) ; 6 ) ; b a u d ( 9 6 0 0 ) ; f a u l t f o r m a t , t h r d h _ w o h _ w o ; 0 ) 1 4 3 t o o f b e 8 b i t s , s e n t , b y w o r d w e w i l l s e n d r e c e i v e d v a l u e / / s e t b a u d n o p a r i t y r a t e t o 9 6 0 0 ( i e t e s t i n g s w i t c h i n p u t s / / s e t u p a r e c o g n i z a b l e d e f a u l t ) o u t p u t p a t t e r n ) t c h _ w o r d j0 x 0 1 ; / / O R i n t c h _ w o r d j0 x 0 2 ; / / O R i n / / s h o r t l s b ) n e x t l s b s t r o b e p u l s e ; t . p u t c ( s w i t c h _ w o r d ) ; _ p o r t . r e a d a b l e ( ) = = 1 ) l = a s y n c _ p o r t . g e t c ( ) ; / / t r a n s m i t s w i t c h _ w o r d / / i s t h e r e a c h a r a c t e r / / i f y e s , t h e n r e a d i t t o b e r e a d ? . ( c o n t i n u e s a s i n P r o g r a m E x a m p l e 7 . 2 ) . } } P r o g r a m E x a m p le 7 .9 B id ir e c tio n a l d a ta tr a n s fe r b e tw e e n tw o m b e d U A R T s C o n n e c t tw o m b e d s a s s h o w n in F ig u r e 7 .1 3 , a n d c o m p ile a n d d o w n lo a d P r o g r a m E x a m p le 7 .9 in to e a c h . Yo u s h o u ld fi n d th a t th e s w itc h e s f r o m o n e m b e d c o n tr o l th e L E D s f r o m th e o th er, an d v ice v ersa. n E x e r c is e 7 .6 O n a n o s c t h e o s c illo s w it c h e s a 1 . W h a t C h a n g illo s c o p e , o s c o p e fro m re p re s s e d . is t h e t im e e th e b a u d b s e r v e t h e d a t a w a v e fo r m o f o n e o f t h e T X lin e s . It h e lp s t o t r ig g e r t h e s t r o b e p u ls e ( p in 7 ) . S e e h o w t h e p a t t e r n c h a n g e s a s t h e d u r a t io n o f e a c h d a t a b it ? H o w d o e s t h is r e la t e t o t h e b a u d r a t e ? r a t e a n d m e a s u r e t h e n e w d u r a t io n . 1 4 4 Chapter 7 2 . Is t h e d a t a b y t e t r a n s m it t e d M S B fi r s t o r L S B ? H o w d o e s t h is c o m p a r e t o t h e s e r ia l p r o t o c o ls s e e n e a r lie r in t h is c h a p t e r ? 3 . W h a t is t h e e ffe c t o f r e m o v in g o n e o f t h e d a t a lin k s in F ig u r e 7 .1 3 ? n 7 .9 .3 A p p ly in g S y n c h r o n o u s C o m m u n ic a t io n w it h t h e H o s t C o m p u t e r Wh ile th e mb ed h as th ree UARTs co n n ectin g to th e ex tern al p in s, Th is is reserv ed fo r co mmu n icatio n b ack to th e USB lin k , an d can d ia g r a m in F ig u r e 2 .2 . T h is UA RT a c ts ju s t lik e a n y o f th e o th e r s , in ( Ta b le 7 .8 ) . We h a v e b e e n u s in g it a lr e a d y , f o r th e fi r s t tim e in P r o saw th ere, th e mb ed co mp iler will reco g n ize p c , U S B T X an d U S B th is co n n ectio n , as in th e lin e: S e r i a l p c ( U S B T X , th e LPC1 7 6 8 h as a fo u rth . b e seen in th e mb ed b lo ck terms o f its u se o f th e API g r a m E x a m p le 5 .4 . A s w e R X as id en tifiers to set u p U S B R X ) ; With p c th u s c rea te d , th e A P I m e mb er fu n c tio n s c a n b e ex p lo ite d . T h e re q u ire m e n t to s et u p th e h o s t c o m p u te r c o rr e c tly in o rd e r to c o m m u n ic a te w ith th is lin k w a s o u tlin e d in S e c tio n 5 .3 . 7 .1 0 M in i-P r o je c t : M u lt i-N o d e I2 C B u s Desig n a simp le circu it wh ich h as a temp eratu re sen so r, ran g e fin d er an d mb ed co n n ected to th e s a m e I 2 C b u s . M e rg e P r o g r a m E x a m p le s 7 .8 a n d 7 .9 , s o th a t m e a s u r e m e n ts f r o m e a c h s e n s o r a r e d is p la y e d in tu r n o n th e s c r e e n . Ve r if y th a t th e I 2 C p r o to c o l w o r k s a s e x p e c te d . C h a p t e r R e v ie w • • • • • • Serial d ata lin k s p ro v id e a read y mean s o f co mmu n icatio n b etween micro co n tro ller an d p e rip h e ra ls , a n d /o r b e twee n micro co n tro llers . SPI is a simp le sy n ch ro n o u s stan d ard , wh ich is still v ery wid ely ap p lied . Th e mb ed h as two SPI p o rts an d a su p p o rtin g lib rary . Wh ile a v ery u sefu l stan d ard , SPI h as certain v ery clear limitatio n s, relatin g to a lack o f flex ib ility an d ro b u stn ess. T h e I2 C p ro to c o l is a m o re s o p h is tic a te d s e ria l a lte rn a tiv e to S P I; it ru n s o n a tw o -w ire b u s , an d in clu d es ad d ressin g an d ack n o wled g men t. I2 C is a flex ib le an d v ersatile stan d ard . Dev ices can b e read ily ad d ed to o r remo v ed fro m an ex istin g b u s, mu lti-master co n fig u ratio n s are p o ssib le, an d a master can d etect if a slav e fails to resp o n d , an d can tak e ap p ro p riate actio n . Nev erth eless, I2 C h as limitatio n s wh ich mean th at it can n o t b e u sed fo r h ig h -reliab ility ap p licatio n s. A v ery wid e ran g e o f p erip h eral d ev ices is av ailab le, in clu d in g in tellig en t sen so rs, wh ich co mmu n icate th ro u g h SPI an d I2 C. S t a r t in g w it h S e r ia l C o m m u n ic a t io n 1 4 5 A u s e fu l a s y n c h ro n o u s a lte rn a tiv e to I 2 C a n d S P I is p ro v id e d b y th e UA RT. T h e m b e d h a s fo u r o f th ese, o n e o f wh ich p ro v id es a co mmu n icatio n lin k b ack to th e h o st co mp u ter. • Q u iz 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 1 0 . Wh at d o th e ab b rev iatio n s SPI, I2 C an d UART stan d fo r? Draw u p a tab le co mp arin g th e ad v an tag es an d d isad v an tag es o f u sin g SPI v ersu s I2 C fo r serial co mmu n icatio n s. Wh at are th e limitatio n s fo r th e n u mb er o f d ev ices th at can b e co n n ected to a sin g le SPI, I2C o r UART b u s? A SPI lin k is ru n n in g with a 5 0 0 k Hz clo ck . Ho w lo n g d o es it tak e fo r a sin g le messag e co n tain in g o n e d ata b y te to b e tran smitted ? An mb ed co n fig u red as SPI master is to b e co n n ected to th ree o th er mb ed s, each co n fig u red as slav e. Sk etch a circu it sh o win g h o w th is in terco n n ectio n co u ld b e mad e. Ex p lain y o u r sk etch . An mb ed is to b e set u p as SPI master, u sin g p in s 1 1 , 1 2 an d 1 3 , ru n n in g at a freq u en cy o f 4 MHz, with 1 2 -b it wo rd len g th . Th e clo ck sh o u ld id le at Lo g ic 1 , an d d ata sh o u ld b e la tc h e d o n its n e g a tiv e e d g e . W rite th e n e c e s s a ry c o d e to s e t th is u p . Rep eat Qu estio n 4 , b u t fo r I2 C, en su rin g th at y o u calcu late time fo r th e co mp lete messag e. Rep eat Qu estio n 5 , b u t fo r I2 C. Id en tify carefu lly th e ad v an tag es an d d isad v an tag es o f each co n n ectio n . Yo u n e e d to s e t u p a s e r ia l n e tw o r k , w h ic h w ill h a v e o n e m a s te r a n d f o u r s la v e s . E ith e r SPI o r I2 C can b e u sed . Ev ery seco n d , d ata h as to b e d istrib u ted , su ch th at o n e b y te is sen t to Slav e 1 , fo u r to Slav e 2 , th ree to Slav e 3 an d fo u r to Slav e 4 . If th e co mp lete d ata tran sfer mu st tak e n o t mo re th an 2 0 0 m s, estimate th e min imu m clo ck freq u en cy th at is allo wab le fo r SPI an d I2 C. Assu me th ere are n o o th er timin g o v erh ead s. Rep eat Qu estio n 4 , b u t fo r asy n ch ro n o u s co mmu n icatio n th ro u g h a UART, assu min g a b au d rate o f 5 0 0 k Hz. En su re th at y o u calcu late time fo r th e co mp lete messag e. References 7 .1 . 7 .2 . 7 .3 . 7 .4 . 7 .5 . S p a s o v , P. ( 1 9 9 6 ) . M ic r o c o n tr o lle r Te c h n o lo g y , T h e 6 8 H C 1 1 . 2 n d e d itio n . P r e n tic e H a ll. A D X L 3 4 5 D a ta s h e e t, R e v . C . w w w.a n a lo g .c o m NXP Semico n d u cto rs. Th e I2 C Bu s Sp ecificatio n an d User Man u al. Rev . 0 3 . 2 0 0 7 . Do cu men t n u mb er UM1 0 2 0 4 . Tex as In stru men ts. TMP1 0 2 . Lo w Po wer Dig ital Temp eratu re Sen so r. Au g u st 2 0 0 7 . Rev . Octo b er 2 0 0 8 . Do cu men t n u mb er SBOS3 9 7 B. S R F 0 8 d a ta . h ttp ://w w w.r o b o t- e le c tr o n ic s .c o .u k /h tm /s r f 0 8 te c h .s h tm l. A c c e s s e d 3 0 J u ly 2 0 1 1 . CHAPTER 8 Liquid Crystal Displays Chapter Outline 8.1 Display Technologies 147 8.1.1 Introducing Liquid Crystal Technology 148 8.1.2 Liquid Crystal Character Displays 149 8.2 Using the PC1602F LCD 150 8.2.1 Introducing the PC1602F Display 151 8.2.2 Connecting the PC1602F to the mbed 152 8.2.3 Using Modular Coding to Interface the LCD 153 8.2.4 Initializing the Display 154 Function Mode 154 DisplayMode 154 Clear Display 155 8.2.5 Sending Display Data to the LCD 155 8.2.6 The Complete LCD.cpp Definition 156 8.2.7 Utilizing the LCD Functions 157 8.2.8 Adding Data to a Specified Location 158 8.3 Using the mbed TextLCD Library 160 8.4 Displaying Analog Input Data on the LCD 162 8.5 More Advanced LCDs 163 8.5.1 Color LCDs 163 8.5.2 Controlling a SPI LCD Mobile Phone Display 163 8.6 Mini-Project: Digital Spirit Level 166 Chapter Review 167 Quiz 167 References 167 8.1 Display Technologies Light-emitting diodes (LEDs), particularly individual LEDs and seven-segment displays, havealready been encountered in previous chapters. On their own, LEDs can only informus of a few different states, for example to indicate whether something is on or off, or whether a variable is cleared or set. It is possible to be innovative in the way LEDs are used, for example, differentflashingspeedscanbeusedto representdifferentstates, butclearly thereis Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00008-8 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 147 148 Chapter 8 a limit to how much information a single LED can communicate. With seven-segment displays it is possibleto display numbers and afew characters fromthe alphabet, but there is a problem with seven-segment displays in that in simple use they require a microcontroller output for each LED segment. The multiplexing technique described in Section 3.6.3 can be used, but a limitation is still seen. Equally, LEDs are relatively power hungry, which is an issueforpower-conscious designs. Embeddedsystems designersneedto becleverintheway they usetheavailableinputandoutputcapabilitiesof amicrocontroller, butobviously theuse of LEDs as a display has its limitations. If text-based messages with a number of characters are required to be communicated with a user, then a more advanced display type is needed, such as the liquid crystal displays (LCDs) that are commonly used in consumer electronics. 8.1.1 Introducing Liquid Crystal Technology Liquid crystal displays are of great importance these days, both in the electronic world in general, andintheembeddedsystemenvironment. Theirmainadvantagesaretheirextremely lowpowerrequirements, light weight andhighflexibility of application. They havebeenone of the enabling technologies for battery-powered products such as the digital watch, the laptopcomputerandthemobiletelephone, andareavailableinahugerangeof indicatorsand displays. However, LCDs do have some disadvantages; these include limited viewing angle andcontrastinsomeimplementations, sensitivity totemperatureextremes, andvery highcost for the more sophisticated graphical displays. Although LCDs do not emit light, they can reflect incident light, or transmit or block backlight. Theprincipleof anLCD isillustratedinFigure8.1. Theliquidcrystal isanorganic compound which responds to an applied electric field by changing the alignment of its molecules, and hence the light polarization that it introduces. A small quantity of liquid crystal is contained between two parallel glass plates. A suitable field can be applied if transparent electrodes are located on the glass surface. In conjunction with the external polarizing light filters, light is either blocked or transmitted by the display cell. The electrodes can be made in any pattern desired. These may include single digits or symbols, orthestandardpatternsof bargraph, seven-segment, dotmatrix, starburst andso on. Alternatively, they may be extended to complex graphical displays, with addressable pixels. Transparent Conductive Coating Polarizing Filter Electrical Contacts Glass Liquid Crystal Figure 8.1: A simple liquid crystal structure Liquid Crystal Displays 149 8.1.2 Liquid Crystal Character Displays A popular, indeed ubiquitous, form of LCD is the character display, as seen in Figure 8.2. These are widely available from one line of characters to four or more, and are commonly seen on many domestic and office items, such as photocopiers, burglar alarms and DVD players. Driving this complex array of tiny LCD dots is far from simple, so such displays always contain a hidden microcontroller, customized to drive the display. The first such controller to gain widespread acceptance was the Hitachi HD44780. While this has been supersededby others, they havekepttheinterfaceandinternal structureof theHitachi device. It is important to know its main features, in order to design with it. The HD44780 contains an 80-byte random access memory (RAM) to hold the display data, and aread only memory (ROM) forgenerating the characters. It has asimple instruction set, including instructions for initialization, cursor control (moving, blanking, blinking) and clearing the display. Communication with the controller is made via an 8-bit data bus, three control lines and an enable/strobe line (E). These are itemized in Figure 8.3a. Data written to the controller is interpreted either as instruction or as display data (Figure 8.3b), depending on the state of the RS (Register Select) line. An important use of reading data back fromthe LCD is to check the controller status via the Busy flag. As some instructions take a finite time to implement (e.g. a minimum of 40 ms is required to receive one character code), it is sometimes useful to be able to read the Busy flag and wait until the LCD controller is ready to receive further data. Thecontrollercanbeset upto operatein8-bit or4-bit mode. Inthelattermodeonly thefour most significant bits of the bus are used, and two write cycles are required to send a single byte. In both cases the most significant bit doubles as the Busy flag when a Read is undertaken. Figure 8.2: The mbed driving an LCD 150 Chapter 8 (a) (b) (c) RS R/W 0 0 Write instruction code 0 1 Read busy flag and address counter 1 0 Writedata 1 1 Read data higher order bits transmitted E Action lower order bits transmitted RS R/W E Instruction Write Busy Flag Check Busy Flag Check Data Write Figure 8.3: (a) HD44780 user interfacelines; (b) HD44780 data and instruction transfers; (c) HD44780 timing for 4-bit interface 8.2 Using the PC1602F LCD Thembedprocessorcanbeinterfacedto anexternal LCD, inordertodisplay messagesonthe screen. Interfacing an LCD requires a few involved steps to prepare the device and achieve thedesireddisplay. Thefollowingtasks must beconsideredinorderto successfully interface the LCD: Liquid Crystal Displays 151 • Hardware integration: the LCD will need to be connected to the correct mbed pins. • Modular coding: as there are many processes that need to be completed, it makes sense to define LCD functions in modular files. • Initializing the LCD: a specific sequence of control signals must be sent to the LCD to initialize it. • Outputtingdata: wewill needtounderstandhowtheLCD convertscontrol dataintolegible display data. Here, wewill usethe2 16characterPowertipPC1602FLCD, althoughanumberof similar LCDs can be found with the same hardware configuration and functionality. 8.2.1 Introducing the PC1602F Display ThePC1602Fdisplay isa2 16characterdisplay withanonboarddatacontrollerchipandan integratedbacklight, asseeninFigure8.2. TheLCD has 16connections, definedinTable8.1. Inthisexamplewewill usetheLCD in4-bitmode. Thismeansthatonly theupper4bitsof the data bus (DB4eDB7) are connected. The two halves of any byte are sent in turn on these Table 8.1: PC1602F pin descriptions Pin number Pin name Function 1 VSS Power supply (GND) 2 VDD Power supply (5 V) 3 V0 Contrast adjust 4 RS Register select signal 5 R=W Data read / write 6 E Enable signal 7 DB0 Data bus line bit 0 8 DB1 Data bus line bit 1 9 DB2 Data bus line bit 2 10 DB3 Data bus line bit 3 11 DB4 Data bus line bit 4 12 DB5 Data bus line bit 5 13 DB6 Data bus line bit 6 14 DB7 Data bus line bit 7 15 A Power supply for LED backlight (5 V) 16 K Power supplyfor LED backlight (GND) 152 Chapter 8 lines. As a result, the LCD can be controlled with only seven lines, rather than the 11 lines requiredfor8-bitmode. Every timeanibble(a4-bitwordissometimescalledanibble) issent, the E line must be pulsed, as seen in Figure 8.3. The display is initialized by sending control instructions to the configuration registers in the LCD. This is done by setting RS and R=W low; once the LCD has been initialized, display data can be sent by setting the RS bit high. As before, the E bit must be pulsed for every nibble of display data sent. 8.2.2 Connecting the PC1602F to the mbed An mbed pin should be attached to each of the LCD data pins that are used, configured as digital output. Fouroutputsarerequiredto sendthe4-bitinstructionanddisplay dataandtwo outputs are required to manipulate the RS and E control lines. Thesuggestedinterfaceconfigurationforconnectingthembedto thePC1602Fisasshownin Table8.2. Notethat, insimpleapplications, theLCD canbeusedonly inwritemode, so R=W canbetiedpermanently to ground(mbedpin1). If rapidcontrol of theLCD isrequired, i.e. if it needs updating faster than approximately every 1 ms, then the R=W input can be activated to enable reading from the LCD’s Busy flag. The Busy flag changes state when a display request has been completed, so by testing it the LCD can be programmed to operate as quickly aspossible. If theR=W lineistiedtoground, thena1 msdelay betweendatatransfers is adequate to ensure that all internal processes can complete before the next transfer. Table 8.2: Wiring table for connecting the PC1602F to the mbed mbed pin number LCD pin number LCD pin name Power connection 1 1 VSS 0V 39 2 VDD 5V 1 3 V0 0V 19 4 RS 1 5 R=W 20 6 E 21 11 DB4 22 12 DB5 23 13 DB6 24 14 DB7 39 15 A 5V 1 16 K 0V A: anode; K: cathode of the backlight LED. 0V Liquid Crystal Displays 153 Figure 8.4: PC1602F physical pin layout TheLCD pins DB0, DB1, DB2 andDB3areleft unconnectedas thesearenot requiredwhen operating in 4-bit data mode. The PC1602F has the pin layout shown in Figure 8.4. 8.2.3 Using Modular Coding to Interface the LCD Initializing and interfacing a peripheral device, such as an LCD, can be done effectively by usingmodularfilestodefinevariouspartsof thecode. Wewill thereforeusethreefilesforthis application. The files required are: • a main code file (main.cpp), which can call functions defined in the LCD feature file • an LCD definition file (LCD.cpp), which will include all the functions for initializing and sending data to the LCD • an LCD header file (LCD.h), which will be used to declare data and function prototypes. We will declare the following functions in the LCD header file: • toggle_enable( ): a function to toggle/pulse the enable bit • LCD_init( ): a function to initialize the LCD • display_to_LCD( ): a function to display characters on the LCD. The LCD.h header file should therefore define the function prototypes as shown in Program Example 8.1. /* Program Example 8.1: LCD.h header file */ #ifndef LCD_H #define LCD_H #include "mbed.h" void toggle_enable(void); //function to toggle/pulse the enable bit void LCD_init(void); //function to initialize the LCD void display_to_LCD(char value); //function to display characters #endif Program Example 8.1 LCD header file IntheLCD definitionfile(LCD.cpp), weneedto definethembedobjects requiredto control the LCD. Here, one digital output each can be used for RS and E, and an mbed BusOut 154 Chapter 8 object for the 4-bit data. The suggested mbed object definitions need to conform to the pin connections listed in Table 8.2. To control and initialize the LCD, we send a number of control bytes, each sent as two 4-bit nibbles. Aseachnibbleis asserted, theLCD requirestheE bit to bepulsed. Thisisdone by the toggle_enable( ) function, detailed in Program Example 8.2. 8.2.4 Initializing the Display A specific initialization procedure must be programmed in order for the PC1602F display to operate correctly. Full details are provided in the Powertip PC1602F datasheet (Reference 8.1) and also in Reference 8.2. Readingthisdata, weseethatwefirstneedtowaitashortperiod(approximately 20 ms), then set theRSandElinesto zero, andthensendanumberof configurationmessagesto set upthe LCD. WethenneedtosendconfigurationdatatotheFunctionMode, Display ModeandClear Display registers in order to initialize the display. These are now introduced. Function Mode To set the LCD function mode, the RS, R=W and DB0-7 bits should be set as shown in Figure 8.5. Data bus values are sent as two nibbles. If,forexample,wesendabinaryvalueof 00101000(0x28hex)totheLCDdatapins,thisdefines 4-bitmode, 2linedisplay and5x7dotcharacters. Inthegivenexamplewewouldthereforesend thevalue0x2, pulseE, thensend0x8, thenpulseE again. TheC/Cþ þ codeFunctionMode registercommands areshownintheLCD_init( ) functiondetailedin ProgramExample8.2. Display Mode TheDisplay Modecontrol registermust also beset upduringinitialization. Here, weneedto send a command to switch the display on, and to determine the cursor function. The Display Mode register is defined as shown in Figure 8.6. Figure 8.5: Function Mode control register Liquid Crystal Displays 155 Figure 8.6: Display Mode control register Inorderto switchthedisplay onwithablinking cursor, thevalue0x0F(intwo 4-bit nibbles) isrequired. TheC/Cþ þ codeDisplay ModeregistercommandsareshownintheLCD_init( ) function detailed in Program Example 8.2. Clear Display Before data can be written to the display, the display must be cleared, and the cursor reset to the first character in the first row (or any other location that you wish to write data to). The Clear Display command is shown in Figure 8.7. Figure 8.7: Clear Display command 8.2.5 Sending Display Data to the LCD A function called (in this example) display_to_LCD( ) displays characters on the LCD screen. Characters aredisplayedby settingtheRSflagto 1(datasetting), thensendingadata byte describing the ASCII character to be displayed. ThetermASCII (AmericanStandardCodeforInformationInterchange) has beenintroduced previously in Chapter 6; it is a method for defining alphanumeric characters as 8-bit values. Whencommunicatingwithdisplays, by sendingasingleASCII byte, thedisplay is informed which particular character should be shown. The complete ASCII table is included with the LCD datasheet, but for interest some common ASCII values for display on the LCD are shown in Table 8.3. The display_to_LCD( ) function needs to accept an 8-bit value as adata input, so that it can display thedesiredcharacterontheLCD screen. InC/Cþ þ thechar datatypecanbeusedto define an 8-bit number. It can be seen in the LCD.h header file (Program Example 8.1) that 156 Chapter 8 Table 8.3: Common ASCII values Less significant bits (lower nibble) 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB 0xC 0xD 0xE 0xF More significant bits 0x0 (upper nibble) 0x1 0x2 ! " # $ % & ’ ( ) * þ , - . / 0x3 0 1 2 3 4 5 6 7 8 9 : ; < ¼ > ? 0x4 @ A B C D E F G H I J K L M N O 0x5 P Q R S T U V W X Y Z [ \ ] ^ _ 0x6 ‘ a b C d e f g h i j k l m n o 0x7 p q r S t u v w x y z { j } ~ display_to_LCD( ) has already been defined as a function with a char input. Referring to Table 8.3, it can be seen, for example, that if we send the data value 0x48 to the display, the character ‘H’ will be displayed. The display_to_LCD( ) function is shown in Program Example 8.2. Note that, as we are using4-bit mode, themost significant bits of theASCII bytemust beshiftedright inorderto be output on the 4-bit bus created through BusOut. The lower 4 bits can then be output directly. 8.2.6 The Complete LCD.cpp Definition The LCD definition file (LCD.cpp) contains the three C functions e toggle_enable( ), LCD_init( ) anddisplay_to_LCD( ) e asdescribedabove. Thecompletelistingof LCD.cpp is shown in Program Example 8.2. Note that the toggle_enable( ) function has two 1 ms delays, whichremove the need to monitor theBusy flag; the downsideto this is that wehave introduced a timing delay into our program, the consequences of which will be discussed in more detail in Chapter 9. /* Program Example 8.2: Declaration of objects and functions in LCD.cpp file */ #include "LCD.h" DigitalOut RS(p19); DigitalOut E(p20); BusOut data(p21, p22, p23, p24); void toggle_enable(void){ E=1; wait(0.001); E=0; Liquid Crystal Displays 157 wait(0.001); } //initialize LCD function void LCD_init(void){ wait(0.02); // pause for 20 ms RS=0; // set low to write control data E=0; // set low //function mode data=0x2; toggle_enable(); data=0x8; toggle_enable(); //display mode data=0x0; toggle_enable(); data=0xF; toggle_enable(); //clear display data=0x0; toggle_enable(); data=0x1; toggle_enable(); // 4 bit mode (data packet 1, DB4-DB7) // 2-line, 7 dot char (data packet 2, DB0-DB3) // 4 bit mode (data packet 1, DB4-DB7) // display on, cursor on, blink on // // clear } //display function void display_to_LCD(char value){ RS=1; // set high to write character data data=value>>4; // value shifted right 4 = upper nibble toggle_enable(); data=value; // value bitmask with 0x0F = lower nibble toggle_enable(); } Program Example 8.2 Declaration of objects and functions in LCD.cpp 8.2.7 Utilizing the LCD Functions We can now develop a main control file (main.cpp) to utilize the LCD functions described above. Program Example 8.3 initializes the LCD, displays the word ‘HELLO’ and then displays the numerical characters from 0 to 9. /* Program Example 8.3 Utilizing LCD functions in the main.cpp file */ #include "LCD.h" int main() { LCD_init(); // call the initialize function display_to_LCD(0x48); // ‘ H’ display_to_LCD(0x45); // ‘ E’ display_to_LCD(0x4C); // ‘ L’ display_to_LCD(0x4C); // ‘ L’ display_to_LCD(0x4F); // ‘ O’ 158 Chapter 8 for(char x=0x30;x<=0x39;x++){ display_to_LCD(x); // display numbers 0-9 } } Program Example 8.3 File main.cpp utilizing LCD functions n Exercise 8.1 Applying Table8.2, connect a Powertip PC1602F LCD to an mbed and construct a new program with the files main.cpp, LCD.cpp and LCD.h as described in the program examples above. Compile and run the program. 1. Verify that the word ‘HELLO’ and the numerical characters 0e9 are correctly displayed with a flashing cursor. 2. Change the program so that your name appears on the display, after the word ‘HELLO’, instead of the numerical characters 0e9. n n Exercise 8.2 If you look at the toggle_enable( ) function in Program Example 8.2, you will notice that it sets theE linehigh and low, waiting 1 ms in each case. This saves us testing the Busy flag, as seen in Figure 8.3c, as the display will have exited from its Busy state during the 1 ms delay. For many embedded applications, however, this loss of 2 ms would be quite unacceptable. Tryapplyingtheinformation so far supplied to writearevised program, so that thedelays areremoved, and theBusyflagistested. You will nowneed to activateR=W and set it to 1 in order to read theBusyflag, which is indicated bydata bit DB7. OnceBusyis clear, the program should proceed. Estimate how much time is saved by your new program. You can test this with an oscilloscope by making your program write a digit continuously to the display, and measuring on the oscilloscope the time between the E pulses. n 8.2.8 Adding Data to a Specified Location The display is mapped out with memory address locations so that each display unit has auniqueaddress. Thedisplay pointercanthereforebeset beforeoutputtingdata, andthedata will then appear in the position specified. The display address layout is shown in Figure 8.8. If theprogramcounterisset to address0x40, datawill bedisplayedatthefirstpositiononthe second line. To change the pointer address, the desired 6-bit address value must be sent in a control byte with bit 7 also set, as shown in Figure 8.9. Liquid Crystal Displays 159 Figure 8.8: Screen display pointer address values A new function can be created to set the location of the display pointer prior to writing. We will call this function set_location( ), as shown in Program Example 8.4. /* Program Example 8.4 function to set the display location. Parameter “ location” address of display unit to be selected */ void set_location(char location){ RS=0; data=(locationj0x80)>>4; // upper nibble toggle_enable(); data=location&0x0F; // lower nibble toggle_enable(); } holds Program Example 8.4 Function to change the display pointer position Notice that bit DB7 is set by ORing the location value with 0x80. n Exercise 8.3 Addtheset_location( ) functionshowninProgramExample8.4totheLCD.cppdefinition. You will also need to declarethefunction prototypein LCD.h. Now add set_location( ) function callsto main.cpp so that theword ‘HELLO’ appearsin thecenter of thefirst line and thenumerical characters 0e9 appear in thecenter of thesecond lineof thedisplay. n n Exercise 8.4 Modify the LCD_init( ) function to disable the flashing cursor. Here, you will need to modify the value sent to the Display Mode register. n Figure 8.9: Display pointer control 160 Chapter 8 8.3 Using the mbed TextLCD Library Thereis anmbedlibrary whichmakes theuseof analphanumeric LCD muchsimplerand quickertoprogram.ThembedTextLCDlibraryisalsomoreadvancedthanthesimplefunctions wehavecreated;inparticular,theTextLCDlibraryperformsthelaboriousLCDsetuproutinefor us. TheTextLCD definitionalso tellstheLCD objectwhichpinsareusedforwhichfunctions. The object definition is defined in the following manner: TextLCD lcd(int rs, int e, int d0, int d1, int d2, int d3); We need to ensure that our pins are defined in the same order. For our particular hardware setup (described in Table 8.2) this will be: TextLCD lcd(p19, p20, p21, p22, p23, p24); Simple printf( ) statements are used to display characters on the LCD screen; this statement is also discussed in Section B.9 of Appendix B. The printf( ) function allows formatted print statements to be used. This means that text strings and formatted data can be sent to a display, meaning that a function call is not required for each individual character (as was the case in Program Example 8.3). C code feature Whenusingtheprintf( ) functionwiththembedTextLCD library, thedisplay object’s name isalso required, so if theTextLCD objectisdefinedasintheexamplesabove(withtheobject name lcd), then a ‘Hello World’ string can be written as follows: lcd.printf("Hello World!"); Whenusingpredefinedmbedlibraries, suchasTextLCD, thelibrary fileneedstobeimported to the mbed program. The mbed TextLCD library can (at the time of writing) be accessed from the following location: http://mbed.org/users/simon/libraries/TextLCD/livod0 Thelibrary headerfilemustalso beincludedwiththe#includestatementinthemain.cpp file orrelevant project headerfiles. ProgramExample8.5 is asimpleHello Worldexampleusing the TextLCD library. /*Program Example 8.5: TextLCD library example */ #include "mbed.h" #include "TextLCD.h" TextLCD lcd(p19, p20, p21, p22, p23, p24); //rs,e,d0,d1,d2,d3 int main() { lcd.printf("Hello World!"); } Program Example 8.5 TextLCD Hello World The cursor can be moved to a chosen position to allow you to choose where to display data. This uses the locate( ) function as follows. The display is laid out as two rows (0e1) of 16 Liquid Crystal Displays 161 columns (0e15). The locate function defines the column first followed by the row. For example, add the following statement to move the cursor to the second line and fourth column: lcd.locate(3,1); Any printf( ) statements after this will be printed at the new cursor location. n Exercise 8.5 1. Create a new program and import the TextLCD library file (right click on the project and select ‘import library’). 2. Add Program Example 8.5 to the main.cpp file and compile and run. Verify that the program correctly displays the Hello World characters. 3. Experiment further with thelocatefunction and verifythat theHello World stringcan be positioned to a desired location on the display. n The screen can also be cleared with the following command: lcd.cls(); Program Example 8.6 displays a count variable on the LCD. The count variable increments every second. /* Program Example 8.6: LCD Counter example */ #include "mbed.h" #include "TextLCD.h" TextLCD lcd(p19, p20, p21, p22, p23, p24); // rs, e, d0, d1, d2, d3 int x=0; int main() { lcd.printf("LCD Counter"); while (1) { lcd.locate(5,1); lcd.printf("%i",x); wait(1); x++; } } Program Example 8.6 LCD counter n Exercise 8.6 1. Implement Program Example 8.6 as a new program. Do not forget to import the TextLCD library! 2. Increasethespeed of thecounter and investigatehowthecursor position changes as the count value increases. n 162 Chapter 8 8.4 Displaying Analog Input Data on the LCD An analog input can be defined e before the main( ) function e on pin 18 as follows: AnalogIn Ain(p18); We can now connect a potentiometer between 3.3 V (mbed pin 40) and 0 V (mbed pin 1) with the wiper connected to pin 18. The analog input variable has a floating point value between 0 and 1, where 0 is 0 V and 1 represents 3.3 V. We will multiply the analog input value by 100 to display a percentage between 0 and 100%, as shown in Program Example 8.7. An infinite loop can be used so that the screen updates automatically. To do this it is necessary to clear the screen and add a delay to set the update frequency. /*Program Example 8.7: Display analog input data */ #include "mbed.h" #include "TextLCD.h" TextLCD lcd(p19, p20, p21, p22, p23, p24); //rs,e,d0, d1,d2,d3 AnalogIn Ain(p17); float percentage; int main() { while(1){ percentage=Ain*100; lcd.printf("%1.2f",percentage); wait(0.002); lcd.cls(); } } Program Example 8.7 Display analog input data n Exercise 8.7 1. Implement ProgramExample8.7 and verifythat thepotentiometer modifiesreadings between 0 and 100%. 2. Modify the wait( ) statement to be a larger value and evaluate the change in performance. It is interesting to make a mental note that a certain range of update ratesappearsirritatingto view(too fast), whileothersmaybeperceived astoo slow. n n Exercise 8.8 Create a program to make the mbed and display act like a standard voltmeter, as shown in Figure8.10. Potential differenceshould bemeasured between 0 and 3.3 V and displayed to the screen. Note the following: Liquid Crystal Displays 163 Figure 8.10: Voltmeter display • You will need to convert the 0.0e1.0 analog input value to a value that represents 0 e3.3 V. • An infinite loop is required to allow the voltage value to update continuously as the potentiometer position changes. • Check the display with the reading from an actual voltmeter: is it accurate? • Increase the number of decimal places that the voltmeter reads. Evaluate the noise and accuracyof thevoltmeter readings with respect to thembed’s ADC resolution. n 8.5 More Advanced LCDs 8.5.1 Color LCDs Nowadays, LCD technology is used in advanced displays for mobile phones, PC monitors and televisions. For color displays, each pixel is made up of three subpixels for red, green and blue. Each subpixel can be set to 256 different shades of its color, so it is therefore possible for a single LCD pixel to display 256 * 256 * 256 ¼16.8 million different colors. The pixel color is therefore usually referred to by a 24-bit value, where the highest 8 bits definetheredshade, themiddle8bitsthegreenshadeandthelower8bitstheblueshade, as shown in Table 8.4. Given that each pixel needs to be assigned a 24-bit value and a 1280 1024 LCD computer display has over1 millionpixels (1280 * 1024 ¼1 310 720), alot of dataneeds to besent to a color LCD. Standard color LCDs are set to refresh the display at a frequency of 60 Hz, so the digital input requirements are much greater than those associated with the alphanumeric LCD discussed previously in this chapter. 8.5.2 Controlling a SPI LCD Mobile Phone Display A mobile phone screen, like the Nokia 6610, represents state-of-the-art, low-cost, highvolume display technology. Yet many have an interface based on the good old serial peripheral interface(SPI) standard, introducedinChapter7. Itishardtofindformal published 164 Chapter 8 Table 8.4: 24-bit color values Color 24-bit value Red 0xFF0000 Green 0x00FF00 Blue 0x0000FF Yellow 0xFFFF00 Orange 0xFF8000 Purple 0x800080 Black 0x000000 White 0xFFFFFF data on the Nokia display; Reference 8.3, however, gives some useful background. We can use the Nokia 6610 display with the mbed. Here, we will see how to connect it and how to type data on the screen fromthe PC keyboard. Instead of using the basic SPI library, wewill use the predesigned mbed MobileLCD library. You will need to import this library from: http://mbed.co.uk/projects/cookbook/svn/MobileLCD/tests/MobileLCD Themobilescreenhas10pins, asshowninFigure8.11. Itcanbeconnectedtothembedusing the connections shown in Table 8.5. It is possible to clear the screen, set the background color, fill blocks, draw pixel images, movethepointerandperformmany otheroperations. ProgramExample8.8writescharacters to the display from the computer keyboard, and uses the #key to clear the screen. /*Program Example 8.8: Program which reads character from computer screen, and displays on Nokia LCD display. */ #include "mbed.h" #include "MobileLCD.h" // include the Nokia display library MobileLCD lcd(p11, p12, p13, p15, p16); // mosi,miso,clk,cs,rst Serial pc(USBTX, USBRX); char c; void screen_setup(void); // host terminal comms setup // char variable for keyboard input // function prototype int main() { pc.printf("\n\rType something to be displayed:\n\r"); screen_setup(); // call the screen setup function while(1){ c = pc.getc(); // c = character input from computer keyboard wait(0.001); if (c==’ #’ ){ // perform the following if "#" is pressed screen_setup(); // call the screen setup function Liquid Crystal Displays 165 lcd.locate(0,0); } else{ lcd.printf("%c",c); pc.printf("%c",c); } } // move the cursor back to row 0 column 0 // print character on the LCD screen // print character on the terminal screen } //function definition for screen_setup void screen_setup(void) { lcd.background(0x0000FF); lcd.cls(); } // set the background color // clear the screen +3.3V BL+(5-7V) RST GND CS DIO / MOSI CLK Nokia 6610 Figure 8.11: Nokia 6610 display connections Table 8.5: Connections between Nokia display and mbed Nokia 6610 pin mbed pin þ 3.3 V 40 GND 1 BLþ 39 RST 9 CS 8 MOSI 5 CLK 7 166 Chapter 8 Program Example 8.8 Writing characters to the Nokia display Having connected the circuit, create a new project, and enter and compile the example code. Onceit is runningonthembed, andwiththeterminal applicationopen, youshouldbeableto type to the LCD screen. n Exercise 8.9 Add the following fill functions to the screen_setup( ) function (after the lcd.cls command) in order to fill some areas of the LCD: lcd.fill(2, 51, 128, 10, 0x00FF00); lcd.fill(50, 1, 10, 128, 0xFF0000); It is also possibleto draw on thescreen pixel bypixel. Thefollowing loop will createthe function for a sine wave and print this to the screen. Add this to the setup function. for(int i=0; i<130; i++) { lcd.pixel(i, 80 + sin((float)i / 5.0)*10, 0x000000); } n We have seen that LCDs allow greater flexibility than simple LED-based displays, and that simple alphanumeric and advanced color LCD devices can be utilized with microcontrollers and embedded systems. 8.6 Mini-Project: Digital Spirit Level Design, buildandtestadigital spiritlevel basedonthembed. UseanADXL345(Section7.3) accelerometer to measure the angle of orientation in two planes, a digital push-to-make switch to allow calibration and zeroing of the orientation, and a color LCD to output the measured orientation data, in degrees. To help you proceed, consider the following: 1. Design your display to show a pixel or an image moving around the LCD screen with respect to the orientation of the accelerometer. 2. Add the digital switch to allow simple calibration and zeroing of the data. 3. Improve your display output to give accurate measurements of the two-plane orientation angles in degrees from the horizontal (i.e. horizontal ¼0 ). Liquid Crystal Displays 167 Chapter Review • Liquid crystal displays (LCDs) use an organic crystal which can polarize and block light when an electric field is introduced. • Many types of LCDs areavailableand, wheninterfacedwithamicrocontroller, they allow digital control of alphanumeric character displays and high-resolution color displays. • The PC1602F is a 16-column by 2-row character display which can be controlled by the mbed. • DatacanbesenttotheLCDregisterstoinitializethedeviceandtodisplaycharactermessages. • Character data is defined using the 8-bit ASCII table. • The mbed TextLCD library can be used to simplify working with LCDs and allow the display of formatted data using the printf( ) function. • Color LCDs use a serial interface to display data, with each pixel given a 24-bit color setting. • The mbed MobileLCD library can be used to interface a Nokia 6610 mobile phone-type LCD. Quiz 1. What are the advantages and disadvantages associated with using an alphanumeric LCD in an embedded system? 2. What types of cursor control are commonly available on alphanumeric LCDs? 3. How does the mbed BusOut object help to simplify interfacing an alphanumeric display? 4. What is the function of the E input on an alphanumeric display such as the PC1602F? 5. What does ASCII stand for? 6. What are the ASCII values associated with the numerical characters from 0 to 9? 7. What is the correct printf( ) C/Cþ þ code required to display the value of a floating point variable called ‘ratio’ to two decimal places ? 8. List five practical examples of a color LCD used in an embedded system. 9. If a color LCD is filled to a single background color, what colors will the following 24-bit codes give: (a) 0x00FFFF (b) 0x00007F (c) 0x7F7F7F? References 8.1. Rapid Electronics. PC1602F datasheet. http://www.rapidonline.com/pdf/57-0913.pdf 8.2. HD44780 LCDisplays. http://www.a-netz.de/lcd.en.php 8.3. Nokia 6100 LCD Display Driver. http://www.sparkfun.com/tutorial/Nokia%206100%20LCD%20Display% 20Driver.pdf CHAPTER 9 Interrupts, Timers and Tasks Chapter Outline 9.1 Time and Tasks in Embedded Systems 170 9.1.1 Timers and Interrupts 170 9.1.2 Tasks 170 9.1.3 Event-Triggered and Time-Triggered Tasks 171 9.2 Responding to Event-Triggered Events 171 9.2.1 Polling 171 9.2.2 Introducing Interrupts 172 9.3 Simple Interrupts on the mbed 173 9.4 Getting Deeper into Interrupts 175 9.4.1 Interrupts on the LPC1768 178 9.4.2 Testing Interrupt Latency 178 9.4.3 Disabling Interrupts 179 9.4.4 Interrupts from Analog Inputs 180 9.4.5 Conclusion on Interrupts 181 9.5 An Introduction to Timers 181 9.5.1 The Digital Counter 181 9.5.2 Using the Counter as a Timer 182 9.5.3 Timers on the mbed 183 9.6 Using the mbed Timer 183 9.6.1 Using Multiple mbed Timers 184 9.6.2 Testing the Timer Duration 185 9.7 Using the mbed Timeout 187 9.7.1 A Simple Timeout Application 187 9.7.2 Further Use of Timeout 189 9.7.3 Timeout used to Test Reaction Time 190 9.8 Using the mbed Ticker 191 9.8.1 Using Ticker for a Metronome 192 9.8.2 Reflecting on Multi-Tasking in the Metronome Program 194 9.9 The Real Time Clock 195 9.10 Switch Debouncing 196 9.11 Mini-Projects 198 9.11.1 A Self-Contained Metronome 198 9.11.2 Accelerometer Threshold Interrupt 198 Chapter Review 199 Quiz 199 Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00009-X Copyright Ó 2012 Elsevier Ltd. All rights reserved. 169 170 Chapter 9 9.1 Time and Tasks in Embedded Systems 9.1.1 Timers and Interrupts The very first diagram in this book, Figure 1.1, shows the key features of an embedded system. Amongtheseistime. Embeddedsystemshavetorespondinatimely mannertoevents as they happen. Usually, this means they have to be able to do the following: • measure time durations • generate time-based events, which may be single or repetitive • respond with appropriate speed to external events, which may occur at unpredictable times. Indoingall of thesethesystemmayfindthatithasaconflictofinterest,withtwoactionsneeding attentionat thesametime. Forexample, anexternal event may demand attentionjust when aperiodic event needs to takeplace. Therefore, thesystemmay needto distinguishbetween events that haveahighlevel of urgency and thosethat do not, andtake actionaccordingly. It follows that we need a set of tools and techniques to allow effective time-based activity to occur. Key featuresof thistoolkitareinterruptsandtimers, thesubjectof thischapter. Inbrief, atimerisjustwhatitsnameimplies, adigital circuitthatallowsustomeasuretime, andhence make things happen when a certain time has elapsed. An interrupt is a mechanism whereby a running program can be interrupted, with the central processing unit (CPU) then being requiredto jumpto someotheractivity. Inourstudy of interrupts andtimers, wemakemajor stepsforwardinourunderstandingof howprogramscanbestructured, andhowwecanmove towards more sophisticated programdesign. That is where the third topic in the chapter title comes in e the concept of program tasks. 9.1.2 Tasks Inalmostall embeddedprograms,theprogramhastoundertakeanumberof differentactivities. Enteringbriefly theworldof small-scalefarming, considertherequirementsforatemperature controllerforamushroom-growingshed, workinginacoldenvironment. Thesefriendly little fungi growbestundertightly controlledconditionsof temperatureandhumidity. Theirgrowth goes throughseparate phases, at whichtime different preferred temperatures may apply. The systemwill need to control, display and log thetemperature, keep track of time, respond to changesinsettingby theuser, andcontrol theheaterandfan. Eachisafairly distinct activity, and each will requireablock of code. Inprogramming terminology wecall these distinct activities tasks. Our ability to partitionany programinto tasks becomes an important skill in moreadvancedprogramdesign. Onceaprogramhasmorethanonetask, weenterthedomain of multi-tasking. As tasks increasein number, the challengeof responding to theneeds of all tasks becomes greater, and many techniques aredeveloped to do this. Interrupts, Timers and Tasks 171 9.1.3 Event-Triggered and Time-Triggered Tasks Tasks performed by embedded systems tend to fall into two categories: event triggered and timetriggered. Tasks that areevent triggeredoccurwhenaparticularexternal event happens, atatimewhichisusually notpredictable. Tasksthataretimetriggeredhappenperiodically, at a time determined by the microcontroller. To continue with our example of the mushroom shed, Table9.1listssomepossibletasksandsuggestswhethereachisevent ortimetriggered. For those that are time triggered, it becomes necessary to indicate how frequently the tasks occur; suggestions for this are also shown. 9.2 Responding to Event-Triggered Events 9.2.1 Polling A simple example of an event-triggered activity is when a user pushes a button. This can happen at any time, without warning, but when it does the user expects a response. Oneway of programming for this is to continuously test that external input. This is illustrated in Figure9.1, whereaprogramisstructuredasacontinuousloop. Withinthis, itteststhestateof two input buttons, and responds to themif activated. This way of checking external events is called polling; the program ensures that it periodically checks input states and responds if thereisaneed. Thisisthesortof approachwehaveusedsofarinthisbook, wheneverneeded. It works well for simple systems; however, it is not adequate for more complex programs. Supposetheprogramof Figure9.1isextended, sothatamicrocontrollerhas20inputsignalsto testineachloop. Onmostloopiterations, theinputdatamay notevenchange, sowearerunning thepollingfornoapparentbenefit. Worse, theprogrammightspendtimecheckingthevalueof unimportantinputs, whilenotrecognizingvery quickly whenamajorfaultconditionhasarisen. There are two main problems with polling: • The processor cannot perform any other operations during a polling routine. • All inputsaretreatedasequal; theurgent changehastowaititsturnbeforeit isrecognized by the computer. Table 9.1: Example tasks: temperature controller for a mushroom shed Task Event or time triggered Measure temperature Time (every minute) Compute and implement heater and fan settings Time (every minute) Respond to user control Event Record and display temperature Time (every minute) Orderly switch to battery backup in case of power loss Event 172 Chapter 9 Respond to button 1 Y Is button 1 pressed? N Respond to button 2 Y Is button 2 pressed? N Do other things Figure 9.1: A simple program using polling A better solutionis for input changes to announce themselves; time is not wasted finding out that thereisno change. Thedifficulty liesinknowingwhentheinput valuehaschanged. This is the purpose of the interrupt system. 9.2.2 Introducing Interrupts The interrupt represents a radical alternative to the polling approach just described. With an interrupt, thehardwareisdesignedso that theexternal variablecanstoptheCPUinitstracks, anddemandattention. Supposeyoulivedinahouse, andwereworriedthatathief mightcome induringthenight. Youcouldarrangeanalarmclocktowakeyouupevery half hourto check there was no thief, but you would not get much sleep. In this case you would be polling the possible thief ‘event’. Alternatively, you could fit a burglar alarm. You would then sleep peacefully, unless the alarm went off, interrupted your sleep, and you would jump up and chase the burglar. In very simple terms, this is the basis of the computer interrupt. Interrupts have become a hugely important part of the structure of any microprocessor or microcontroller, allowing external events and devices to force a change in CPU activity. In early processors interrupts were mainly used to respond to really major external events; designs allowed for just one, or a small number of interrupt sources. The interrupt concept was, however, found to be so useful that more and more possible interrupt sources were introduced, sometimes for dealing with rather routine matters. In responding to interrupts, most microprocessors follow the general pattern of the flow diagramshown in Figure9.2. The CPU completes the current instructionit is executing. It is Interrupts, Timers and Tasks 173 Interrupt Detected main programis running Complete Current Instruction Save 'Context' on Stack, including Program Counter (PC) Find Interrupt Vector, and Reload PC Interrupt Service Routine (ISR) execution starts Continue Program Execution No End of ISR ? Yes Load Context, including PC, from Stack Continue Program Execution main programresumes Figure 9.2: A typical microprocessor interrupt response about to go off and find a completely different piece of code to execute, so it must save key informationabout what it has just beendoing; this is called thecontext. Thecontext includes at least the value of the Program Counter (this tells the CPU where it should come back to when the interrupt has completed) and generally a set of key registers, for example those holding current data values. All this is saved on a small block of memory local to the CPU, called the Stack. The CPU then runs a section of code called an Interrupt Service Routine (ISR); this has been specifically written to respond to the interrupt that has occurred. The address of the ISR is found through a memory location called the Interrupt Vector. On completing the ISR, the CPU returns to the point in the main code immediately after the interruptoccurred, findingthisby retrievingtheProgramCounterfromtheStack whereitleft it. Itthencontinuesprogramexecutionasif nothinghappened. Later, inSection9.4, weaddto this explanation, and set it more in the context of the mbed. 9.3 Simple Interrupts on the mbed Thembedapplicationprogramminginterface(API)exploitsonlyasmall subsetof theinterrupt capability of the LPC1768 microcontroller, mainly focusing on theexternal interrupts. Their 174 Chapter 9 useisveryflexible,asanyof pins5e30canbeusedasaninterruptinput,exceptingonlypins19 and 20. The availableAPI functions are shown in Table9.2. Usingthesewecan create an interrupt input, write thecorresponding ISR andlink the ISR withthe interrupt input. ProgramExample9.1isavery simpleinterruptprogram, adaptedfromthembedwebsite. Itis madeupof acontinuousloop, whichswitches onandoff LED4(labeledflash). Theinterrupt input is specifiedas pin5, andlabeledbutton. A tiny ISR is writtenforit, called ISR1, which isstructuredexactly asafunction. Theaddressof thisfunctionisattachedtotherisingedgeof the interrupt input, in the line button.rise(&ISR1); When the interrupt is activated, by this rising edge, the ISR executes, and LED1 is toggled. This can occur at any time in program execution. The program has effectively one timetriggered task, the switching of LED4, and one event-triggered task, the switching of LED1. /* Program Example 9.1: Simple interrupt example. External input causes interrupt, while led flashes */ #include "mbed.h" InterruptIn button(p5); //define and name the interrupt input DigitalOut led(LED1); DigitalOut flash(LED4); void ISR1() { led = !led; } int main() { button.rise(&ISR1); while(1) { flash = !flash; wait(0.25); } } //this is the response to interrupt, i.e. the ISR // attach the address of the ISR function to the // interrupt rising edge // continuous loop, ready to be interrupted Program Example 9.1 Introductory use of an interrupt Table 9.2: API interrupts summary Function Usage InterruptIn Create an InterruptIn connected to the specified pin rise Attach a function to call when a rising edge occurs on the input rise Attach amember function to call when arisingedgeoccurson theinput fall Attach a function to call when a falling edge occurs on the input fall Attach a member function to call when a falling edge occurs on the input mode Set the input pin mode Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller Interrupts, Timers and Tasks 175 Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 Figure 9.3: Circuit build for Program Example 9.1 Compile and run this program, applying the very simple build shown in Figure 9.3. Notice that when you push the button the interrupt is taken high, and LED1 changes state; LED4 meanwhile continues its flashing, almost unperturbed. The program depends on the internal pull-down resistor, which is enabled by default during setup. If you experience erratic behavior with this program, you may be experiencing switch bounce. In this case, fast forward to Section 9.10 for an introduction to this important topic. n Exercise 9.1 Change Program Example 9.1 so that: 1. The interrupt is triggered by a falling edge on the input. 2. Therearetwo ISRs, fromthesamepush-button input. Onetoggles LED1 on a rising interrupt edge, and the other toggles LED2 on a falling edge. n 9.4 Getting Deeper into Interrupts We can take our first generalized understanding of interrupts further, and try to understand a little morewhat goes on inside the mbed. It should be pointed out straight away that this is not essential as far as using the mbed API is concerned. In fact, although the LPC1768 176 Chapter 9 microcontroller, inside the mbed, has a very sophisticated interrupt structure, the mbed only uses a small part of this, and that only in a modest way. Therefore, go straight to the next section if you do not want to get into any deeper interrupt detail. Okay, so you’re still there! Let’s extend our ideas of interrupts. Whilewe said earlier that an interrupt was possibly like a thief coming in the night, imagine now a different scenario. Supposeyouareateacherof abigclassmadeupof enthusiastic butpoorly behavedkids; you have set them a task to do but they need your help. Tom calls you over, but while you are helping him Jane starts clamoring for attention. Do you: • tell Jane to be quiet and wait until you’ve finished with Tom? OR • tell Tom you’ll come back to him, and go over to sort Jane out? To makematters worse, yourschool principal has askedyouto let themembers of theschool band out of class half anhourearly, but youreally want themto finishtheirwork beforethey go. This influences the above decision. Suppose Jane is in the band, and Tom is not. Therefore, in this situation you decide you must leave Tom to help Jane. This school classroomsituation is reflected in almost any embedded system. There could be a number of interrupt sources, all possibly needing attention. Some will be of great importance, others much less. Therefore, most processors contain four important mechanisms: • Interrupts can be prioritized, in other words some are defined as more important than others. If two occur at the same time, then the higher priority one executes first. • Interruptscanbemasked, i.e. switchedoff, if they arenotneeded, orarelikely to get inthe way of moreimportant activity. This maskingcouldbejust forashort period, forexample while a critical program section completes. • Interrupts can be nested. This means that a higher priority interrupt can interrupt one of lower priority, just like the teacher leaving Tom to help Jane. Working with nested interrupts increases the demands on the programmer and is strictly for advanced players only. Not all processors permit nested interrupts, and some allow youto switchnesting on or off. • The location of the ISR in memory can be selected, to suit the memory map and programmer’s wishes. Let us take on just a couple more important interrupt concepts, these ones from the point of view of the interrupt source. Go to the moment in the above scenario when Jane suddenly realizes she needs help, and puts her hand up. Some short time later the teacher comes over. The delay between her putting up her hand and the teacher actually arriving is called the interrupt latency. Latency may be due to a number of things; in Interrupts, Timers and Tasks 177 this case the teacher has to notice Jane’s hand in the air, may need to finish with another pupil, and then has to walk over. Once the teacher arrives, Jane puts her hand down. While Jane is waiting with her hand in the air, patiently we hope, her interrupt is said to be pending. These concepts and capabilities hint at some of the deep magic that can be achieved with advanced interrupt structures. We can put all of this into more technical terms, and hence refine our understanding of interrupt action. This was first illustrated in the flow diagram of Figure 9.2. Further detail on part of this figure is now shown in Figure 9.4. The interrupt being asserted is like Jane putting up her hand. In a microprocessor, the interrupt input will be a logic signal; depending on its input configuration it may be active high or low, or triggered by a rising or falling edge. This input will cause an internal ‘flag’ to be set. This is normally just a single bit in a register, which records the fact that an interrupt has occurred. This does not necessarily mean that the interrupt automatically gets the attention it seeks. If it is not enabled (i.e. it is masked), then therewill be no response. The flag is left high, however, as the program may later enable that interrupt or the program may just poll the interrupt flag. Back to the flow diagram: if another ISR is already running then again the incoming interrupt may not get a response, at least not immediately. If it is higher priority and nested interrupts are allowed, then it will be allowed to run. If it is lower priority, it will have to wait for the other ISR to complete. The subsequent actions in the flow diagram, as already Interrupt Asserted Interrupt Flag is set Interrupt Detected This Interrupt is enabled? Complete Current Instruction No No immediate response, but flag stays set Yes Higher Priority Interrupt is Running? Yes No action till other ISR completes No Complete Current Instruction Figure 9.4: A typical microprocessor interrupt response e some greater detail 178 Chapter 9 seen in Figure 9.2, then follow. Note that the figure is potentially misleading, as it implies these actions happen in turn. To get low latency, they should happen as rapidly as possible; a good interrupt management system will allow some of the actions to take place in parallel. For example, the interrupt vector could be accessed while the current instruction is completing. 9.4.1 Interrupts on the LPC1768 Now let’s get back to microprocessor hardware. Recall that the mbed contains the LPC1768 microprocessor, andthat theLPC1768containstheARMCortex core. It isto theCortex core that wemust turnfirst, as it provides theinterrupt structureusedby themicrocontroller. Back in Figure2.3, wesaw the Cortex core, set withintheLPC1768 microprocessor. Management of all interrupts in the Cortex is undertaken by the formidable-sounding Nested Vectored Interrupt Controller (NVIC). You could think of this as managing the processes overviewed inFigures9.2and9.4. TheNVIC isalso abitlikeadigital electronic control box withalotof unconnectedwireshangingout. WhentheCortex isembeddedinto amicrocontroller, suchas the LPC1768, the chip designer assigns and configures those features (through the ‘loose wires’) of the NVIC that are needed for that application. For example, the Cortex allows for 240 possible interrupts, both external and from the peripherals, and 256 possible priority levels. The LPC1768, however, has ‘only’ 33 interrupt sources, with 32 possible programmable priority levels. 9.4.2 Testing Interrupt Latency Now that we have met the concept of interrupt latency, we can test it in the mbed. Program Example 9.2 adapts Program Example 9.1, but the interrupt is now generated by an external square wave, instead of an external button push. This makes it easier to see on an oscilloscope. When an interrupt occurs, the external LED is pulsed high for a fixed duration. /* Program Example 9.2: Tests interrupt latency. External input causes interrupt, which pulses external LED while LED4 flashes continuously. */ #include "mbed.h" InterruptIn squarewave(p5); DigitalOut led(p6); DigitalOut flash(LED4); void pulse() { led = 1; wait(0.01); led = 0; } int main() { //Connect input square wave here //ISR sets external led high for fixed duration Interrupts, Timers and Tasks 179 squarewave.rise(&pulse); while(1) { flash = !flash; wait(0.25); } // attach the address of the pulse function to // the rising edge // interrupt will occur within this endless loop } Program Example 9.2 Testing interrupt latency CreateanewprojectfromProgramExample9.2. Connectanexternal LED betweenpin6and ground, ensuring correct polarity. Connect to pin5 asignal generatorset to logic-compatible square wave output (probably labeled ‘TTL compatible’), running initially at around 10 Hz. Once connected, with the program running, the external LED should flash at this rate, i.e. around 10 times a second. n Exercise 9.2 Connect two inputs of an oscilloscope to the interrupt input, and the LED output, triggering from the interrupt. Increase the input frequency to around 50Hz. Set the oscilloscope time base to 5 ms per division. You should be able to see the rising edge of the interrupt input, and a few microseconds later the LED output rising. The time delay between the two is an indication of latency. The rise of the LED will be flickering a little, as the delay will depend on what the CPU is doing at the moment the interrupt occurs. It is important to note that the latency as measured here depends on both hardware and software factors. n 9.4.3 Disabling Interrupts Interrupts are an essential tool in embedded design. But because they can occur at any time, they can have unexpected or undesirable side effects. In some situations it is essential to disable (mask) the interrupt. These include when you are undertaking a time-sensitive activity, or a complex calculation that must be completed in one go. As any incoming interrupt will have left its flag set, it can be responded to once interrupts are enabled again. Of course, a delay in response has been introduced and the latency greatly compromised. You can simply disable interrupts, as shown here: __disable_irq(); //activity which can’t be interrupted __enable_irq(); //disable interrupts //enable interrupts Note that each line starts with two underscores. 180 Chapter 9 n Exercise 9.3 Using Program Example 9.2, disable the interrupt for the duration of the wait(0.25) delay. Connect the oscilloscope as in Exercise 9.2 and observe the output again. Comment on the outcome. Experiment with different values for this wait function. Try then splitting it into two waits, runningimmediatelyafter each other, with onehavinginterrupts disabled and the other enabled. n 9.4.4 Interrupts fromAnalog Inputs Asidefromdigital inputs, it isuseful to generateinterruptswhenanalogsignalschange, for exampleif ananalogtemperaturesensorexceeds acertainthreshold. Oneway to do thisisby applyingacomparator. A comparatorisjust that, it comparestwo input voltages. If oneinput is higherthantheotherthentheoutputswitchestoahighstate;ifitislower,theoutputswitcheslow.A comparatorcaneasily beconfiguredfromanoperational amplifier(opamp), asshownin Figure9.5. Here, aninput voltage, labeledVin, iscomparedto athresholdvoltagederivedfrom apotential divider, madefromthetwo resistorsR1 andR2. Theseareconnectedto thesupply voltage, labeledVsup. Fortheright choiceof opamporcomparator, andwithsuitablesupply voltages,theoutputisaLogic1whentheinputisabovethethresholdvalue,andLogic0otherwise. Thethresholdvoltagejustmentioned, labeledVe inthediagram, iscalculatedusingEquation9.1: V ¼VsupR2=ðR1 þ R2Þ 9.1 As an example, we might want to generate an interrupt from a temperature input, using an LM35temperaturesensor(Figure5.8), withtheinterrupttriggeredif thetemperatureexceeds 30 C. As we know, this sensor has an output of 10 mV/ C, which would lead to an output Vin 3 + 7 6 Vsup R1 V– 2 - 4 R2 Figure 9.5: A comparator circuit Vo (a logic value connected to an mbed input) Interrupts, Timers and Tasks 181 voltageof 300 mV at thetriggerpoint proposed. To set Ve to 300 mV inFigure9.5, weapply Equation 9.1, with a Vsup value of 3.3 V; we find that R1 ¼0.1R2. Values of R1 ¼10k, and R2 ¼1k could therefore be chosen. n Exercise 9.4 Unlike many op amps, the ICL7611 can be run from very low supply voltages, even the 3.3 V of the mbed. Using an LM35 IC temperature sensor, and an ICL7611 op amp connected as a comparator, design and build a circuit that causes an interrupt when the temperature exceeds 30 C. Write a program that lights an LED when the interrupt occurs. The pin connections shown in Figure 9.5 can be applied. Pin 7 is the positive supply, and can be connected to the mbed 3.3 V; pin 4 is the negative supply, and is connected to 0 V. For thisop amp, also connect pin 8to thepositivesupplyrail. (Thispin controls the output drive capability; check the datasheet for more information.) n 9.4.5 Conclusion on Interrupts This section has provided a good introduction to interrupts and the main concepts associated with them. They become an essential part of the toolkit of any embedded designer. We havesofarlimitedourselvestosingle-interruptexamples. Wheremultipleinterruptsareused, the design challenges become considerably greater e interrupts can have a very destructive effect if not used well. The design of advanced multiple interrupt programs is, however, beyond the scope of this book. 9.5 An Introduction to Timers A simpleprogram, forexamplethevery first ProgramExample2.1, uses wait( ) functions to performtimingoperations, forexampleto introduceadelay of 200 ms. This is easy andvery convenient, but during this delay loop the microcontroller cannot performany other activity; thetimespent waitingis just wastedtime. As wetry to writemoredemandingprograms, this simpletimingtechniquebecomes inadequate. Weneed away of letting timingactivity go on in the background, while the program continues to do useful things. We turn to the digital hardware for this. 9.5.1 The Digital Counter It is an easy task in digital electronics to make electronic counters; you simply connect togetheraseriesof bistablesorflip-flops. Eachoneholdsonebitof information, andall those bits together form a digital word. This is illustrated in very simple form in Figure 9.6, with 182 Chapter 9 We can preload Input an interrupt at the moment of overflow 0 0 1 0 1 0 0 1 We can read Figure 9.6: A simple 8-bit counter each little block representing one flip-flop, each holding one bit of the overall number. If the input of thisarrangementis connectedto aclock signal thenthecounterwill count, inbinary, thenumberof clockpulsesappliedtoit. Itiseasy toreadtheoverall digital numberheldinthe counter, and it is not difficult to arrange the necessary logic to preload it with a certain number, or to clear it to zero. Thenumberthat acountercancount upto isdeterminedby thenumberof bits inthecounter. In general, an n-bit counter can count from 0 to (2n 1). For example, an 8-bit counter can count from 0000 0000 to 1111 1111, or 0 to 255 in decimal. Similarly, a 16-bit counter can count from 0 to 65 535. If a counter reaches its maximum value, and the input clock pulses keeponcoming, thenitoverflowsbacktozero, andstartscountingupall overagain. All isnot lost if this happens e in fact we have to be ready to deal with it. Many microcontroller counters cause an interrupt as the counter overflows; this interrupt can be used to record the overflow, and the count can continue in a useful way. 9.5.2 Using the Counter as a Timer The input signal to a counter can be a series of pulses coming from an external source, for example counting people going through a door. Alternatively, it can be a fixed-frequency logic signal, suchas theclock sourcewithinamicrocontroller. Very importantly, if that clock source is a known and stable frequency, then the counter becomes a timer. As an example, if the clock frequency is 1.000 MHz (hence with period of 1 ms), then the count will update every microsecond. If thecounterisclearedto zero, andthenstartscounting, thevalueheldin the counter will give the elapsed time since the counting started, with a resolution of 1 ms. This can be used to measure time, or trigger an event when a certain time has elapsed. It can also beusedto control time-basedactivity, forexampleserial datacommunication, orapulse width modulation (PWM) stream. Interrupts, Timers and Tasks 183 Alternatively, if the counter is just free-running with a continuous clock signal, then the ‘interrupt on overflow’ occurs repeatedly. This becomes very useful where a periodic interrupt is needed. For example, if an 8-bit counter is clocked with a clock frequency of 1 MHz, it will reach its maximumvalue and overflow back to zero in 256ms (it is the 256th pulsethat causes theoverflowfrom255 to 0). If it is left runningcontinuously, thenthis train of interrupt pulses can be used to synchronize timed activity, for example it could define the baud rate of a serial communication link. Timers based on these principles are an incredibly important feature of any microcontroller. Indeed, most microcontrollers have many more than one timer, applied to a variety of different tasks. These include generating timing in PWM or serial links, measuring the duration of external events and producing other timed activity. 9.5.3 Timers on the mbed To findoutwhathardwaretimersthembedhas, weturnback to Figure2.3andReference2.4, the LPC1768 usermanual. We find that themicrocontrollerhas fourgeneral-purposetimers, aRepetitiveInterrupt Timer andaSystemTickTimer. All are basedon theprinciples just described. The mbed makes useof these inthree distinct applications, described inthe followingsections. ThesearetheTimer, usedforsimpletimingapplications, Timeout, which calls afunctionafterapredetermined delay, and Ticker, whichrepeatedly calls afunctionat apredeterminedrate. ItalsoappliesaReal TimeClocktokeeptrackof timeof day andthedate. 9.6 Using the mbed Timer The mbed Timer allows basic timing activities to take place, for comparatively short durations. A Timercanbecreated, started, stoppedandread. Thereis no limit onthenumber of Timersthatcanbesetup. TheAPI summary isshowninTable9.3. Thembedsitenotesthat Table 9.3: API summary for Timer Function Usage start Start the timer stop Stop the timer reset Reset the timer to 0 read Get the time passed in seconds read_ms Get the time passed in milliseconds read_us Get the time passed in microseconds 184 Chapter 9 the Timer is based on the 32-bit counters, and can time up to a maximum of (231 1) microseconds, i.e. something over 30 minutes. Based on the theory above, one might expect theTimerto countupto (232 1). However, onebitisreservedintheAPI objectasasignbit, so only 31 bits are available for counting. Program Example 9.3 gives a simple but interesting timing example, and is taken from the mbed site. It measures the time taken to write a message to the screen, and displays that message. Compile and run the program, with Tera Term activated (Appendix E). Then carry out Exercise 9.5 to make some further measurements and calculations. /* Program Example 9.3: A simple Timer example, from mbed website. Activate Tera Term terminal to test. */ #include "mbed.h" Timer t; Serial pc(USBTX, USBRX); // define Timer with name “t” int main() { t.start(); //start the timer pc.printf("Hello World!\n"); t.stop(); //stop the timer pc.printf("The time taken was %f seconds\n", t.read()); //print to pc } Program Example 9.3 A simple Timer application n Exercise 9.5 Run Program Example 9.3, and note from the computer screen readout the time taken for themessageto bewritten. Then writesomeother messages, of differinglengths, and record in each case the number of characters and the time taken. Can you relate the times taken to the baud rate used? Can you make any other deductions? If necessary, check Section 7.9 to recall someof thetiming issues relating to theasynchronous serial data link used. n 9.6.1 Using Multiple mbed Timers We are now going to apply the Timer in a different way, to run one function at one rate and anotherfunctionat anotherrate. Two LEDs will beusedto show this; you will quickly realize that theprincipleis powerful, and can beextended to more tasks and moreactivities. Program Example 9.4 shows the program listing. The program creates two Timers, named timer_fast and timer_slow. The main program starts these running, and tests when each exceeds a certain number. When the time value is exceeded, a function is called, which flips the associated LED. Interrupts, Timers and Tasks 185 /*Program Example 9.4: Program which runs two time-based tasks */ #include "mbed.h" Timer timer_fast; // define Timer with name "timer_fast" Timer timer_slow; // define Timer with name "timer_slow" DigitalOut ledA(LED1); DigitalOut ledB(LED4); void task_fast(void); void task_slow(void); int main() { timer_fast.start(); timer_slow.start(); while (1){ if (timer_fast.read()>0.2){ task_fast(); timer_fast.reset(); } if (timer_slow.read()>1){ task_slow(); timer_slow.reset(); } } } //function prototypes //start the Timers //test Timer value //call the task if trigger time is reached //and reset the Timer //test Timer value void task_fast(void){ ledA = !ledA; } //”Fast” Task void task_slow(void){ ledB = !ledB; } //”Slow” Task Program Example 9.4 Running two timed tasks CreateaprojectaroundProgramExample9.4, andrunitonthembedalone. Checkthetiming with a stopwatch or an oscilloscope. n Exercise 9.6 Experiment with different repetition ratesin ProgramExample9.4, includingonesthat are not multiplesofeachother. Addathirdandthenafourthtimertoit, flashingall mbedLEDs at different rates. n 9.6.2 Testing the Timer Duration Wequotedabovethemaximumvaluethat theTimercanreach. Aswithmany microcontroller features, it is very important to understand the operating limits and to be certain to remain within them. Program Example 9.5 measures the Timer limit in a simple way. It clears the Timerandthensetsitrunning, displayingatimeupdateto theTeraTermscreenevery second. 186 Chapter 9 Indoingthisitkeepsitsownrecordof secondselapsedandcomparesthiswiththeelapsedtime valuegivenby theTimer. Fromtheprogramstructureweexpect theTimervaluealways to be just ahead of the recorded time value. At some point, however, the Timer overflows back to zero andthis conditionis no longersatisfied. Theprogramdetectsthis andsends amessageto the screen. The highest value reached by the Timer is recorded on the screen. /* Program Example 9.5: Tests Timer duration, displaying current time values to terminal */ #include "mbed.h" Timer t; float s=0; float m=0; DigitalOut diag (LED1); Serial pc(USBTX, USBRX); //seconds cumulative count //minutes cumulative count int main() { pc.printf("\r\nTimer Duration Test\n\r"); pc.printf("-------------------\n\n\r"); t.reset(); //reset Timer t.start(); // start Timer while(1){ if (t.read()>=(s+1)){ //has Timer passed next whole second? diag = 1; //If yes, flash LED and print a message wait (0.05); diag = 0; s++ ; //print the number of seconds exceeding whole minutes pc.printf("%1.0f seconds\r\n",(s-60*(m-1))); } if (t.read()>=60*m){ printf("%1.0f minutes \n\r",m); m++ ; } if (t.read()<s){ //test for overflow pc.printf("\r\nTimer has overflowed!\n\r"); for(;;){} //lock into an endless loop doing nothing } } //end of while } Program Example 9.5 Testing Timer duration n Exercise 9.7 Create a project around Program Example 9.5 and run it on an mbed, enabling also a connection to Tera Term (see AppendixE). No further hardware is needed. Calculate precisely the time duration you expect from the Timer, i.e. (231 1) microseconds. You can leavetheprogramrunning whiledoing other things. Comeback, however, just after half an hour, and watch intently to see whether it overflows! Do your predicted and measured times agree? n Interrupts, Timers and Tasks 187 In some embedded programs there comes a moment when we just want the programto stop; thereissimply nothingmoreforit to do. ProgramExample9.3is onesuch. Yet wehaveno instructionavailableto us that just says stop; theCPU is designed to go on and on running until it is switched off. Notice at the end of this program examplehowthestopis implemented, by trapping programexecutioninanendless loopthat does nothing. C code feature 9.7 Using the mbed Timeout Program Example 9.4 showed the mbed Timer being used to trigger time-based events in an effective way. However, we needed to poll the Timer value to know when the event should be triggered. The Timeout allows an event to be triggered by an interrupt, with no polling needed. Timeout sets up an interrupt to call a function after a specified delay. There is no limit on the number of Timeouts created. The API summary is shown in Table 9.4. 9.7.1 A Simple Timeout Application A simple first example of Timeout is shown in Program Example 9.6. This causes an action to be triggered a fixed period after an external event. This simple program is made up of the main( ) function and a blink( ) function. A Timeout is created, named Response, along with some familiar digital input and output. Looking in the main( ) function, we see an if declaration, which tests if the button is pressed. If it is, the blink( ) function gets attached to the Response Timeout. We can expect that two seconds after this attachment is made, the blink( ) function will be called. To aid in the diagnostics, the button also switches on LED3. As a continuous task, the state of LED1 is reversed every 0.2 s. This program is thus a microcosm of many embedded systems programs. A timetriggered task needs to keep going, while an event-triggered task needs to take place at unpredictable times. Table 9.4: API summary for Timeout Function Usage attach Attach a function to be called by the Timeout, specifying the delay in seconds attach Attach a member function to be called by the Timeout, specifying the delay in seconds attach_us Attach a function to be called by the Timeout, specifying the delay in microseconds attach_us Attach amember function to becalled bytheTimeout, specifyingthedelayin microseconds detach Detach the function 188 Chapter 9 /*Program Example 9.6: Demonstrates Timeout, by triggering an event a fixed duration after a button press. */ #include "mbed.h" Timeout Response; //create a Timeout, and name it "Response" DigitalIn button (p5); DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); void blink() { led2 = 1; wait(0.5); led2=0; } //this function is called at the end of the Timeout int main() { while(1) { if(button==1){ Response.attach(&blink,2.0); // attach blink function to Response Timeout, //to occur after 2 seconds led3=1; //shows button has been pressed } else { led3=0; } led1=!led1; wait(0.2); } } Program Example 9.6 Simple Timeout application Compile Program Example 9.6 and download to an mbed, with the build of Figure 9.3. Observe the response as the push-button is pressed. n Exercise 9.8 With Program Example 9.6 running, answer the following questions: 1. Is the2s Timeout timed fromwhen thebutton is pressed or when it is released? Why is this? 2. When theevent-triggered task occurs(i.e. theblinkingof LED2), what impact doesit have on the time-triggered task (i.e. the flashing of LED1)? 3. If you tap the button very quickly, you will see that it is possible for the program to miss it entirely (even though electrically we can prove that the button has been pressed). Why is this? n Interrupts, Timers and Tasks 189 9.7.2 Further Use of Timeout Program Example 9.6 has demonstrated use of the Timeout nicely, but the questions in Exercise 9.8 throw up some of the classic problems of task timing, notably that execution of the event-triggered task can interfere with the timing of the time-triggered task. ProgramExample9.7doesthesamethingasthepreviousexample, but inamuchbetterway. Glancingthroughit, weseetwo Timeoutscreated, andaninterrupt. Thelatterconnectsto the push-button, and replaces the digital input which previously took that role. There are now three functions, in addition to main( ). This has become extremely short and simple, and is concerned primarily with keeping the time-triggered task going. Now response to the pushbutton is by interrupt, and it is within the interrupt function that the first Timeout is set up. Whenitisspent, theblink( ) functioniscalled. ThissetstheLED output, butthenenablesthe second Timeout, which will trigger the end of the LED blink. /*Program Example 9.7: Demonstrates the use of Timeout and interrupts, to allow response to an event-driven task while a time-driven task continues. */ #include "mbed.h" void blink_end (void); void blink (void); void ISR1 (void); DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); Timeout Response; //create a Timeout, and name it Response Timeout Response_duration; //create a Timeout, and name it Response_duration InterruptIn button(p5); //create an interrupt input, named button void blink() { //This function is called when Timeout is complete led2=1; // set the duration of the led blink, with another timeout, duration 0.1 s Response_duration.attach(&blink_end, 1); } void blink_end() { led2=0; } //A function called at the end of Timeout Response_duration void ISR1(){ led3=1; //shows button is pressed; diagnostic and not central to program //attach blink1 function to Response Timeout, to occur after 2 seconds Response.attach(&blink, 2.0); } int main() { button.rise(&ISR1); while(1) { led3=0; led1=!led1; wait(0.2); } } //attach the address of ISR1 function to the rising edge //clear LED3 190 Chapter 9 Program Example 9.7 Improved use of Timeout Compile and run the code of Program Example 9.7, again using the build of Figure 9.3. n Exercise 9.9 Repeat all thequestionsof Exercise9.8 for themost recent programexample, notingand explaining the differences you find. n 9.7.3 Timeout used to Test Reaction Time ProgramExample9.8 shows aninterestingrecreational applicationof Timeout, in whichthetimeout durationis itself avariable. It tests reactiontimeby blinkingan LED, andtiminghowlongit takes fortheplayerto hit aswitchinresponse. To add challenge, a‘random’ delay is generatedbeforetheLED is lit. This uses theC library function rand( ). Theprogramshouldbeunderstandablefromthecomments it contains. C code feature The circuit build is the same as seen in Figure 9.3. Now the push-button is the switch the player must hit to show a reaction. A Tera Term terminal should be enabled. /*Program Example 9.8: Tests reaction time, and demos use of Timer and Timeout functions */ #include "mbed.h" #include <stdio.h> #include <stdlib.h> //contains rand() function void measure (); Serial pc(USBTX, USBRX); DigitalOut led1(LED1); DigitalOut led4(LED4); DigitalIn responseinput(p5); //the player hits the switch connected here to respond Timer t; //used to measure the response time Timeout action; //the Timeout used to initiate the response speed test int main (){ pc.printf("Reaction Time Test\n\r"); pc.printf("------------------\n\r"); while (1) { int r_delay; //this will be the “random” delay before the led is blinked pc.printf("New Test\n\r"); led4=1; //warn that test will start wait(0.2); led4=0; r_delay = rand() % 10 + 1; // generates a pseudorandom number range 1-10 pc.printf("random number is %i\n\r", r_delay); // allows test randomness; //removed for normal play action.attach(&measure,r_delay); // set up Timeout to call measure() // after random time wait(10); //test will start within this time, and we then return to it Interrupts, Timers and Tasks 191 } } void measure (){ // called when the led blinks, and measures response time if (responseinput ==1){ //detect cheating! pc.printf("Don’t hold button down!"); } else{ t.start(); //start the timer led1=1; //blink the led wait(0.05); led1=0; while (responseinput==0) { //wait here for response } t.stop(); //stop the timer once response detected pc.printf("Your reaction time was %f seconds\n\r", t.read()); t.reset(); } } Program Example 9.8 Reaction time test: applying Timer and Timeout n Exercise 9.10 Run Program Example 9.8 for a period of time and note the sequence of ‘random’ numbers. Run it again. Do you recognizea pattern in thesequenceof ‘random’ numbers? In fact, it is difficult for a computer to generate true random numbers, although various tricks and algorithms are used to create pseudorandomsequences of numbers. n 9.8 Using the mbed Ticker The mbed Ticker feature sets up a recurring interrupt, which can be used to call a function periodically, at aratedecidedby theprogrammer. Thereis no limit onthenumberof Tickers created. The API summary is shown in Table 9.5. Table 9.5: API summary for Ticker Function Usage attach Attach a function to be called by the Ticker, specifying the interval in seconds attach Attach a member function to be called by the Ticker, specifying the interval in seconds attach_us Attach a function to be called by the Ticker, specifying the interval in microseconds attach_us Attach amember function to becalled bytheTicker, specifyingtheinterval in microseconds detach Detach the function 192 Chapter 9 WecandemonstrateTickerby returningto thevery firstprogramexampleinthisbook, number 2.1. This simply flashes anLED every 200ms. Creatingaperiodic event is oneof themost natural andcommonrequirementsinanembeddedsystem, soitisnotsurprisingthatitappeared inourfirstprogram. Wecreatedthe200msperiodby usingadelay function; theseareuseful in alimitedway, but whenthey arerunningthey tieuptheCPU, so that it cando nothingelse productive. Program Example 9.9 simply replaces the Delay functions with the Ticker. /* Program Example 9.9: Simple demo of "Ticker". Replicates behavior of first led flashing program. */ #include "mbed.h" void led_switch(void); Ticker time_up; //define a Ticker, with name “time_up” DigitalOut myled(LED1); void led_switch(){ myled=!myled; } //the function that Ticker will call int main(){ time_up.attach(&led_switch, 0.2); //initializes the ticker while(1){ //sit in a loop doing nothing, waiting for Ticker interrupt } } Program Example 9.9 Applying Ticker to our very first program Itshouldbeeasy tofollowwhatisgoingoninthisprogram. Themajorstepforwardisthatthe CPUisnowfreedto do anythingthatisneeded, whilethetask of measuringthetimebetween LED changes is handed over to the Timer hardware, running in the background. We have already called functions periodically with the Timer feature, so at first Ticker does not seem to add anything really new. Remember, however, that we have to poll the Timer value in Program Example 9.4 to test its value, and instigate the related function. Using Ticker, it is an interrupt that calls the associated function when time is up. As already discussed, this is a more effective approach to programming. 9.8.1 Using Ticker for a Metronome ProgramExample9.10uses thembedto createametronome, usingtheTickerfacility. If you have not met one before, a metronome is an aid to musicians, setting a steady beat, against which they can play their music. The musician generally selects a beat rate in the range 40e208 beats per second. Old metronomes were based on elegant clockwork mechanisms, with a swinging pendulum arm. Most are made these days electronically. Normally the indicationgiven to the musicianis aloud audible‘tick’, sometimes accompanied by anLED flash. Here we just restrict ourselves to the LED. Interrupts, Timers and Tasks 193 The main program while loop checks the up and down buttons, adjusts the beat rate accordingly, anddisplaysthecurrentratetoscreen. Thisloopscontinuously, butlurkinginthe background is the Ticker. This has been initialized before the while loop, in the line beat_rate.attach(&beat, period); //initializes the beat rate Oncethetimeindicatedby period haselapsed, thebeat functioniscalled. Atthismomentthe Ticker is updated, possibly with a new value of period, and the LED is flashed to indicate a beat. Program execution then returns to the main while loop, until the next Ticker occurrence. /*Program Example 9.10: Metronome. Uses Ticker to set beat rate */ #include "mbed.h" #include <stdio.h> Serial pc(USBTX, USBRX); DigitalIn up_button(p5); DigitalIn down_button(p6); DigitalOut redled(p19); //displays the metronome beat Ticker beat_rate; //define a Ticker, with name “beat_rate” void beat(void); float period (0.5); //metronome period in seconds, initial value 0.5 int rate (120); //metronome rate, initial value 120 int main() { pc.printf("\r\n"); pc.printf("mbed metronome!\r\n"); pc.printf("_______________\r\n"); period = 1; redled = 1; //diagnostic wait(.1); redled = 0; beat_rate.attach(&beat, period); //initializes the beat rate //main loop checks buttons, updates rates and displays while(1){ if (up_button = =1) //increase rate by 4 rate = rate + 4; if (down_button = =1) //decrease rate by 4 rate = rate - 4; if (rate > 208) //limit the maximum beat rate to 208 rate = 208; if (rate < 40) //limit the minimum beat rate to 40 rate = 40; period = 60/rate; //calculate the beat period pc.printf("metronome rate is %i\r", rate); //pc.printf("metronome period is %f\r\n", period); //optional check wait (0.5); } } void beat() { //this is the metronome beat beat_rate.attach(&beat, period); //update beat rate at this moment 194 Chapter 9 redled = 1; wait(.1); redled = 0; } Program Example 9.10 Metronome, applying Ticker The hardware build for the metronome is simple, and is shown in Figure 9.7. The Tera Term terminal should be enabled. Build the hardware, and compile and download the program. With a stopwatch or another timepiece check that the beat rates are accurate. n Exercise 9.11 Wehaveleft a bit of polling in ProgramExample9.10. Rewriteit so that responseto the external pins is done with interrupts. n 9.8.2 Reflecting on Multi-Tasking in the Metronome Program “up” “down” Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller Having picked up the idea of program tasks at the beginning of this chapter, we have seen a sequence of program examples that could be described as multi-tasking. This started with Figure 9.7: Metronome build Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 Interrupts, Timers and Tasks 195 ProgramExample 9.1, which runs one time-triggered and one event-triggered task. Many of the subsequent programs have clear multi-tasking features. In the metronome example, the program has to keep a regular beat going. While doing this, it must also respond to inputs from the user, calculate beat rates and write to the display. There is, therefore, one time-triggered task, the beat, and at least one event-triggered task, the userinput. Sometimes itisdifficulttodecidewhichprogramactivitiesbelongtogetherinonetask. Inthemetronome example the user response seems to contain several activities, but they all relate closely to each other, so it is sensible to view them as the same task. We have developed here a useful program structure, whereby time-triggered tasks can be linked to a Timer or Ticker function, and event-triggered tasks to an external interrupt. This will be useful as long as there are not too many tasks, and as long as they are not too demanding of CPU time. When that happens, we will need to look at more sophisticated solutions, either with a real-time operating systemor with a multi-processor hardware. Both of these are beyond the scope of this book, but topics to look out for as your knowledge and confidence increase. 9.9 The Real Time Clock The Real Time Clock (RTC) is an ultra-low-power peripheral on the LPC1768, which is implemented by the mbed. The RTC is a timing/counting system that maintains a calendar and time-of-day clock, with registers for seconds, minutes, hours, day, month, year, day of monthandday of year. It canalso generateanalarmforaspecific dateandtime. It runs from its own 32 kHz crystal oscillator, and can have its own independent battery power supply. It can thus be powered, and continue in operation, even if the rest of the microcontroller is powereddown. ThembedAPI doesnotcreateany Cþ þ objects, butjustimplementsstandard functions fromthestandardC library, as shownin Table9.6. Simpleexamples forusecanbe found on the mbed website. Table 9.6: API summary for Real Time Clock Function Usage Time Get the current time set_time Set the current time mktime Converts a tm structure to a timestamp localtime Converts a timestamp to a tm structure ctime Converts a timestamp to a human-readable string strftime Converts a tm structure to a custom format human-readable string 196 Chapter 9 Ideal switch response Actual switch response Figure 9.8: Demonstrating switch bounce 9.10 Switch Debouncing With the introduction of interrupts, we now have some choices to make when writing a program to a particular design specification. For example, Program Example 3.3 uses a digital input to determine which of two LEDs to flash. The digital input value is continuously polled within an infinite loop. However, we could equally have designed this programwithanevent-drivenapproach, to flipacontrol variableevery timethedigital input changes. Importantly, there are some inherent timing constraints within Program Example 3.3 which have not previously been discussed. One is that the frequency of polling is actually quite slow, because once the switch input has been tested a 0.4 s flash sequence is activated. This means that the system has a response time of at worst 0.4 s, because it only tests the switch input once for every program loop. When the switch changes position it could take up to 0.4s for the LED to change, which is very slow in terms of embedded systems. Interrupt-driven systems can have much quicker response rates to switch presses, because theresponseto thedigital inputcantakeplacewhileothertasksarerunning. However, when a system can respond very rapidly to a switch change, a new issue arises which needs addressing, called switch bounce. This is due to the fact that the mechanical contacts of a switch literally bounce together as the switch closes. This can cause a digital input to swing wildly between Logic 0 and Logic 1 for a short time after a switch closes, as illustrated in Figure 9.8. The solution to switch bounce is a technique called switch debouncing. First, the problem with switch bounce can be identified by evaluating a simple eventdriven program. Program Example 9.11 attaches a function to a digital interrupt on pin 5, so the circuit build shown in Figure 9.3 can again be used. The function simply toggles (flips) the state of the mbed’s onboard LED1 for every raising edge on pin 18. Interrupts, Timers and Tasks 197 /* Program Example 9.11: Toggles LED1 every time p18 goes high. Uses hardware build shown in Figure 9.3. */ #include "mbed.h" InterruptIn button(p5); // Interrupt on digital pushbutton input p18 DigitalOut led1(LED1); // mbed LED1 void toggle(void); // function prototype int main() { button.rise(&toggle); } // attach the address of the toggle // function to the rising edge void toggle() { led1=!led1; } Program Example 9.11 Toggles LED1 every time mbed pin 5 goes high Implement program18 with a push-button or SPDT (single-pole, double-throw) type switch onpin18. Dependingalittleonthetypeof switchyouuse, youwill seethattheprogramdoes not work very well. It can become unresponsive or the button presses can become out of synch with the LED. This demonstrates the problem with switch bounce. From Figure 9.8 it is easy to see how a single button press or change of switch position can causemultipleinterruptsandhencetheLED canget out of synchwiththebutton. Theswitch can be ‘debounced’ with a timer feature. The debounce feature needs to ensure that once the raising edge has been seen, no further raising edge interrupts should be implemented until a calibrated time period has elapsed. In reality, some switches move positions more cleanly than others, so the exact timing required needs some tuning. To assist, switch manufacturers often provide dataon switch bounce duration. The downside to including debouncing of this type is that the implemented timing period also reduces the response of the switch, although not as much as that discussed with reference to polling. Switch debouncing can be implemented in a number of ways. In hardware, there are little configurations of logic gates that can be used (see Reference 5.1). In software, timers, bespokecounters orother programmingmethods can beused. ProgramExample9.12 solves the switch bounce issue by starting a timer on a switch event and ensuring that 10ms has elapsed before allowing a second event to be processed. /* Program Example 9.12: Event driven LED switching with switch debounce */ #include "mbed.h" InterruptIn button(p18); // Interrupt on digital pushbutton input p18 DigitalOut led1(LED1); // digital out to LED1 Timer debounce; // define debounce timer void toggle(void); // function prototype int main() { debounce.start(); button.rise(&toggle); // attach the address of the toggle 198 Chapter 9 } void toggle() { if (debounce.read_ms()>10) led1=!led1; debounce.reset(); } // function to the rising edge // only allow toggle if debounce timer // has passed 10 ms // restart timer when the toggle is performed Program Example 9.12 Event-driven LED switching with switch debounce n Exercise 9.12 1. Experiment with modifying thedebouncetimeto beshorter or greater values. There comes a point wherethetimer does not effectively solvethedebouncing, and at the other end of thescaleresponsiveness can bereduced too. What is thebest debounce time for the switch you are using? 2. Implement Program Example 9.12 using an mbed Timeout object instead of the Timer object. Are there any advantages or disadvantages to each approach? 3. Rewrite Program Example 3.3 to do the same thing but with an event-driven approach (i.e. using interrupts). How much improvement can be made to the system’s responsiveness to switch changes? n 9.11 Mini-Projects 9.11.1 A Self-Contained Metronome The metronome described in Section 9.8.1 is interesting, but it does not result in something thatamusicianwouldreally wantto use. So try revisingtheprogram, anditsassociatedbuild, to make aself-contained battery-powered unit, using an LCD instead of the computer screen to display beat rate. Experiment also withgettingaloudspeakerto ‘tick’ alongwiththeLED. If you succeed in this, then try including the facility to play ‘concert A’ (440 Hz), or another pitch, to allow the musicians to tune their instruments. 9.11.2 Accelerometer Threshold Interrupt WemettheADXL345accelerometer,withitsSPIserial interface,inSection7.3.Althoughwedidnot usethematthetime, itisinterestingto notethatthedevicehastwo interruptoutputs, asseenin Figure7.6. Thesecanbeconnectedto anmbeddigital inputto runaninterruptroutinewheneveran accelerationthresholdisexceeded.Forexample,theaccelerometermightbeacrashdetectionsensorin avehiclewhich, whenaspecifiedaccelerationvalueisexceeded, activatesanairbag. Use an accelerometer on a cantilever armto provide the acceleration data. Figure 9.9 shows thegeneral construction. A plastic 30 cmor1foot ruler, clampedatoneendto atable, canbe Interrupts, Timers and Tasks 199 Accelerometer SPI wires to mbed Cantilever beam held or fixed at one end Figure 9.9: Cantilever beam held or fixed one end used. Set the accelerometer to generate an interrupt whenever a threshold in the z-axis is exceeded. Connect this as an interrupt input to the mbed, and program it so a warning LED lightsforonesecondwheneverthethresholdisexceeded. Youcanexperimentwiththeactual threshold value to alter the sensitivity of the detection system. Chapter Review • Signal inputs can be repeatedly tested in a loop, a process known as polling. • An interrupt allows an external signal to interrupt the action of the CPU, and start code execution from somewhere else in the program. • Interrupts are a powerful addition to the structure of the microprocessor. Generally, multiple interrupt inputs are possible, which adds considerably to the complexity of both hardware and software. • It is easy to make a digital counter circuit, which counts the number of logic pulses presented at its input. Such a counter can be integrated into a microcontroller structure. • Given a clock signal of known and reliable frequency, a counter can readily be used as a timer. • Timers can be structured in different ways so that interrupts can be generated from their output, for example to give a continuous sequence of interrupt pulses. • Switchdebounceis required inmany cases to avoidmultipleresponses being triggeredby a single switch press. Quiz 1. Explainthedifferencesbetweenusingpollingandevent-driventechniques fortestingthe state of one of the digital input pins on a microcontroller. 2. List the most significant actions that a CPU takes when it responds to an enabled interrupt. 200 Chapter 9 3. Explain the following terms with respect to interrupts: (a) priority (b) latency (c) nesting. 4. A comparator circuit and LM35 are to be used to create an interrupt source, using the circuit of Figure 9.5. The comparator is supplied from 5.0 V and the temperature threshold is to be approximately 38 C. Suggest values for R1 and R2. Resistor values of 470, 680, 820, 1k, 1k2, 1k5 and 10k are available. 5. Describe in overview how a timer circuit can be implemented in hardware as part of a microprocessor’s architecture. 6. What is the maximum value, in decimal, that a 12-bit and a 24-bit counter can count up to? 7. A 4.0 MHz clock signal is connected to the inputs of a 12-bit and a 16-bit counter. Each startscountingfromzero. Howlongdoesit takebeforeeachreachesitsmaximumvalue? 8. A 10-bit counter, clocked with an input frequency of 512 kHz, runs continuously. Every timeitoverflows, itgeneratesaninterrupt. Whatisthefrequency of thatinterruptstream? 9. Whatisthepurposeof thembed’sReal TimeClock? Giveanexampleof whenitmightbe used. 10. Describetheissueof switchbounceandexplainhowtimerscanbeusedto overcomethis. CHAPTER 10 Memory and Data Management Chapter Outline 10.1 A Memory Review 201 10.1.1 Memory Function Types 201 10.1.2 Essential Electronic Memory Types 202 10.2 Using Data Files with the mbed 205 10.2.1 Reviewing some Useful C/C++Library Functions 205 10.2.2 Defining the mbed Local File System 205 10.2.3 Opening and Closing Files 206 10.2.4 Writing and Reading File Data 206 10.3 Example mbed Data File Access 207 10.3.1 File Access 207 10.3.2 String File Access 208 10.3.3 Using Formatted Data 209 10.4 Using External Memory with the mbed 210 10.5 Introducing Pointers 212 10.6 Mini-Project: Accelerometer Data Logging on Exceeding Threshold 214 Chapter Review 215 Quiz 216 References 216 10.1 A Memory Review 10.1.1 Memory Function Types Broadly speaking, amicroprocessorneeds memory for two reasons: to hold its program, and to hold the data that it is working with; these are often called programmemory and data memory. To meet these needs a number of different semiconductor memory technologies is available, which can be embedded on the microcontroller chip. Memory technology is divided broadly into two types: volatile and non-volatile. Non-volatile memory retains its data when power is removed, but tends to be more complex to write to in the first place. For historical reasons it is still often called ROM (read only memory). Non-volatile memory is generally Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00010-6 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 201 202 Chapter 10 requiredforprogrammemory, so thattheprogramdataisthereandready whentheprocessor is poweredup. Volatilememory loses all datawhenpoweris removed, but is easy to writeto. Volatile memory is traditionally used for data memory; it is essential to be able to write to memory easily, and there is little expectation for data to be retained when the product is switchedoff. Forhistorical reasonsitisoftencalledRAM(randomaccessmemory), although this terminology tells us little that is useful. These categorizations of memory, however, give an over-simplified picture. It can be useful to change the contents of program memory, and there are times when we want to save data long term. Moreover, new memory technologies now provide non-volatile memory that is easy to write to. 10.1.2 Essential Electronic Memory Types Inany electronic memory wewant to beableto storeall the1s and0s that makeupourdata. There are several ways that this can be done, and a few essential ones are outlined here. A simpleone-bit memory isacoin. It isstableintwo positions, witheither‘heads’ facingup, or ‘tails’. We can try to balance the coin on its edge, but it would pretty soon fall over. The coin is stable in two states, and we call this bistable. It could be said that ‘heads’ represents Logic 1 and ‘tails’ Logic 0. With eight coins, an8-bit number can be represented and stored. If we had 10 million coins, we could store the data that makes up one photograph of good resolution, but that would take up a lot of space indeed! Therearevariouselectronic alternativesto thecoin, whichtakeupmuchlessspace. Oneisto use an electronic bistable (or ‘flip-flop’) circuit, as shown in Figure 10.1. The two circuits of (a) acoin (b) two transistors and two resistors (c) VCC Figure 10.1: Three ways of implementing a one-bit memory unit two NAND gates Memory and Data Management 203 Figure10.1bandc arestableinonly two states, andeachcanbeusedto storeonebit of data. Circuits like these have been the bedrock of volatile memory. Looking at the bigger picture, there are several different types of volatile and non-volatile memory, as shown in Figure 10.2 and described in some detail in References 1.1 and 10.1. Static randomaccess memory (SRAM) consists of avast array of memory cells based on the circuit of Figure 10.1b. These have to be addressable, so that just the right group of cells is writtento, orreadfrom, atany onetime. Tomakethispossible, twoextratransistorsareadded to the two outputs. To reduce the power consumption, the two resistors are usually replaced by two transistors also. That means six transistors per memory cell. Each transistor takes up a certain area on the integrated circuit (IC), so when the circuit is replicated thousands or millions of times, it can be seen that this memory technology is not actually very space efficient. Despite that, it is of great importance; it is low power, can be written to and read fromwithease, canbeembeddedontoamicrocontroller, andhenceformsthestandardway of implementing data memory in most embedded systems. All data is lost when power is removed. Dynamic random access memory (DRAM) is intended to do the same thing as SRAM with a reduced silicon area. Instead of using a number of transistors, one bit of information is storedinatiny capacitor, likeasmall rechargeablebattery. Suchcapacitors canbefabricated in large numbers on an IC. In order to select the capacitor for reading or writing, a simple transistor switch is required. Unfortunately, owing to the small capacitors and leakage currents on the chip, the memory loses its charge over a short period of time (around 10 to 100ms). So the DRAM needs to be accessed every few milliseconds to refresh the charges, otherwisetheinformationislost. DRAMhasaboutfourtimeslargerstoragecapacity than SRAM at about the same cost and chip size, with a compromise of the extra work involved in regular refreshing. It is, moreover, power hungry, so inappropriate for any Figure 10.2: Electronic memory types. SRAM: static random access memory; DRAM: dynamic random access memory; ROM: read only memory; PROM: programmable ROM; EPROM: electrically programmable ROM; EEPROM: electrically erasable and programmable ROM 204 Chapter 10 battery-powered device. DRAM has found wide application as data memory in mains-powered computers, such as the PC. The original ROMs and programmable read only memories (PROMs) could only ever be programmed once, and have now completely disappeared from normal usage. The first type of non-volatile reprogrammable semiconductor memory, electrically programmable read only memory (EPROM), represented a huge step forward e a non-volatile memory could now be reprogrammed. With a process called hot electron injection (HEI), electrons can be forced through a very thin layer of insulator, onto a tiny conductor embedded within the insulator, and can be trapped there almost indefinitely. This conductor is placed so that it interferes withtheactionof afieldeffect transistor(FET). Whenit ischarged/discharged, the action of the FET is disabled/enabled. This modified FET effectively becomes a single memory cell, far more dense than the SRAM discussed previously. Moreover, the memory effect is non-volatile; trapped charge is trapped charge! This programming does require a comparatively high voltage (around 25V), so generally needs a specialist piece of equipment. The memory is erased by exposure to intense ultraviolet light; EPROMs can always be recognized by the quartz window on the IC, which allows this to happen. Thenext stepbeyondHEI was NordheimFowler Tunneling. Thisrequiresevenfinermemory cell dimensions, and gives a mechanism for the trapped charge to be retrieved electrically, which had not previously been possible. With electrically erasable and programmable read only memory (EEPROM), words of data are individually writeable, readable and erasable, and are non-volatile. The downside of this is that more transistors are needed to select each word. Inmany casesthisflexibility isnotrequired. A revisedinternal memory structureledto flashmemory; inthis, theability toeraseindividual wordsisnotavailable. Wholeblockshave to be erased at any one time, ‘in a flash’. This compromise leads to a huge advantage: flash memory isvery highdensity indeed, moreorlessthehighestavailable. Thismemory typehas been a key feature of many recent products that we have now become used to, like digital cameras, memory sticks, solid-state hard drives and so on. A curious feature of flash and EEPROM, unlike most electronics, is that they exhibit awear-out mechanism. Electrons can get trappedintheinsulatorthroughwhichthey areforcedwhenawriteoperationtakesplace. Therefore this limitation is often mentioned in datasheets, for example a maximum of 100000write/erasecycles. This is avery highnumber, andis not experiencedinnormal use. Although EPROM had become very widely used, and had been integrated onto microcontrollers, itwasrapidly andcompletely replacedby flashmemory. Nowinembedded systems, the two dominant memory technologies are flash and SRAM. A glance back at Figures 2.2 and 2.3 shows how important they are to the mbed. Program memory on the LPC1768isflash, anddatamemory isSRAM. Onthembedcard, the‘USB disk’ isaflashIC. The other technology that we are likely to meet at times is EEPROM; this is still used where the ability to rewrite single words of data remains essential. Memory and Data Management 205 10.2 Using Data Files with the mbed Armed with a little knowledge about memory technologies, let’s explore how to access andusethembedmemory. TheLocalFileSystemlibrary allowsustosetupalocal filesystem for accessing the mbed flash universal serial bus (USB) disk drive. This allows programs to read and write files on the same disk drive that is used to hold the mbed programs, andwhichareaccessedfromthehostcomputer. Oncethesystemhasbeensetup, thestandard C/Cþ þ file access functions can be used to open, read and write files. 10.2.1 Reviewing some Useful C/C++Library Functions In C/Cþ þ we can open files, read and write data and also scan through files to specific locations, even searching for particular types of data. The functions for input and output operations are all defined by the C Standard Input and Output Library (stdio.h), introduced in Section B.9 of Appendix B. Here, we will use the functions summarized in Table 10.1 (this is effectively Table B.6, repeated here for convenience). C code feature Data can be stored in files (as chars) or as words and strings (as character arrays). The mbed provides a mechanism to allow storage in its USB disk, to save data that can be recalled at a later date. 10.2.2 Defining the mbed Local File System The compiler needs to know where to store and retrieve files; this is done using the mbed LocalFileSystem declaration. This sets up the mbed as an accessible flash memory storage unit and defines a directory for storing local files. To implement, simply add the line: Table 10.1: Useful stdio library functions Function Format Summary action fopen FILE * fopen ( const char * filename, const char * mode); Opens the file of name filename fclose int fclose ( FILE * stream ); Closes a file fgetc int fgetc ( FILE * stream ); Getsa character froma stream fgets char * fgets ( char * str, int num, FILE * stream ); Gets a string from a stream fputc int fputc ( int character, FILE * stream ); Writes a character to a stream fputs int fputs ( const char * str, FILE * stream ); Writes a string to a stream fseek int fseek ( FILE * stream, long int offset, int origin ); Moves file pointer to specified location str: An array containing the null-terminated sequence of characters to be written. stream: Pointer to a FILE object that identifies the stream where the string is to be written. 206 Chapter 10 LocalFileSystem local("local"); //Create local file system named "local" to the declarations section of a program. 10.2.3 Opening and Closing Files A filestoredonthembed(inthis examplecalled‘datafile.txt’) canthereforebeopenedwith the following command: FILE* pFile = fopen("/local/datafile.txt","w"); C code feature Thefopen( ) functioncall usesthe* operatorto assignapointerwithnamepFileto the file at the specific location given. Fromhere onwards we can access the file by referring to its pointer (pFile) rather than having to use the specific filename. We also need to specify whether wewant read or write access to the file. This is done by the ‘w’ specifier, whichisreferredto asanaccessmode(inthiscasedenotingwriteaccess). If the file does not already exist the fopen( ) function will automatically create it in the specified location. Several other file open access modes, and their specific meanings, are shown in TableB.7andareelaboratedfurtherinReference10.2. Thethreemostcommonaccessmodes are given also in Table 10.2. The append access mode (denoted by ‘a’) is useful for opening an existing file and writing additional data to the end of that file. When you have finished using a file for reading or writing it is essential to close it, for example using: fclose(pFile); If you fail to do this you might lose all access to the mbed (see Section 10.3.1)! 10.2.4 Writing and Reading File Data If the intention is to store numerical data, this can be done in a simple way by storing individual 8-bit data values. The fputc function allows this, as follows: char write_var=0x0F; fputc(write_var, pFile); Table 10.2: Common access modes for fopen Access mode Meaning Action ‘r’ Read Opens an existing file for reading ‘w’ Write Creates a new empty file for writing. If a file of the same name already exists it will be deleted and replaced with a blank file ‘a’ Append Appends to a file. Writeoperations result in data being appended to the end of the file. If the file does not exist a new blank file will be created Memory and Data Management 207 Thisstoresthe8-bitvariablewrite_var tothedatafile. Thedatacanalsobereadfromafileto a variable as follows: read_var = fgetc(pFile); Using the stdio.h functions, it is also possibleto read and writewords andstrings andsearch ormovethroughfiles lookingforparticulardataelements. TheC/Cþ þ fseek( ) functioncan be used to search through text files. 10.3 Example mbed Data File Access 10.3.1 File Access ProgramExample10.1 creates adata file and writes the arbitrary value 0x23 to that file. The fileissavedonthembedUSB disk. Theprogramthenopensandreadsbackthedatavalueand displays it to the screen in a host terminal application. /* Program Example 10.1: read and */ #include "mbed.h" Serial pc(USBTX,USBRX); LocalFileSystem local("local"); int write_var; int read_var; write char data bytes // setup terminal link // define local file system // create data variables int main () { FILE* File1 = fopen("/local/datafile.txt","w"); write_var=0x23; fputc(write_var, File1); fclose(File1); FILE* File2 = fopen ("/local/datafile.txt","r"); read_var = fgetc(File2); fclose(File2); pc.printf("input value = %i \n",read_var); // // // // open file example data put char (data value) into file close file // // // // open file for reading read first data value close file display read data value } Program Example 10.1 Saving data to a file CreateanewprojectandaddthecodeinProgramExample10.1. Runtheprogram, andverify that the data file is created on the mbed and read back correctly. If you navigate to and open thefiledatafile.txt inastandardtexteditorprogram(suchasMicrosoftWordpad), youshould seeahashcharacter(#) inthetopleft corner. This is becausetheASCII characterfor0x23is the hash character (recall Table 8.3). n Exercise 10.1 ChangeProgramExample10.1 to experiment with other datavalues; check theseagainst their associated ASCII codes. Write the numbers 1e10 and view them on the screen. n 208 Chapter 10 Note that when the microcontroller programopens a file on the local drive, the mbed will be marked as ‘removed’ on a host PC. This means the PC will often display a message such as ‘insert a disk into drive’ if you try to access the mbed at this time; this is normal, and stops both the mbed and the PC trying to access the USB disk at the same time. Note also that the USB drive will only reappear when all file pointers are closed in your program, or the microcontroller programexits. If a running programon the mbed does not correctly close an open file, you will no longer be able to see the USB drive when you plug the mbed into yourPC. Itisthereforeimportantforaprogrammertotakecarewhenusingfilestoensurethat all files are closed when they are not being used. If a running programon the mbed does not exit correctly, to allow you to see the drive again (and load a new program), use the following procedure: 1. Unplug the mbed. 2. Hold the mbed reset button down. 3. Whilestill holdingthebutton, pluginthembed. ThembedUSB driveshouldappearonthe host computer screen. 4. Keep holding the button until the new program is saved onto the USB drive. 10.3.2 String File Access ProgramExample 10.2 creates a file and writes text data to that file. The file is saved on the mbed. The program then opens and reads back the text data and displays it to the screen in a host terminal application. /* Program Example 10.2: Read and write text string data */ #include "mbed.h" Serial pc(USBTX,USBRX); // setup terminal link LocalFileSystem local("local"); // define local file system char write_string[64]; // character array up to 64 characters char read_string[64]; // create character arrays (strings) int main () { FILE* File1 = fopen("/local/textfile.txt","w"); fputs("lots and lots of words and letters", File1); fclose(File1); FILE* File2 = fopen ("/local/textfile.txt","r"); fgets(read_string,256,File2); fclose(File2); pc.printf("text data: %s \n",read_string); // open file access // put text into file // close file // // // // open file for reading read first data value close file display read data string } Program Example 10.2 Saving a string to a file Compileandruntheprogram,andverify thatthetextfileiscreatedandreadbackcorrectly e if youopenthefiletextfile.txt, foundonthembed, thecorrecttextdatashouldbefoundwithin. Memory and Data Management 209 When reading data from a file, the file pointer can be moved with the fseek( ) function. For example, thefollowingcommandwill repositionthefilepointerto the8thbyteinthetextfile: fseek (File2 , 8 , SEEK_SET ); // move file pointer to byte 8 from the start Thefseek( ) functionneeds threeinput terms; first, thenameof thefilepointer; secondly, the value to offset the file pointer to; and thirdly, an ‘origin’ term which tells the function where exactly to apply the offset. The termSEEK_SET is a predefined origin term(defined in the stdio library) which ensures that the 8-byte offset is applied from the start of the file. n Exercise 10.2 Add the following fseek( ) statement to Program Example 10.2 just prior to the data being read back: fseek (File2 , 8 , SEEK_SET ); // move file pointer to byte 8 Verifythat Tera Termonlydisplays thedata after byte8 of thedata file. Remember byte values increment from zero, so it will actually be after the 9th character in the file. n 10.3.3 Using Formatted Data It is possible to format data stored in a file. This can be done with the fprintf( ) function, whichhasvery similarsyntax to printf( ), exceptthatthefilenamepointer is also required. Wemay want, forexample, to logspecific events to adatafileand include variable data values such as time, sensor input data and output control settings. Program Example 10.3 shows use of the fprintf( ) function in an interrupt controlled pushbutton project. Each time the push-button is pressed, the light-emitting diode (LED) toggles and changes state. Also on each button press, the file log.txt is updated to include the time elapsedsincethepreviousbuttonpress, andthecurrent LED state. ProgramExample10.3also implementsasimpledebouncetimer(asdescribedinSection9.10) to avoidmultipleinterrupts and file write operations. C code feature /* Program Example 10.3: Interrupt toggle switch with formatted data logging to text file */ #include "mbed.h" InterruptIn button(p30); DigitalOut led1(LED1); Timer debounce; LocalFileSystem local("local"); void toggle(void); int main() { // // // // // Interrupt on digital input p30 digital out to onboard LED1 define debounce timer define local file system function prototype 210 Chapter 10 debounce.start(); // start debounce timer button.rise(&toggle); // attach the toggle function to the rising edge } void toggle() { // perform toggle if debounce time has elapsed if (debounce.read_ms()>200) led1=!led1; // toggle LED FILE* Logfile = fopen ("/local/log.txt","a"); // open file for appending fprintf(Logfile,"time=%.3fs: setting led=%d\n\r",debounce.read(),led1.read()); fclose(Logfile); // close file debounce.reset(); // reset debounce timer } } Program Example 10.3 Push-button LED toggle with formatted data logging Note that the text file log.txt may not display full formatting in a simple text viewer such as Microsoft Notepad. If line breaks are not displaying correctly then try a more advanced text file viewer such as Microsoft Wordpad. n Exercise 10.3 Create a program which prompts the user to type some text data into a terminal application. When the user presses return the text is captured and stored in a file on the mbed. Ensure that the data is correctly written to the data file by opening it with a standard text viewer program. n 10.4 Using External Memory with the mbed A flash SD (secure digital) card can be used with the mbed via the serial peripheral interface (SPI) protocol, as described in Reference 10.3. Using a micro SD card with a card holder cradle (as shown in Figure 10.3), it is possible to access the SD card as an external memory. Figure 10.3: An SD card with holder. (Image reproduced with permission of SparkFun Electronics) Memory and Data Management 211 Table10.3: Connections for SPI access to theSD card MicroSD breakout mbed pin CS 8 (DigitalOut) DI 5 (SPI mosi) Vcc 40 (Vout) SCK 7 (SPI sclk) GND 1 (GND) DO 6 (SPI miso) CD No connection Table 10.4: Library files and import paths for implementing the SD card interface Library Import path SDFileSystem http://mbed.org/users/simon/programs/SDFileSystem/5yj8f FATFileSystem http://mbed.org/projects/libraries/svn/FATFileSystem/trunk?rev¼ 29 The SD card can be configured into SPI communication mode, which requires the serial connections described in Table10.3. This example uses the mbedSPI port onpins 5, 6 and 7 and an arbitrary digital output on pin 8 to act as the SPI chip select signal. To implement the SD card interface, it is necessary to import the mbed libraries shown in Table 10.4. Having imported the described files and libraries, and connected the SD card as suggested, Program Example 10.4 writes a test text file to the card. /* Program Example 10.4: writing data to an SD card */ #include "mbed.h" #include "SDFileSystem.h" SDFileSystem sd(p5, p6, p7, p8, "sd"); Serial pc(USBTX, USBRX); // MOSI, MISO, SCLK, CS int main() { FILE *File = fopen("/sd/sdfile.txt", "w"); // open file if(File == NULL) { // check for file pointer pc.printf("Could not open file for write\n"); // error if no pointer } else{ pc.printf("SD card file successfully opened\n"); // if pointer ok } fprintf(File, "Here’ s some sample text on the SD card"); // write data fclose(File); // close file } Program Example 10.4 Writing data to an SD card 212 Chapter 10 CompileProgramExample10.4 andverify that theSD cardis correctly accessedby viewing the created text file sdfile.txt in a standard text editor program. Program Example 10.4 requires an enhanced definition statement for the SDFileSystem object, which in this case is named sd. Within the interface definition, SDFileSystem sd(p5, p6, p7, p8, "sd"), wesee that not only arethe SPI interfaceconnectionpins defined, but the name of the SDFileSystem object is also defined as an input variable in quotation marks. Notice that the line: if(File == NULL) { effectively performs an error check to ensure that the file was opened correctly by the previous fopen( ) call. If thefilepointerFilehas aNULL valuethenit means it has not been created and the fopen( ) call was not successfully implemented. n Exercise 10.4 Createa programwhich records 5seconds of analog data to thescreen and to a text file on an SD card. Use a potentiometer to generate the analog input data with sample period of 100 ms. Ensure that your data file records the elapsed time and voltage data. You can then open your datafilefromwithin astandard spreadsheet application, such as Microsoft Excel. This will enable you to plot a chart and to visualize the analog data. n 10.5 Introducing Pointers C code feature Pointers areusedinC/Cþ þ to indicatewhereaparticularelement orblock of data isstoredinmemory. Pointersarealso discussedinSectionB.8.2. Wewill look here in a little more detail at a specific mbed example using functions and pointers. When a pointer is defined it can be set to a particular memory address and C/Cþ þ syntax allows the data at that address to be accessed. Pointers are required for a number of reasons; one is because the C/Cþ þ standard does not allow us to pass arrays of data to and from functions, sowemustusepointersinstead. Insomeprogramminglanguages(suchasMatlab), it is possible to develop a mean average calculation function which reads in a data array, calculates the average from the sum of the data divided by the number of data values and returns the calculated mean. Using the mbed, however, we cannot pass the array of data into the function, so instead we need to pass the pointer value which points to the data array. Pointers are defined similarly to variables but by additionally using the * operator. For example, the following declaration defines a pointer called ptr which points to data of type int: Memory and Data Management 213 int *ptr; // define a pointer which points to data of type int The specific address of a data variable can also be assigned to a pointer by using the & operator, for example: int datavariable=7; int *ptr; ptr = &datavariable; // define a variable called datavariable with value 7 // define a pointer which points to data of type int // assign the pointer to the address of datavariable Inprogramcodethe* operatorcanalso beusedtogetthedatafromthegivenpointeraddress, for example: int x = *ptr; // get the contents of location pointed to by ptr and // assign to x (in this case x will equal 7) Pointers can also be used with arrays, because an array is really just a number of datavalues stored at consecutive memory locations. So if the following is defined: int dataarray[]={3,4,6,2,8,9,1,4,6}; // define an array of arbitrary values int *ptr; // define a pointer ptr = &dataarray[0]; // assign pointer to the address of // the first element of the data array the following statements will therefore be true: *ptr == 3; *(ptr+1) == 4; *(ptr+2) == 6; // the first element of the array pointed to // the second element of the array pointed to // the third element of the array pointed to So array searching can be done by moving the pointer value to the correct array offset. ProgramExample 10.5 implements a function for analyzing an array of data and returns the average of that data. /* Program Example 10.5: Pointers example for an array average function */ #include "mbed.h" Serial pc(USBTX, USBRX); // setup serial comms char data[]={5,7,5,8,9,1,7,8,2,5,1,4,6,2,1,4,3,8,7,9}; //define some input data char *dataptr; // define a pointer for the input data float average; // floating point average variable float CalculateAverage(char *ptr, char size); // function prototype int main() { dataptr=&data[0]; // point pointer to address of the first array element average = CalculateAverage(dataptr, sizeof(data)); // call function pc.printf("\n\rdata = "); for (char i=0; i<sizeof(data); i++) { // loop for each data value pc.printf("%d ",data[i]); // display all the data values } pc.printf("\n\raverage = %.3f",average); // display average value } // CalculateAverage function definition and code float CalculateAverage(char *ptr, char size) { 214 Chapter 10 int sum=0; // define variable float mean; // define variable for (char i=0; i<size; i++) { sum=sum + *(ptr+i); // add all } mean=(float)sum/size; // divide return mean; for calculating the sum of the data for floating point mean value data elements together by size and cast to floating point } Program Example 10.5 Averaging function using pointers Lookingatsomekey elementsof ProgramExample10.5, wecanseethatthepointer dataptr is assignedto theaddress of thefirst element of thedata array. The CalculateAverage( ) functiontakesinapointervaluethatpointsto thefirstvalueof the data array and a second value that defines the size of the array. The function returns the floatingpoint meanvalue. Thereis also anadditional C/Cþ þ keywordusedhere, sizeof, which deduces thesizeof aparticulararray. This gets thesize(i.e. thenumberof dataelements) inthe array data. Alsonotethatthecalculationof themeanvalueisintheformof anintegerdividedby a char, yet we want the answer to be a floating point value. To implement this, we cast the equation as floating point by using (float), which ensures that the resultant mean value is to floating point precision. C code feature Pointers are used for a number of reasons, especially in Cþ þ programs which rely heavily on functions, methods and passing data between these. Pointers can also be used to improve programming efficiency and speed, by directly accessing memory locations and data. In general, the use of pointers in the programming seen in this book is required because of a deficiency in the C/Cþ þ capabilities, i.e. not being able to pass arrays to functions. Where possible, we try to avoid the use of pointers in order to keep code simple and readable, but sometimes they offer the best solution to a programming challenge. 10.6 Mini-Project: Accelerometer Data Logging on Exceeding Threshold In this mini-project you are challenged to create a program that records the acceleration profileencounteredinasimplevibratingcantilever. It isthenpossibleto plot theacceleration data as shown in Figure 10.4. This project develops from the mini-project in Section 9.11. Design and implement a new project to the following specification: 1. Enable the mbed to access external SD card memory. 2. Attach a SPI accelerometer to a simple plastic cantilever with a flying lead to the mbed. 3. Program the accelerometer to cause an interrupt trigger when excessive acceleration is encountered. 4. Create an interrupt routine to log 100 data samples to a file on the SD card. You may wish to use the fprintf( ) function to format accelerometer data in the text file. Memory and Data Management 215 4 acceleration, g Accelerometer 2 0 -2 0 0.5 1 time, s 1.5 2 Figure 10.4: Accelerometer data-logging mini-project 5. When a certain acceleration threshold is exceeded, the data should be logged. The text file can then be opened in a spreadsheet software program, such as Microsoft Excel, to plot the recorded acceleration waveform. Note: to achieveasuitablesampleperiodyoumay want to apply anmbedTickerorTimerto ensure that the accelerometer logs data regularly. A sampling frequency of around 50Hz should be sufficient to record a detailed acceleration waveform. Chapter Review • Microprocessors use memory for holding the program code (program memory) and the working data (data memory) in an embedded system. • A coinoralogic flip-flop/bistablecanbethoughtof asasingle1-bitmemory devicewhich retains its state until the state is actively changed. • Volatile memory loses its data once power is removed, whereas non-volatile can retain memory with no power. Different technologies are used to realize these memory types, including SRAM and DRAM (volatile) and EEPROM and flash (non-volatile). • The mbed has 512kb of flash and 64kb of SRAM in the LPC1768 IC, and a further 16-megabit USB memory area. • Files can be created on the mbed for storing and retrieving data and formatted text. • An external SD memory card can be interfaced with the mbed to allow larger memory. 216 Chapter 10 • Pointers point to memory address locations to allow direct access to the data stored at the pointed location. • Pointers aregenerally requiredowingto thefact that C/Cþ þ does not allowarrays of data to be passed into functions, so a pointer to the array data must be passed instead. Quiz 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. What does the term bistable mean? How many bistables would you expect to find in the mbed’s SRAM? What are the fundamental differences between SRAM and DRAM type memory? What are the fundamental differences between EEPROM and flash type memory? Which C/Cþ þ command would open a text file for adding additional text to the end of the current file. Which C/Cþ þ command should be used to open a text file called ‘data.txt’ and read the 12th character? Give a practical example where data logging is required and explain the practical requirements with regard to timing, memory type and size. Give one reason why pointers are used for direct manipulation of memory data. Give the C/Cþ þ code that defines an empty five-element array called dataarray and a pointer called datapointer which is assigned to the first memory address of the data array. How is a pointer used to access and manipulate the different elements of a data array? References 10.1. Grindling, G. and Weiss, B. (2007). Introduction to Microcontrollers. https://ti.tuwien.ac.at/ecs/teaching/ courses/mclu/theory-material/Microcontroller.pdf 10.2. Cþ þ stdio.h fopen reference. http://www.cplusplus.com/reference/clibrary/cstdio/fopen/ 10.3. SD Group (Matsushita Electric Industrial Co. and SanDisk Corporation) (2006). SD Physical Layer Simplified Specification, Version 2.00. http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_ Physical_Layer_Spec.pdf CHAPTER 11 An Introduction to Digital Signal Processing Chapter Outline 11.1 What is a Digital Signal Processor? 219 11.2 Digital Filtering Example 220 11.3 An mbed DSP Example 222 11.3.1 Input and Output of Digital Data 222 11.3.2 Signal Reconstruction 224 11.3.3 Adding a Digital Low-Pass Filter 224 11.3.4 Adding a Push-Button Activation 228 11.3.5 Digital High-Pass Filter 229 11.4 Delay/ Echo Effect 229 11.5 Working with Wave Audio Files 232 11.5.1 The Wave Information Header 233 11.5.2 Reading the Wave File Header with the mbed 235 11.5.3 Reading and Outputting Mono Wave Data 236 11.6 Summary on DSP 239 11.7 Mini-Project: Stereo Wave Player 240 11.7.1 Basic Stereo Wave Player 240 11.7.2 Stereo Wave Player with PC Interface 240 11.7.3 Portable Stereo Wave Player with Mobile Phone Display Interface 241 Chapter Review 241 Quiz 241 References 242 11.1 What is a Digital Signal Processor? Digital signal processing (DSP) refers to the computation of mathematically intensive algorithms applied to data signals, such as audio signal manipulation, video compression, datacoding/decodinganddigital communications. A digital signal processor, also informally calledaDSPchip, isaspecial typeof microprocessorusedforDSPapplications. A DSP chip providesrapidinstructionsequences, suchasshift-and-addandmultiply-and-add(sometimes called multiply-and-accumulate or MAC), which are commonly used in signal processing algorithms. Digital filteringandfrequency analysis withtheFouriertransformrequires many numbers to be multiplied and added together, so a DSP chip provides specific internal Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00011-8 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 219 220 Chapter 11 hardwareandassociatedinstructionstomaketheseoperationsrapidinoperationandeasierto code in software. A DSP chip is therefore particularly suitable for number crunching and mathematical algorithm implementations. It is possible to perform DSP applications with any microprocessor or microcontroller, although specific DSP chips will outperform a standard microprocessor with respect to execution time and code size efficiency. 11.2 Digital Filtering Example Filters are used to remove chosen frequencies from a signal, as shown in Figure 11.1, for example. Here, thereisasignal withbothlow-frequency andhigh-frequency components. We may wishto removeeitherthelow-frequency component, by implementingahigh-passfilter (HPF), or the high-frequency component, by implementing a low-pass filter (LPF). A filter 1 HP filter 0 0.5 voltage 1 voltage 0.5 -0.5 -1 0 -0.5 0 20 40 60 1 80 100 120 140 160 180 200 time, ms -1 0 LP filter 20 40 60 voltage 0.5 0 -0.5 -1 0 20 40 60 80 100 120 140 160 180 200 time, ms Figure 11.1: High-pass and low-pass filtered signals 80 100 120 140 160 180 200 time, ms An Introduction to Digital Signal Processing 221 has acut-off frequency, whichdetermines whichsignal frequencies areinthepass-band(and are still evident afterthe filtering) and whicharein thestop-band (whichare removed by the filteringoperation). Thecut-off effect isnot perfect, however, as frequenciesinthestop-band are attenuated more the further away from the cut-off frequency they are. Filters can be designed to have different steepness of cut-off attenuation and so adjust the filter’s roll-off rate. Ingeneral, themorecomplex thefilterdesign, thesteeperitsroll-off canbe. Thefiltering can be performed with an active or a passive analog filter, but the same process can also be performed in software with a DSP operation. Wewill not go deeply into themathematicsof digital filtering, but thesoftwareprocessrelies heavily on addition and multiplication. Figure 11.2 shows an example block diagram for a simple digital filtering operation. Figure11.2showsthatcoefficienta1 ismultipliedby themostrecentsamplevalue. Coefficient a2 is multiplied by the previous sample and a3 is multiplied by the sample before that. The valuesof thefilter tapsdeterminewhetherthefilterishighpassorlowpassandwhatthecut-off frequency is. The order of the filter is given by the number of delays that are used, so the example shown in Figure 11.2 is a third order filter. The order of the filter determines the steepnessof thefilterroll-off curve; atoneextremeafirstorderfiltergivesavery gentleroll-off, while at the other an eighth order is used for demanding anti-aliasing applications. This filter is an example of a finite impulse response (FIR) filter, because it uses a finite numberof input values to calculatetheoutput value. Findingtherequiredvalues forthefilter taps is a complex process, but many design packages exist to simplify this process. As an Figure 11.2: Third order FIR filter 222 Chapter 11 example, if thefiltertapsinFigure11.2all haveavalueof 0.25, thenthisimplementsasimple meanaveragefilter(acrudeLPF) whichcontinuously averages thelast fourconsecutivedata values. It can be seen that the filter has a number of multiply and addition processes, which can be grouped into a single MAC operation. A DSP chip has a special area of hardware for processing MAC operations. This is specifically designed so that MAC commands can be processed in a single clock cycle, i.e. much faster than on conventional processors. It should be noted that although the mbed is not a dedicated DSP processor, it is still powerful enough to perform many DSP operations. 11.3 An mbed DSP Example 11.3.1 Input and Output of Digital Data We can develop an mbed program which reads signal data in via the analog-to-digital converter (ADC), processes the data digitally and then outputs the signal via the digital-toanalog converter (DAC). Since DSP algorithms need to sample and process data at regular fixedintervals, wewill usethembedTimerinterruptsto enableascheduledprogram. Wewill now write a programthat reads audio data and implements low- and high-pass digital filters. In these examples, the data will be output from the mbed’s DAC and through some simple electronic circuitry. The resulting audio output can then be routed to a loudspeaker amplifier (such as a set of portable PC speakers) so that you can listen to the processed signal. First, weneedasignal sourcetoinputtothembed. A simpleway tocreateasignal sourceisto use ahost PC’s audio output while playinganaudio file of thedesired signal data. A number of audio packages, such as Steinberg Wavelab, can be used to create wave audio files (with a .wav file extension); here, we will use three audio files as follows: • 200hz.wav e an audio file of a 200Hz sine wave • 1000hz.wav e an audio file of a 1000Hz sine wave • 200hz1000hz.wav e an audio file with the 200Hz and 1000Hz audio mixed. Each audio signal should be mono and around 60 seconds in duration. These files are available for download from the book website. The audio files can be played directly from the host PC into a set of headphones, and the differentsinewavesignalscanbeheard. Nowwecanconnecttheaudio signal to thembedby connecting the host PC’s audio cable to an mbed analog input pin. The signal can also be viewed on an oscilloscope. You will see that the signal oscillates positiveand negativeabout 0V. Thisisnotmuchuseforthembed, asitcanonly readanalogdatabetween0and3.3V, so all negative data will be interpreted as 0V. An Introduction to Digital Signal Processing 223 3.3V 47k audio signal in to mbed analog input pin + 10uF 47k GND Figure 11.3: Input circuit with coupling capacitor and bias resistors Because the mbed can only accept positive voltage inputs, it is necessary to add a small coupling and biasing circuit to offset the signal to a midpoint of approximately 1.65V. The offsethereisoftenreferredto asadirectcurrent(DC) offset. ThecircuitshowninFigure11.3 effectively couplesthehostPC’saudio outputto thembed. Createanewprojectandenterthe code of Program Example 11.1. /* Program Example 11.1 DSP input and Output */ #include "mbed.h" //mbed objects AnalogIn Ain(p15); AnalogOut Aout(p18); Ticker s20khz_tick; //function prototypes void s20khz_task(void); //variables and data float data_in, data_out; //main program start here int main() { s20khz_tick.attach_us(&s20khz_task,50); // attach task to 50us tick } // function 20khz_task void s20khz_task(void){ data_in=Ain; data_out=data_in; Aout=data_out; } Program Example 11.1 DSP input and output ProgramExample 11.1 first defines analog input and output objects (data_in and data_out) andasingleTickerobjectcalleds20khz_tick. Thereisalso afunctioncalleds20khz_task( ). 224 Chapter 11 The main( ) function simply assigns the 20kHz Ticker to the 20kHz task, with a Ticker interval of 50ms (which sets up the 20kHz rate). The input is now sampled and processed at this regular rate, within s20khz_task( ). n Exercise 11.1 Compile Program Example 11.1 and use a two-channel oscilloscope to check that the analog input signal and the DAC output signal are similar. Use the oscilloscope to see how accurate the DAC output is with respect to the analog input signal for all three audio files. Consider amplitude, phase and the waveform profile. You will also need to implement the input circuit shown in Figure 11.3. n 11.3.2 Signal Reconstruction If you look closely at the audio signals, particularly the 1000Hz signal or the mixed signal, you will see that the DAC output has discrete steps. This is more obvious in the highfrequency signal as it is closer to the sampling frequency chosen, as shown in Figure 11.4a. With many audio DSP systems, the analog output from the DAC is converted to a reconstructed signal by implementing an analog reconstruction filter, which removes all steps from the signal, leaving a smooth output. In audio applications, a reconstruction filter is usually designed to be an LPF with a cut-off frequency at around 20kHz, because the humanhearingrange does not exceed 20kHz. Thereconstructionfiltershownin Figure11.5 can be implemented with the current project (which gives the complete DSP input/output circuitasshowninFigure11.6). NotethataftertheLPF, adecouplingcapacitor isalso added to remove the 1.65V DC offset from the signal. Once the DC offset has been removed, the signal can be routed to a loudspeaker amplifier to monitor the processed DAC output. The mathematical theory associated with digital sampling and reconstruction is complex and beyondthescopeof thisbook. AsdiscussedinChapter4, inaudio samplingsystemsit isoften necessary to add an anti-aliasing filter prior to the analog-to-digital conversion. For simplicity this extra filter has not been implemented here. For those interested, the theory of sampling, aliasing and reconstruction is described well and in detail by a number of authors including Marven and Ewers (Reference 11.1) and Proakis and Manolakis (Reference 11.2). 11.3.3 Adding a Digital Low-Pass Filter We will add a digital low-pass filter routine to filter out the 1000Hz frequency component. This can be assigned to a switch input so that the filter is implemented in real time when a push-button is pressed. An Introduction to Digital Signal Processing 225 (a) without reconstuction filter 5.0 V 4.0 5.0 V 4.0 3.0 3.0 2.0 2.0 1.0 1.0 0.0 0.0 -1.0 -1.0 -2.0 -2.0 (b) with reconstuction filter implemented 5.0 V 4.0 5.0 V 4.0 3.0 3.0 2.0 2.0 1.0 1.0 0.0 0.0 -1.0 -1.0 -2.0 -2.0 Figure 11.4: Signal output DAC output 1.5 k +0.1 uF reconstructed audio signal 4.7 nF GND Figure 11.5: Analog reconstruction filter and decoupling capacitor This example will use a third order infinite impulse response (IIR) filter, as shown in Figure 11.7. The IIR filter uses recursive output data (i.e. data fed back from the output), as well as input data, to calculate the filtered output. 47k audio signal in + 10uF 47k GND reconstructed signal out 0.1uF + 1.5k Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 4.7nF GND Figure 11.6: DSP input/output circuit Figure 11.7: Third order digital IIR filter mbed Microcontroller 226 Chapter 11 Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 An Introduction to Digital Signal Processing 227 This filterresults inthefollowingequationforcalculatingthefilteredvaluegiventhecurrent input, the previous three input values and the previous three output values: yðnÞ¼b0xðnÞþ b1xðn 1Þþ b2xðn 2Þþ b3xðn þ a1yðn 1Þþ a2yðn 2Þþ a3yðn 3Þ 3Þ 11.1 where x(n) is the current data input value; x(n 1) is the previous data input value, x(n 2) is the data value before that, and so on; y(n) is the calculated current output value; y(n 1) is the previous data output value y(n 2) is the data value before that, and so on; and a0e3 and b0e3 are coefficients (filter taps) that define the filter’s performance. Wecanimplement this equationto achievefiltered datafromtheinput data. Thechallenging task is determining the values required for the filter coefficients to give the desired filter performance. Filter coefficients can, however, be calculated by a number of software packages, such as the Matlab Filter Design and Analysis Tool (Reference 11.3), and those provided in Reference 11.4. The LPF designed for a 600Hz cut-off frequency (third order with 20kHz sampling frequency) can be implemented as a C function as shown in Program Example 11.2. We chose a 600Hz LPF because the cut-off is exactly half way between the two signal frequencies. /*Program Example 11.2 Low-pass filter function */ float LPF(float LPF_in){ float a[4]={1,2.6235518066,-2.3146825811,0.6855359773}; float b[4]={0.0006993496,0.0020980489,0.0020980489,0.0006993496}; static float LPF_out; static float x[4], y[4]; x[3] = x[2]; x[2] = x[1]; x[1] = x[0]; y[3] = y[2]; y[2] = y[1]; y[1] = y[0]; // move x values by one sample // move y values by one sample x[0] = LPF_in; // new value for x[0] y[0] = (b[0]*x[0]) + (b[1]*x[1]) + (b[2]*x[2]) + (b[3]*x[3]) + (a[1]*y[1]) + (a[2]*y[2]) + (a[3]*y[3]); LPF_out = y[0]; return LPF_out; // output filtered value } Program Example 11.2 Low-pass filter function Here, wecanseethecalculatedfiltervaluesforthea andb coefficients. Thesecoefficientsare deduced by the online calculator provided by Reference 11.4. Note also that we have used the static variable type for the internally calculated datavalues. The static definition ensures that data calculated are held even after the function is complete, so the recursive data values for previous samples are held within the function and not lost during program execution. 228 Chapter 11 n Exercise 11.2 Create a new mbed program based on Program Example 11.1, only this time add the function for the LPF seen in Program Example 11.2. Now in the 20 kHz task process the input data by feeding it through the LPF function, for example: data_out=LPF(data_in); Compile and run the code to check that high-frequency components are filtered from the mbed’s analog output. Your system should use the mbed with the input and output circuitry shown in Figure 11.6. n 11.3.4 Adding a Push-Button Activation Wecannowassignaconditional statementto adigital input, allowingthefilterto beswitched in and out in real-time. The following conditional statement implemented in the 20kHz task will allow real-time activation of the digital filter: data_in=Ain-0.5; if (LPFswitch==1){ data_out=LPF(data_in); } else { data_out=data_in; } Aout=data_out+0.5; You will notice that before performing the calculation, the mean value of the signal is subtracted, in the line: data_in=Ain-0.5; Thisisto normalizethesignal to anaveragevalueof zero, so thesignal oscillatespositiveand negative and allows the filter algorithm to perform DSP with no DC offset in the data. As the DAC anticipates floating point data in the range 0.0e1.0, we must also add the mean offset back to the data before we output, in the line: Aout=data_out+0.5; n Exercise 11.3 Implement the real-time push-button activation in your LPF program. You can now use theoscilloscopeor headphonesto listen to thesignal which includesboth the200Hzand 1000Hz signal played simultaneously. When the switch is pressed, the high-frequency An Introduction to Digital Signal Processing 229 component should be removed, leaving just the low-frequency component audible, or visible on the oscilloscope. n 11.3.5 Digital High-Pass Filter The implementation of an HPF function is identical to the low-pass function, but with different filter coefficient values. The filter coefficients for a 600Hz HPF (third order with a 20kHz sample frequency) are as follows: float a[4]={1,2.6235518066,-2.3146825811,0.6855359773 }; float b[4]={0.8279712953,-2.4839138860,2.4839138860,-0.8279712953}; n Exercise 11.4 Add a second switch to the circuit and a filter function to the program, to act as an HPF. This switch will enable filtering of the low-frequency component and leave the high-frequency signal. Implement the second function with a second conditional statement in the 20 kHz task, so that either the LPF or HPF can be activated in real time. You should now beableto listen to thesimultaneous 200 Hz and 1000 Hz audio signal and filter either thelow frequency or thehigh frequency, or both, dependent on which switch is pressed. n 11.4 Delay/Echo Effect Many audio effects use DSP systems for manipulating and enhancing audio. These can be useful forlive audio processing(e.g. guitar effects) orforpost-production. Audio production DSP effects includeartificial reverb, pitchcorrection, dynamic rangemanipulationandmany other techniques to enhance captured audio. A feedback delay can be used to make an echo effect, which sees a single sound repeated a number of times. Each time the signal is repeated it is attenuated until it eventually decays away. Therefore, the speed of repetition and the amount of feedback attenuation can be manipulated. This effect is used commonly as a guitar effect, and for vocal processing and enhancement. Figure 11.8 shows a block diagram design for a simple delay effect unit. To implement the systemdesign shown in Figure 11.8, historical sample data must be stored so that it canbemixedback inwithimmediatedata. Therefore, sampleddigital dataneeds to be copied into a buffer (a large array) so that the feedback data is always available. The feedback gain determines how much buffer data is mixed with the sampled data. 230 Chapter 11 Figure 11.8: Delay effect block diagram For each sample coming in, an earlier value is mixed in also, but the length of time between the immediate and historical value can be varied by the delay time potentiometer. Effectively, thischangesthesizeof thedatabufferby resettinganarray counterbasedonthe value of the delay time input. If the delay time input is large, a large number of array datawill befedback beforeresetting, resultinginalongdelay time. Forsmallerdelay values the array counter will reset sooner, giving a more rapid delay effect. /* Program Example 11.3 Delay / Echo Effect */ #include "mbed.h" AnalogIn Ain(p15); //object definitions AnalogOut Aout(p18); AnalogIn delay_pot(p16); AnalogIn feedback_pot(p17); Ticker s20khz_tick; void s20khz_task(void); // function prototypes #define MAX_BUFFER 14000 // max data samples signed short data_in; // signed allows positive and negative unsigned short data_out; // unsigned just allows positive values float delay=0; float feedback=0; signed short buffer[MAX_BUFFER]={0}; // define buffer and set values to 0 int i=0; //main program start here int main() { s20khz_tick.attach_us(&s20khz_task,50); } // function 20khz_task void s20khz_task(void){ data_in=Ain.read_u16()-0x7FFF; buffer[i]=data_in+(buffer[i]*feedback); data_out=buffer[i]+0x7FFF; // read data and normalize // add data to buffer data // output buffer data value An Introduction to Digital Signal Processing 231 Aout.write_u16(data_out); if (i>(delay)){ i=0; delay=delay_pot*MAX_BUFFER; feedback=(1-feedback_pot)*0.9; }else{ i=i+1; } // // // // // write output if delay loop has completed reset counter calculate new delay buffer size calculate feedback gain value // otherwise increment delay counter } Program Example 11.3 Delay/echo effect Notice that the data_in and data_out values are defined as follows: signed short data_in; unsigned short data_out; // signed allows positive and negative // unsigned just allows positive values The short data type (see Table B.4) ensures that the data is constrained to 16bit values; this can be specified as signed (i.e. to use the range 32768 to 32767 decimal) or unsigned (to use the range 0 to 65535). We need the computation to take place with signed numbers. When outputting to the mbed’s DAC, however, this needs an offset adding owing to the fact that DAC is configured to work with unsigned data. C code feature The initial mbed hardware setup shown in Figure 11.6 can be used here. This demonstrates the advantage of a single hardware design that can operate multiple software features in adigital system. Wewill needto addpotentiometersto mbedanaloginputsinorderto control the feedback speed and gain in real time, as shown in Figure 11.8. Program Example 11.3 definesthedelay andfeedback potentiometersbeingconnectedto mbedanaloginputsonpins 16 and 17, respectively. n Exercise 11.5 Implement a new project with the code shown in Program Example 11.3. Initially, you will need to useatest signal which givesashort pulsefollowed byaperiod of inactivityto evaluate the echo effect performance. You should see a similar echo response to that shown in Figure 11.9. Verify that the delay and feedback gain potentiometers alter the output signal as expected. For testing purposes, a pulse signal called pulse.wav can be downloaded from the book website. n Figure 11.9 shows input and output waveforms for the delay/echo effect. It can be seen that for a single input pulse, the output is a combination of the pulse plus repeated echoes of that pulse with slowly diminishing amplitude. The rate of echo and the rate of attenuation are alteredby adjustingthepotentiometersasdescribed. Thisprojectcanbedevelopedasaguitar 232 Chapter 11 2.0 V DC 1.6 1.2 0.8 0.4 0.0 -0.4 -0.8 -1.2 -1.6 -2.0 0.0 s 0.25 0.5 0.75 1.0 1.25 1.5 1.75 2.0 2.25 2.5 1.75 2.0 2.25 2.5 Pico Technology www.picotech.com 500.0 mV DC 400.0 300.0 200.0 100.0 0.0 -100.0 -200.0 -300.0 -400.0 -500.0 0.0 s 0.25 0.5 0.75 1.5 1.0 1.25 Pico Technology www.picotech.com Figure 11.9: Input signal (top) and output signal (bottom) for the digital echo effect system effect unit by adding extra signal conditioning, variable amplification stages and enhanced output conditioning. Some good examples are given in Reference 11.5. 11.5 Working with Wave Audio Files Thischapter, sofar, hasanalyzedaDSPapplicationwhichcapturesdata, manipulatesthedata andthenoutputsit. However, anumberof signal processingapplicationsrely ondatathat has previously been captured and stored in data memory. Continuing with examples relating to An Introduction to Digital Signal Processing 233 digital audio, this can be explored by analyzing wave audio files and evaluating the requirements in order to output a continuous and controlled stream of audio data. 11.5.1 The Wave Information Header There are many types of audio data file, of which the wave (.wav) type is one of the most widely used. Wave files contain a number of details about the audio data followed by the audio data itself. Wave files contain uncompressed (i.e. raw) data, mostly in a format known as linear pulse code modulation (PCM). Since PCM specifically refers to the coding of amplitude signal data at a fixed sample rate, each sample value is given to a specified resolution (often16-bit) on alinear scale. Timedataforeachsampleis not recorded because the sample rate is known, so only amplitude data is stored. The wave header information details theactual resolutionandsamplefrequency of theaudio, so by readingthis headerit is possibleto accurately decodeandprocess thecontainedaudio data. Thefull waveheaderfile description is shown in Table 11.1. It is possible to identify much of thewave header information simply by opening a .wav file withatext editorapplication, asshowninFigure11.10. HereweseetheASCII charactersfor Table 11.1: Wave file information header structure Data name Offset (bytes) Size (bytes) Details ChunkID 0 4 The characters ‘RIFF’ in ASCII ChunkSize 4 4 Details the size of the file from byte 8 onwards Format 8 4 The characters ‘WAVE’ in ASCII Subchunk1ID 12 4 The characters ‘fmt’ in ASCII Subchunk1Size 16 4 16 for PCM AudioFormat 20 2 PCM ¼1. Any other value indicates data compressed format NumChannels 22 2 Mono ¼1; stereo ¼2 SampleRate 24 4 Sample rate of the audio data in Hz ByteRate 28 4 ByteRate¼SampleRate* NumChannels* BitsPerSample/8 BlockAlign 32 2 BlockAlign ¼NumChannels* BitsPerSample/8. The number of bytes per sample block BitsPerSample 34 2 Resolution of audio data SubChunk2ID 36 4 The characters ‘data’ in ASCII Subchunk2Size 40 4 Subchunk2Size¼Number of samples* BlockAlign. Thetotal size of the audio data in bytes Data 44 e The actual data of size given by Subchunk2Size 234 Chapter 11 Figure 11.10: Wave file opened in text editor SubChunk1Size =16 bytes ChunkID “RIFF” SampleRate =16000 Hz ChunkSize =27124 bytes ByteRate =32000 bits per second Format “WAVE” BlockAlign =2 bytes BitsPerSample =16 bits Subchunk1ID “fmt “ NumChannels =1 (mono) AudioFormat =1 (PCM) Subchunk2ID “data” First packets of audio data ... Subchunk2Size =27100 bytes Figure 11.11: Structure of the wave file header data ChunkID (‘RIFF’), Format (‘WAVE’), Subchunk1ID (‘fmt’) and Subchunk2ID (‘data’). These are followed by the ASCII data which makes up the raw audio. Looking more closely at the header information for this file in hexadecimal format, the specific values of the header information can be identified, as shown in Figure 11.11. Note also that for each value made up of multiple bytes, the least significant byte is always given first andthemost significantbytelast. Forexample, thefourbytesdenotingthesamplerateis given as 0x80, 0x3E, 0x00 and 0x00, which gives a 32-bit value of 0x00003E80¼16000 decimal. An Introduction to Digital Signal Processing 235 11.5.2 Reading the Wave File Header with the mbed In order to accurately read and reproduce wave data via a DAC, we need to interpret the information given in the header data, and configure the read and playback software features with the correct audio format (from AudioFormat), number of channels (NumChannels), sample rate (SampleRate) and the data resolution (BitsPerSample). Toimplementwavefilemanipulationonthembed,thewavedatafileshouldbestoredonaSecure Digital (SD) memory cardandtheprogramshouldbeconfiguredwiththecorrect SD reader libraries,asdiscussedinChapter10. TheSDcardisrequiredpredominantlybecausewaveaudio filesaregenerallyquitelarge,muchtoolargetobestoredinthembed’sinternal memory,butalso becausethefileaccessthroughtheserial peripheral interface(SPI)/SDcardinterfaceisveryfast. ProgramExample 11.4 reads a wave audio file called test.wav, utilizes the fseek( ) function used to move the file pointer to the relevant position, and then reads the header data and displays this to a host terminal. Notealso that to read .wav files onthe mbed, youshould use the ‘8.3 filename’ convention (sometimes referred to as short file name or SFN) for audio files. TheSFNconventionstipulatesthat filenamesshouldnot belongerthaneight characters with a three-character extension. /* Program Example 11.4 Wave file header reader */ #include "mbed.h" #include "SDFileSystem.h" SDFileSystem sd(p5, p6, p7, p8, "sd"); Serial pc(USBTX,USBRX); // set up terminal link char c1, c2, c3, c4; // chars for reading data in int AudioFormat, NumChannels, SampleRate, BitsPerSample ; int main() { pc.printf("\n\rWave file header reader\n\r"); FILE *fp = fopen("/sd/sinewave.wav", "rb"); fseek(fp, 20, SEEK_SET); fread(&AudioFormat, 2, if (AudioFormat==0x01) pc.printf("Wav file is } else { pc.printf("Wav file is } // set pointer to byte 20 1, fp); // check file is PCM { PCM data\n\r"); not PCM data\n\r"); fread(&NumChannels, 2, 1, fp); // find number of channels pc.printf("Number of channels: %d\n\r",NumChannels); fread(&SampleRate, 4, 1, fp); // find sample rate pc.printf("Sample rate: %d\n\r",SampleRate); fread(&BitsPerSample, 2, 1, fp); // find resolution pc.printf("Bits per sample: %d\n\r",BitsPerSample); fclose(fp); } Program Example 11.4 Wave header reader 236 Chapter 11 Try reading the header of a number of different wave files and verify that the correct information is always read to a host PC. A wave audio file can be created in many simple audio packages, such as Steinberg Wavelab, or can be extracted from a standard music compact disc with music player software such as iTunes or Windows Media Player. When reading different wavefiles remember to update the fopen( ) call to use the correct filename. In Program Example 11.4 the fread( ) function is used to read a number of data bytesinasinglecommand. Examplesof fread( ) showthatthememory addressfor the data destination is specified, along with the size of each data packet (in bytes) andthetotal numberof datapackets to beread. Thefilepointeris also given. Forexample, the command C code feature fread(&SampleRate, 4, 1, fp); // find sample rate reads asingle4-bytedatavaluefromthedatafilepointedto by fp andplaces thereaddataat the internal memory address location of variable SampleRate. n Exercise 11.6 Extend Program Example 11.4 to display ByteRate and Subchunk2Size, which indicates the size of the raw audio data within the file. n 11.5.3 Reading and Outputting Mono Wave Data Having accessed the wave file and gathered important information about its characteristics, it is possible to read the raw audio data and output that from the mbed’s DAC. To do this, we need to understand the format of the audio data. Initially, we will use an oscilloscope to verify that the data outputs correctly, but it is possible to output the audio data to a loudspeaker amplifier. For this example, we will use a 16-bit mono wave file of a pure sine wave of 200Hz (Figure 11.12). The same sine wave as utilized in Section 11.3 can be used here. The audio data in a 16-bit mono .wav file is arranged similarly to the other data seen in the header. The data starts at byte 44 and each 16-bit data value is read as two bytes with the least significant byte first. Each 16-bit sample can be outputted directly on pin 18 at the rate defined by SampleRate. It is very important to take good care of data input and output timing when working with audio, as any timing inaccuracies in playback can be heard as clicks or stutters. This can be a challenge because interrupts and timing overheads sometimes make it difficult for the audio to be streamed directly from the SD card at a constant rate. Therefore, a buffered system is used to enable accurate timing control. An Introduction to Digital Signal Processing 237 Figure 11.12: A 200 Hz sine wave .wav file played in Windows Media Player A good method to ensure accurate timing control when working with audio data is to use acircular buffer, as showninFigure11.13. Thebufferallows datato bereadinfromthedata fileandreadoutfromitto aDAC. If thebuffercanholdanumberof audio datasamples, then, aslongastheDAC outputtimerisaccurate, itdoesnotmattermuchif thetimefordatabeing read and processed from the SD card is somewhat variable. When the circular buffer write pointerreachesthelastarray element, itwrapsaroundsothatthenextdataisreadintothefirst memory elementof thebuffer. Thereisaseparatebufferreadpointerforoutputtingdatatothe DAC, and this lags behind the write buffer. It can be seen that two important conditions must be met for the circular buffer method to work; first, thedatawrittento thebuffermust bewrittenat anequal orfasterratethandatais read fromthe buffer (so that thewrite pointer stays ahead of the read pointer); and secondly, Figure 11.13: Circular buffer example 238 Chapter 11 thebuffermustnevercompletely fill up, orelsethereadpointerwill beovertakenby thewrite pointer and data will be lost. It is therefore important to ensure that the buffer size is sufficiently large, or to implement control code to safeguard against data wrapping. Program Example 11.5 reads a 16-bit mono audio file (called in this example testa.wav, whichcanbedownloadedfromthebook website) andoutputs at afixedsampleratewhichis acquiredfromthewavefileheader. As discussedabove, thecircularbufferis usedto ironout the timing inconsistencies found with reading from the wave data file. /* Program Example 11.5: 16-bit mono wave player */ #include "mbed.h" #include "SDFileSystem.h" #define BUFFERSIZE 4096 SDFileSystem sd(p5, p6, p7, p8, "sd"); AnalogOut DACout(p18); Ticker SampleTicker; int SampleRate; float SamplePeriod; int CircularBuffer[BUFFERSIZE]; int ReadPointer=0; int WritePointer=0; bool EndOfFileFlag=0; void DACFunction(void); // number of data in circular buffer // sample period in microseconds // circular buffer array // function prototype int main() { FILE *fp = fopen("/sd/testa.wav", "rb"); // open wave file fseek(fp, 24, SEEK_SET); // move to byte 24 fread(&SampleRate, 4, 1, fp); // get sample frequency SamplePeriod=(float)1/SampleRate; // calculate sample period as float SampleTicker.attach(&DACFunction,SamplePeriod); // start output tick while (!feof(fp)) { // loop until end of file is encountered fread(&CircularBuffer[WritePointer], 2, 1, fp); WritePointer=WritePointer+1; // increment Write Pointer if (WritePointer>=BUFFERSIZE) { // if end of circular buffer WritePointer=0; // go back to start of buffer } } EndOfFileFlag=1; fclose(fp); } // DAC function called at rate SamplePeriod void DACFunction(void) { if ((EndOfFileFlag==0)j(ReadPointer>0)) { // output while data available DACout.write_u16(CircularBuffer[ReadPointer]); // output to DAC ReadPointer=ReadPointer+1; // increment pointer if (ReadPointer>=BUFFERSIZE) { ReadPointer=0; // reset pointer if necessary } } } Program Example 11.5 Wave file player with utilizing a circular buffer An Introduction to Digital Signal Processing 239 (a) raw data output (before correction) (b) after two’s-complement correction 4.0 V DC 3.5 4.5 V DC 4.0 3.0 3.5 2.5 3.0 2.0 2.5 1.5 2.0 1.0 1.5 0.5 1.0 0.0 0.5 0.0 –0.5 –1.0 0.0 ms 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 –1.5 0.0 ms 1.0 Pico Technology ww.picotech.com 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 Pico Technology ww.picotech.com Figure 11.14: Wave file sine wave When Program Example 11.5 is implemented with a pure mono sine wave audio file, initially the results will not be correct. Figure 11.14a shows the actual oscilloscope trace of a sine wave read using this program example. Clearly, this is not an accurate reproduction of the sine wave data. The error occurs because the wave data is coded in 16-bit two’s-complement form, which means that positive data occupies data values 0 to 0x7FFF and values 0x8000 to 0xFFFF represent the negative data. Two’s complement arithmetic is introduced in Appendix A. A simple adjustment of the data is therefore required in order to output the correct waveform as shown in Figure 11.14b. n Exercise 11.7 Modify Program Example 11.5 to include two’s complement correction and ensure that, when using an audio file of a mono sine wave, the output data observed on an oscilloscope is that of an accurate sine wave. Appendix A should help you to work out how to do this. n 11.6 Summary on DSP As shown in this chapter, DSP techniques require knowledge of a number of mathematical and data handling aspects. In particular, attention to detail of timing and data validity is required to ensure that no dataoverflow errors or timing inconsistencies occur. We have also looked at a new type of data file which holds signal data to be output at a specific and 240 Chapter 11 controlledrate. Theability to apply simpleDSPtechniques, whetheronadedicatedDSPchip or on a general-purpose processor like the mbed, hugely expands our capabilities as embedded system designers. 11.7 Mini-Project: Stereo Wave Player This project can be done in basic form, or with several extensions. 11.7.1 Basic Stereo Wave Player A stereo wave player program can be developed by adding additional elements to Program Example 11.5. You will need to update the programto first analyzewhether thewave data is stereo or not, and then implement a conditional feature for the case where stereo data is stored. Stereo wave datais stored inconsecutivesamples forleft andright stereo playback as shown inFigure11.15. If usingjustthestandardmbedanalogoutputyouwill needtoaveragetheleft and right channel data to mono before outputting to the DAC. Full stereo ADC and DAC chips, such as the Texas Instruments TLV320AIC23b, can be purchased and interfaced with the mbed through its serial ports. 11.7.2 Stereo Wave Player with PC Interface Addauserinterfacethatwill display all thewavefilenamesstoredonanSD cardto ahostPC terminal. The user can then select a file to be played by selecting a number that represents the chosen data file. Right channel data 16-bit (LSB-MSB) Left channel data 16-bit (LSB-MSB) Right channel data 16-bit (LSB-MSB) Left channel data 16-bit (LSB-MSB) Figure 11.15: Interleaved left and right channel stereo data An Introduction to Digital Signal Processing 241 11.7.3 Portable Stereo Wave Player with Mobile Phone Display Interface Experiment with using a liquid crystal display (LCD) mobile phone display and digital push-buttons to develop your own portable audio player. Chapter Review • DSP systems and algorithms are used for managing and manipulating streams of data and therefore require high precision and timing accuracy. • A digital filtering algorithm can be used to remove unwanted frequencies from a data stream. Similar mathematical algorithms can be used for signal analysis, audio/video manipulation and data compression for communications. • A DSP systemcommunicates withtheexternal worldthroughanalog-to-digital converters and digital-to-analog converters, so the analog elements of the system also require careful design. • DSP systems usually rely on regularly timed data samples, so the mbed Timer and Ticker interfaces are useful for programming regular and real-time processing. • Wave audio files hold high-resolution audio data which can be read from an SD card and output through the mbed DAC. • Data management and effective buffering are required to ensure that timing and data overflow issues are avoided. Quiz 1. 2. 3. 4. 5. 6. 7. 8. 9. What does the term MAC refer to and why is this important for DSP systems? What differentiates a DSP microprocessor from a microcontroller? What is the difference between an FIR and an IIR digital filter? What are digital filter coefficients and how can they be acquired for a specific digital filter design? Explaintheroleof analogbiasingandanti-aliasingwhenperformingananalog-to-digital conversion. What is a reconstruction filter and where would this be found in a DSP system? What is a circular buffer and why might it be used in DSP systems? What are the potential effects of poor timing control in an audio DSP system? A wave audio file has a 16-bit mono data value given by two consecutive bytes. What will be the correct corresponding voltage output, if this is output through the mbed’s DAC, for the following data? (a) 0x35 0x04 (b) 0xFF 0x5F (c) 0x00 0xE4 242 Chapter 11 10. Drawablock diagramdesignof aDSP process formixingtwo 16-bit datastreams. If the data output is also to be 16 bit, what consequences will this process have on the output data resolution and accuracy? References 11.1. 11.2. 11.3. 11.4. 11.5. Marven, C. and Ewers, G. (1996). A Simple Approach to Digital Signal Processing. Wiley Blackwell. Proakis, J. G. and Manolakis, D. K. (1992). Digital Signal Processing: Principles, Algorithms and Applications. Prentice Hall. The Mathworks (2010). FDATool e open filter design and analysis tool. http://www.mathworks.com/ help/toolbox/signal/fdatool.html Fisher, T. (2010). Interactive Digital Filter Design. Online Calculator. http://www-users.cs.york.ac.uk/ ~fisher/mkfilter/ Sergeev, I. (2010). Audio Echo Effect. http://dev.frozeneskimo.com/embedded_projects/audio_echo_ effect CHAPTER 12 Advanced Serial Communications Chapter Outline 12.1 Introducing Advanced Serial Communication Protocols 243 12.2 Bluetooth Serial Communication 244 12.2.1 Introducing Bluetooth 244 12.2.2 Interfacing the RN-41 and RN-42 Bluetooth Modules 244 12.2.3 Sending mbed Data over Bluetooth 245 12.2.4 Receiving Bluetooth Data from a Host Terminal Application 247 12.2.5 Communicating between Two mbeds on Bluetooth 248 12.3 Introducing USB 251 12.3.1 Using the mbed to Emulate a USB Mouse 252 12.3.2 Sending USB MIDI Data from an mbed 253 12.4 Introducing Ethernet 255 12.4.1 Ethernet Overview 255 12.4.2 Implementing Simple mbed Ethernet Communications 257 12.4.3 Ethernet Communication between mbeds 259 12.5 Local Network and Internet Communications with the mbed 261 12.5.1 Using the mbed as an HTTP Client 262 12.5.2 Using the mbed as an HTTP File Server 264 12.5.3 Using Remote Procedure Calls to Modify mbed Outputs 266 12.5.4 Controlling the mbed using a Remote JavaScript Interface 267 Chapter Review 270 Quiz 271 References 271 12.1 Introducing Advanced Serial Communication Protocols We have already discussed a number of communication methods in earlier chapters, and in particularserial communicationswhichallowfastmessagesto besentandreceivedwithonly a small numberof physical connections, such as universal asynchronous receiver/transmitter (UART), serial peripheral interface (SPI) and inter-integrated circuit (I2C). Each technique requiresaprotocol whichdefinestheway inwhichcommunicationsareinitiatedandhowthe data messages are structured, effectively a code for untangling all the digital 0s and 1s, in order to understand a message as meaningful information. Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00012-X Copyright Ó 2012 Elsevier Ltd. All rights reserved. 243 244 Chapter 12 There are a vast number of serial communications protocols and each is developed to a specific standard and usually with a very specific purpose or application in mind. For this reason, eachserial communicationmethodhasitsownadvantagesanddisadvantagesforcertain applications. Universal serial bus (USB) communications, ontheonehand, work very well for connectinghigh-level peripheral devicesto personal computers(PCs) andhaveasimple‘plugand-play’ method for installation. Ethernet communications, on the other hand, are very high speed and have been developed to allow computer-to-computer communications, whichled to the high-speed Internet networks that we nowadays often take for granted. This chapter discusses a number of advanced serial communications technologies with respect to thembed, to act as adoorway towards thedevelopment of moreadvanced projects relying on digital connectivity and data sharing. 12.2 Bluetooth Serial Communication 12.2.1 Introducing Bluetooth Bluetoothis anovel formof digital radio communication, operatinginthe2.402e2.480GHz radio band. Bluetooth provides wireless data links between such devices as mobile phones, computers, wireless audio headsets and systems requiring the use of remote sensors. Bluetooth’s main characteristics can be summarized as follows: • The communications range is up to 100m for Class 1 Bluetooth devices and up to 20m for Class 2 Bluetooth devices. • Bluetooth consumes relatively low power; Class 1 and 2 devices use around 100mW and 2.5mW, respectively. • Data rates up to 3Mbps can be achieved. • Up to eight devices can be simultaneously linked. • Spread-spectrum frequency hopping is applied, with the transmitter changing frequency in a pseudo-random manner 1600 times per second. The Bluetooth standards, controlled by the Bluetooth Special Interest Group (Reference 12.1), dictate that when Bluetooth devices detect one another, they determine automatically whether they need to interact with each other. Each device has a Media Access Control (MAC) address which communicating devices can recognize and initialize interaction if required. Bluetooth systems in contact with each other forma piconet. Once communication isestablished, membersof thepiconetsynchronizetheirfrequency hopping, sothey remainin contact. A singleroomcancontainseveral piconetswithanumberof devicescommunicating. 12.2.2 Interfacing the RN-41 and RN-42 Bluetooth Modules TheRovingNetworksRN-41(showninFigure12.1) andRN-42Bluetoothmodulesareserial devicesthatallowreplacementof serial wireswithasimpleBluetoothinterface. Forexample, Advanced Serial Communications 245 Figure 12.1: Roving Networks RN-41 Bluetooth module. (Image reproduced with permission of Sparkfun Electronics) most laptop computers have Bluetooth capability installed, so it is possible to replace the USB cable to an mbed with a Bluetooth device and allow wireless host terminal communication. The RN-41 and RN-42 modules have identical control and functionality; however, theRN-41 is aClass 1 Bluetoothdevice, whereas theRN-42is Class 2. TheRN-41 operates at baud rates between 1200bps and 921kbps and includes auto-detect and auto-connection features. In this section the RN-41 module is used; however, all software examples should work equally for an RN-42 device. In order to communicate with a host PC from an RN-41 or RN-42 device, the host PC must first have Bluetooth enabled and the device added as a known Bluetooth module. When initializing the connection to the Bluetoothmodule, it will be necessary to specify a passkey, which is set by default to ‘1234’ as specified in the Advanced User Manual for Roving Networks Bluetooth Devices (Reference 12.2). 12.2.3 Sending mbed Data over Bluetooth TheRN-41hasanumberof configurablefeatures. However, itisvery simpleto useoutof the box as astandardserial interfacewithasimpleTX/RX connection. TheRN-41 thereforecan be connected to one of the mbed’s UART serial ports and configured with a simple mbed serial protocol. The wiring for an RN-41 connected to mbed serial port on pins 9 and 10 is shown in Figure 12.2. It is possible to configure an mbed to send arbitrary data over a serial interface to verify that data is being received by a host terminal application such as Tera Term. Program Example 12.1setsupserial communicationswiththeRN-41andsendsdataovertheUART. Thedatais actually acontinuouscountthroughtheASCII valuesrepresentingnumerical characters0e9. The onboard mbed light-emitting diodes (LEDs) are also configured to represent the count value. In the example we convert the ASCII byte to the relevant numerical value by bit Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller 246 Chapter 12 Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 Figure 12.2: Bluetooth RN-41 connected to the mbed (Image reproduced with permission of Sparkfun Electronics) maskingandclearingthehigher4bits. Thisleavesjustasinglevaluebetween0x00and0x09. Inreality thebitmaskingof x isnotessential becausetheled BusOut objectcanonly takethe lower four bits of the 8-bit anyway. We performthe bit mask here just for completeness, but you could remove it and check that functionality remains the same. /* Program Example 12.1: Bluetooth serial test data program */ #include "mbed.h" Serial rn41(p9,p10); BusOut led(LED4,LED3,LED2,LED1); int main() { rn41.baud(115200); while (1) { for (char x=0x30;x<=0x39;x++){ rn41.putc(x); led = x & 0x0F; wait(0.5); } } } // set baud for RN-41 // ASCII numerical characters 0-9 // send test char data on serial // set LEDs to count in binary Program Example 12.1 Bluetooth serial spammer If aBluetoothconnectionissuccessfully set uponthehost PC (asdetailedin Section12.2.2), thedatasent overBluetoothfromProgramExample12.1shouldbevisibleonahost terminal application. Advanced Serial Communications 247 n Exercise 12.1 Power the mbed with a battery (acceptable voltage range 4.5e9V) by connecting the batteryoutputs to pin 1 (GND) and pin 2 (VIN). This will allow you to removetheUSB cable and demonstrate fully remote communication over Bluetooth. n 12.2.4 Receiving Bluetooth Data froma Host Terminal Application As well as sending data to a PC, it is possible to send data from the host PC to an mbed over Bluetooth. Program Example 12.2 will receive any data from a host PC terminal application; the remote mbed displays the lower 4 bits of the received byte on the four onboard LEDs. This program can be referred to as a ‘sniffer’ program as the mbed continuously monitors (or ‘sniffs’) the serial connection and performs an action when data becomes available. /* Program Example 12.2: Bluetooth serial sniffer program */ #include "mbed.h" Serial rn41(p9,p10); BusOut led(LED4,LED3,LED2,LED1); int main() { rn41.baud(115200); // setup baud rate rn41.printf("Serial sniffer: outputs received data to LEDs\n\r"); while (1) { if (rn41.readable()) { // if data available char x=rn41.getc(); // get data led=x; // output LSByte to LEDs } } } Program Example 12.2 Bluetooth serial sniffer program Program Example 12.2 should run and show wireless communications from the PC to the mbed. If the user presses numerical values between 0 and 9 on the PC keyboard, the corresponding binary representation should be shown on the remote mbed. n Exercise 12.2 Add a batteryand a liquid crystal display(LCD) to theBluetooth-enabled mbed. Update ProgramExample12.2 to allow a user to typedata that on thePC keyboard will appear on the wireless LCD. n 248 Chapter 12 12.2.5 Communicating between Two mbeds on Bluetooth By implementing Bluetooth it is possible to have two or more mbeds communicating wirelessly with each other. The configuration for mbed-to-mbed communication is a little more involved, however, as it is necessary to perform bespoke RN-41 setup procedures in softwareduringinitialization. Thisthereforerequiresamuchmorethoroughunderstandingof the previously mentioned user manual (Reference 12.2). In our example we will use two mbeds and send data from one to the other. We will therefore refer to the mbed sending the data as the master and the receiving mbed as the slave. The MAC address of the receiving systemisrequiredto successfully communicatedata. TheMAC addressof theRN-41module shown in Figure 12.1 can clearly be seen on the module and the passkey is given a default value specified in the RN-41 user manual (in this case ‘1234’). ThemastermbedcommunicateswiththemasterRN-41overUART. ThemasterRN-41needs to be configured to initialize a Bluetooth connection with the slaveRN-41. The serial UART procedure for doingthis is summarized as follows and discussed in moredetail intheRN-41 user manual. • Enter command mode by sending ‘$$$’ to RN-41 module. • Connect to a remote MAC address by sending ‘C,< address> ’ where < address> is the MAC address of the remote slave module to be connected to. • Exit connection mode by sending ‘—< cr> ’, where < cr> is the ASCII carriage return value, i.e. 0x0D. Note that there are other useful commands which will generate status responses from the RN-41, such as: • ‘D’ e displays basic settings: Address, Name, UART Settings, Security, Pin code, Bonding, Remote Address • ‘GB’ e returns the Bluetooth Address of the device • ‘GK’ e returns the current connection status: 1¼connected, 0¼not connected • ‘SP,<text>’ e setsthesecurity passkey forpairing(note, thedefault ‘1234’ shouldalready be set). ProgramExample12.3showsaninitializationroutineforconnectingamasterRN-41module to a remote slave RN-41 module. The slave RN-41 module in this example has a MAC address of 00066607ACC1. /*Program Example 12.3: function to initialize paired Bluetooth connection with RN-41 modules */ void initialize_connection() { rn41.putc(’$’); // Enter command mode rn41.putc(’$’); // Advanced Serial Communications 249 rn41.putc(’$’); wait(0.5); // rn41.putc(’C’); rn41.putc(’,’); rn41.putc(’0’); rn41.putc(’0’); rn41.putc(’0’); rn41.putc(’6’); rn41.putc(’6’); rn41.putc(’6’); rn41.putc(’0’); rn41.putc(’7’); rn41.putc(’A’); rn41.putc(’C’); rn41.putc(’C’); rn41.putc(’1’); wait(0.5); // // Send MAC address // // // // // // // // // // // // rn41.putc(’-’); rn41.putc(’-’); rn41.putc(’-’); rn41.putc(0x0D); wait(0.5); // Exit command mode // // // } Program Example12.3 Function to initializepaired Bluetooth connection with RN-41 modules Once a connection is initialized, it is possible to communicate data wirelessly from the master to the slave using simple putc( ) commands. Program Example 12.4 shows the main codefor sendingacontinuous count variableto theslaveover Bluetooth. An overrideswitch is also included to allow a user to override the count value and show remote control capabilities for the slave Bluetooth device. /* Program Example 12.4: Paired Bluetooth master program */ #include "mbed.h" Serial rn41(p9,p10); BusOut led(LED4,LED3,LED2,LED1); DigitalIn Din(p26); // digital switch input on pin 14 char x; void initialize_connection(void); int main() { rn41.baud(115200); initialize_connection(); while (1) { if (Din==1) { // if digital input switched high x=0x0F; // override with 0x0F } else { 250 Chapter 12 x++; if (x>0x0F) { x=0; } } rn41.putc(x); led = x; wait(0.5); // else increment and // output count value // send char data on serial // set LEDs to count in binary } } // add function initialize_connection code here. Program Example 12.4 Paired Bluetooth master program TheslaveBluetoothsystemcanusethesamesniffercodeasgiveninProgramExample12.2. Thetwo mbedsystems (similarto thoseshownin Figure12.3) shouldnowconnect andshare the same count data wirelessly. n Exercise 12.3 Add an LCD to each mbed device. Add also a uniquesensor such as an accelerometer or ultrasonic range finder to each mbed. Implement a two-way communication program which allows the data from both sensors to be displayed on both displays simultaneously. n (a) comms master with switch input (b) comms slave without switch Figure 12.3: Two battery-powered mbeds communicating via RN-41 Bluetooth modules Advanced Serial Communications 251 Bluetooth is an exciting technology that allows short-range wireless communication. This has many valuable applications where wires are intrusive, expensive or difficult to install. Recent enhancements to Bluetooth have enabled streaming of high-quality audio data and increased range, so the opportunities and applications for Bluetooth are continuously growing. 12.3 Introducing USB The USB protocol was originally introduced to provide a more flexible interconnection system, whereby itemscouldbeaddedorremovedwithouttheneedforreconfigurationof the wholesystem. USB is nowubiquitousandvery familiar, widely usedforitsoriginal purpose, but also to connect all manner of devices, for example digital cameras, MP3 players, webcams and memory sticks, to the PC. A USB network hasonehost, andcanhaveoneormany functions, whichinthiscaserefersto USB-compatible devices that can interact with the host. It is also possible to include hubs, which can have a number of functions connected to them, and which in turn link back to the host. Threedatarates arerecognized: highspeedat 480Mbps, full speedat 12Mbps andlow speedat 1.5Mbps. Thelast of theseis forvery limitedcapability devices, whereonly asmall amount of data will be transferred. The specification for USB Version 2.0 is defined in Reference 12.3. USB uses afour-wire interconnection. Two wires, labeled Dþ and D , carry the differential signal, andtwo areforpowerandearth. Withincertainlimits, USB functionscandrawpower from the bus, taking up to 100mA at a nominal 5V. This is supplied by the host. A higher power demand can also be requested; alternatively, the functions can be self-powered. When a device is first attached to the bus the host resets it, assigns it an address and interrogates it (a process known as enumeration). It thus identifies it and gathers basic operating information, for example device type, power consumption and data rate. All subsequent datatransfersareinitiatedonly by thehost. Itfirstsendsadatapacketwhichspecifiesthetype and direction of data transfer, and the address of the target device. The addressed device responds as appropriate. There is usually then a handshake packet, to indicate success (or otherwise) of the transfer. We have already used the mbed USB interface on a number of occasions: first to connect to the mbed and to download program binary files, but also to communicate serial data to and from a host PC, in order to interface with a terminal application. The mbed has two USB ports: one with a standard USB connector, which we have used already to connect to a PC, and a second on pins 31 and 32 (labeled Dþ and D on the mbed), as seen in Figure 2.1. Several USB library features are provided through the mbed website; these are particularly useful for emulating the mbed as a keyboard or mouse, or for working with musical instrument digital interface (MIDI) systems and advanced audio projects. 252 Chapter 12 12.3.1 Using the mbed to Emulate a USB Mouse Several mbed USB interfaces are defined within the mbed USBDevice library. In order to utilize the USB interfaces, the USBDevice library should be imported to a programfromthe following location: http://mbed.org/users/samux/libraries/USBDevice/m24owv Full documentation on all the USB interfaces can be found on the mbed website. One such interfaceis theUSBMousefeature. WithUSBMouseit is possibleto makethembedbehave like a standard USB mouse, sending position and button-press commands to the host. Program Example 12.5 implements a USBMouse interface and continuously sends relative position information to move the mouse pointer around four coordinates, which make up a square. The coordinates are defined by the two arrays dx and dy; the mouse is moved to these positions within a for loop. The mouse, when initialized to its default parameters, uses arelativecoordinatesystem, soif dy ¼40anddx ¼40, thenthemousepointerisinstructedto move 40 pixels right and 40 pixels down. Negative coordinates for x and y planes move the pointer left and up, respectively. /* Program Example 12.5: Emulating a USB mouse */ #include "mbed.h" // include mbed library #include "USBMouse.h" // include USB Mouse library USBMouse mouse; // define USBMouse interface int dx[]={40,0,-40,0}; int dy[]={0,40,0,-40}; int main() { while (1) { for (int i=0; i<4; i++) { mouse.move(dx[i],dy[i]); wait(0.2); } } } // relative x position coordinates // relative y position coordinates // scroll through position coordinates // move mouse to coordinate Program Example 12.5 Emulating a USB mouse n Exercise 12.4 Experiment with the other features of the USBMouse library. In particular, implement the following small programs: 1. Using the scroll library feature, automatically make pages scroll up and down. You will need to open a document or webpage to test the scroll feature. 2. Add a push-button to your mbed and implement a mouseclick feature. 3. Add an accelerometer to your mbed and use the read acceleration values to update the mouse pointer position. n Advanced Serial Communications 253 12.3.2 Sending USB MIDI Data froman mbed MIDI is a serial message protocol that allows digital musical instruments to communicate with digital signal processing systems which can turn those signals into sound. It was first developed in 1982 by the MIDI Manufacturers’ Association. MIDI data contains a number of parameters, as described in detail in Reference 12.4. It is still a valuable method for enabling communications between electronic music systems, particularly given that in 1999 a new MIDI standard was developed to allow messaging through the more modern USB protocol. AnexampleinstrumentusingaMIDI interfaceisaMIDI piano-stylekeyboard. Thekeyboard itself does not makeany sound. Instead, theMIDI signalscommunicatewithasoundmodule or computer with MIDI software installed, so that the signals can be turned into music. In a very simple MIDI system the most valuable information is: • whether a musical note is to be switched on or off • the pitch of the note. The method for setting up and interfacing the mbed with MIDI sequencing software varies subtly dependingonthesoftwareused. Inmost cases, however, theaudio sequencersoftware (suchas AbletonLive, AppleLogic orSteinbergCubase) automatically recognizes thembed MIDI interface and allows it to control a software instrument or synthesizer. A MIDI interface can be created by first importing the USBDevice library (as mentioned in Section 12.3.1 above), importing theUSBMIDI.h headerfile and initializing theinterface (in this case named ‘midi’) as follows: USBMIDI midi; // initialize MIDI interface A MIDI message to sound a note is activated by the following command: midi.write(MIDIMessage::NoteOn(note)); // play musical note This command uses the Cþ þ scope resolution operator (::), which relates to a number of advanced Cþ þ programming features. It is not our intention to explore advanced Cþ þ programmingconcepts, so forthepurposeof this exampleit is sufficient simply to accept the described syntax for sending a MIDI message from the mbed. The value note represents notes on a piano keyboard; this is a 7-bit value so there are 128 possiblenotesthatcanbedescribedby MIDI. Thevaluezerorepresentsavery lowCnoteand, as thereare12notes inthechromatic musical scale, octaves of C occurat multiplesof 12. So theMIDI notevalue60representsmiddleC (also referredto asC4), whichhasafundamental frequency of 261.63Hz. An excerpt of the full MIDI note table is shown in Table 12.1. ProgramExample12.6setsupanmbedMIDI interfacetocontinuously stepthroughthenotes shown in Table 12.1. The Program Example also implements an analog input, which can be connected to a potentiometer, so that the speed of the steps can be manipulated. 254 Chapter 12 Table 12.1: MIDI note values and associated musical notes and frequencies MIDI note 48 49 50 51 52 53 54 55 56 57 58 59 Musical note C3 C#3 D3 D#3 E3 F3 F#3 G3 G#3 A3 A#3 B3 Frequency (Hz) 130.1 138.6 146.8 155.6 164.8 174.6 185.0 196.0 207.7 220.0 233.1 246.9 MIDI note 60 61 62 63 64 65 66 67 68 69 70 71 Musical note C4 C#4 D4 D#4 E4 F4 F#4 G4 G#4 A4 A#4 B4 Frequency (Hz) 261.6 277.2 293.7 311.1 329.6 349.2 370.0 392.0 415.3 440.0 466.2 493.9 /* Program Example 12.6: MIDI messaging with variable scroll speed */ #include "mbed.h" #include "USBMIDI.h” USBMIDI midi; // initialize MIDI interface AnalogIn Ain(p19); // create analog input int main() { while (1) { for(int i=48; i<72; i++) { midi.write(MIDIMessage::NoteOn(i)); wait(Ain); midi.write(MIDIMessage::NoteOff(i)); wait(2*Ain); } } } // // // // // step through notes note on pause note off pause Program Example 12.6 MIDI messaging with variable scroll speed The output of Example 12.6 is shown in the MIDI control window of Apple Logic software, in Figure 12.4. n Exercise 12.5 Replace the analog input in Program Example 12.6 with a value measured by an ultrasonic range finder. It is therefore possible to change the speed of the note transitions by moving closer to or further away from the sensor. Also experiment with modifyingthenoteparameters, for examplethedistancemeasured by an ultrasonic range finder could be used to change the pitch (i.e. the note number) being played. n Other mbed USB library features, which are all supported by the USBDevice library, are shown in Table 12.2. Advanced Serial Communications 255 Figure 12.4: MIDI notes generated by the mbed and recorded into Apple Logic software Table 12.2: mbed USBDevice library Mbed USB library Description USBMouse Allows the mbed to emulate a USB mouse USBKeyboard Allows the mbed to emulate a USB keyboard USBMouseKeyboard A USB mouse and keyboard feature set combined in a single library USBHID Allowscustomdata to besent and received froma human interfacedevice(HID) allowing custom USB features to bedeveloped without theneed for host drivers to be installed USBSerial Emulates an additional standard serial port on the mbed, through the USB connections USBMIDI Allows send and receive of MIDI messages in communication with a host PC using MIDI sequencer software USBAudio Allowsthembed to berecognized asan audio interfaceallowingstreamingaudio to be read, output or analyzed and processed USBMSD Emulates a mass storage device over USB, allowing interaction with a USB storage device 12.4 Introducing Ethernet 12.4.1 Ethernet Overview Ethernet is a serial protocol which is designed to facilitate network communications. Any device successfully connected to the Ethernet can potentially communicate with any other device connected to the network. 256 Chapter 12 Networks are often described as being one of two types: • local area network (LAN) e usually for devices connected together in close proximity, perhaps in the same building and often without Internet access • wide area network (WAN) e describes a network of devices over a greater geographical area, usually connected by the Internet. Ethernet communications are defined by the IEEE 802.3 standard (see Reference 12.5) and support data rates up to 100 Gigabits per second. Ethernet uses differential send (Tx) and receive (Rx) signals, resulting in four wires labeled RXþ , RX , TXþ and TX . Ethernet messages are communicated as serial data packets referred to as frames. Using framesallowsasinglemessageto holdanumberof datavaluesincludingavaluedefiningthe length of the data packet as well as the data itself. The Ethernet frame therefore defines its own size, which means that only the necessary amount of data is communicated, with no wasted or empty data bytes. Ethernet communications need to pass a large quantity of data at high rates, so data efficiency is a very important aspect. The use of frames allows an efficient method. Each frame also includes a unique source and destination MAC address. The frame is wrapped within a set of preamble and start of frame (SOF) bytes and a frame check sequence (FCS), which enables devices on the network to understand the function of eachcommunicateddataelement. Thestandard802.3Ethernetframeisconstructedasshown in Table 12.3. The minimum Ethernet frame is 72 bytes; however, the preamble, SOF and FCS are often discardedonceaframehasbeensuccessfully received. So a72-bytemessagecanbereported as having just 60 bytes by some Ethernet communications readers. The Ethernet data takes the form of the Manchester encoding method, which relies on the directionof theedgetransitionwithinthetimingwindow, asshowninFigure12.5. If theedge transitionwithinthetimingframeishighto low, thecodedbit isa0; if thetransitionislowto high then the bit is a 1. The Manchester protocol is very simple to implement in integrated circuit hardwareand, asthereisalwaysaswitchfrom0to 1or1to 0forevery datavalue, the clock signal is effectively embedded within the data. As shown in Figure 12.5, even when a stream of zeros (or ones for that matter) is being transmitted, the digital signal still shows transitions between high and low states. Table 12.3: Ethernet frame structure Preamble 7 e bytes of 10101010 Start of frame Destination Source MAC delimiter MAC address address Length 1 byte of 10101011 6 bytes 6 bytes 2 bytes Data 46 e 1500 bytes Frame check Interframe sequence gap 4 bytes Advanced Serial Communications 257 Figure 12.5: Manchester encoding for Ethernet data 12.4.2 Implementing Simple mbed Ethernet Communications The mbed Ethernet API is shown in Table 12.4. We can set up an mbed Ethernet systemto send data and evaluate this on a logic oscilloscope to verify the Ethernet frame structure. Here, we are not initially concerned with the specific MAC addresses of sending or receiving devices, we simply want to send some known data and see it appearing on the logic scope. Table 12.4: The mbed Ethernet API Function Usage Ethernet Create an Ethernet interface write Writes into an outgoing Ethernet packet send Send an outgoing Ethernet packet receive Receives an arrived Ethernet packet read Read from a received Ethernet packet address link Gives the Ethernet address of the mbed Returnsthevalue1 if an Ethernet link ispresent and 0 if no link ispresent set_link Sets the speed and duplexparameters of an Ethernet link 258 Chapter 12 ProgramExample12.7sendstwo databytesevery 200msfromanmbed’sEthernetport. The two byte values are arbitrarily chosen as 0xB9 and 0x46. /* Program Example 12.7: Ethernet write */ #include "mbed.h" #include "Ethernet.h" Ethernet eth; // The Ethernet object char data[]={0xB9,0x46}; // Define the data values int main() { while (1) { eth.write(data,0x02); // Write the package eth.send(); // Send the package wait(0.2); // wait 200 ms } } Program Example 12.7 Ethernet write Figures12.6and12.7showdetailedanalysisof thedatapacketonafastlogicanalyzer(i.e. an oscilloscopethat canmeasureat speeds of around10Gbps). Thenoisecaneasily beseenbut theoscilloscopeaccurately convertstheEthernet signal to anidealizeddigital representation. In Figure 12.6, the 7-byte preamble and SOF data are identified. The preamble and SOF delimiter are followed by destination and source MAC addresses (6 bytes each) and the 2 bytes denoting the data length, which is a minimumof 46 bytes (as described in Table 12.3). Note that even though in this example we have only sent two data bytes, theminimumdatasizeof 46bytes is sent. Theremaining44databytes aremadeupof empty (0x00) data, being followed by the four frame check sequence bytes. (This is not a particularly efficient use of Ethernet, which is usually required to send large data packets.) Looking at the end of the data packet, shown in Figure 12.7, we can also see the final zero padded data and the FCS data. Figure 12.6: Ethernet packet showing preamble and SOF data Advanced Serial Communications 259 Figure 12.7: Padded Ethernet data and frame check sequence n Exercise 12.6 Using a fast logic oscilloscope, identify the data making up the 0xB9 0x46 data values transmitted in Program Example 12.7. Experiment with different data values and array sizes, ensuring that each time the correct binary data can be observed on the oscilloscope. n 12.4.3 Ethernet Communication between mbeds An mbed Ethernet port can be used to read data. We can use the simple Ethernet write program of Program Example 12.7. We will also need a second mbed system to receive incomingdataanddisplay itto thehostterminal screen, inordertoverify thatthecorrectdata is being read. The following program will allow an mbed to read Ethernet data traffic and display the captured data on the screen. /* Program Example 12.8: Ethernet read */ #include "mbed.h" Ethernet eth; // Ethernet object Serial pc(USBTX, USBRX); // tx, rx for host terminal coms char buf[0xFF]; // create a large buffer to store data int main() { pc.printf("Ethernet data read and display\n\r"); while (1) { 260 Chapter 12 int size = eth.receive(); if (size > 0) { eth.read(buf, size); pc.printf("size = %d data = ",size); for (int i=0;i<size;i++) { pc.printf("%02X ",buf[i]); } pc.printf("\n\r"); } // // // // // // get size of incoming data packet if packet received read packet to data buffer print to screen loop for each data byte print data to screen } } Program Example 12.8 Ethernet read Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 Figure 12.8: mbed-to-mbed Ethernet wiring diagram Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 mbed Microcontroller Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller Note that Program Example 12.8 first defines a large data buffer to store incoming data. During the infinite loop the programuses the eth.receive( ) function to evaluate the size of any Ethernet data traffic. If the data packet has a size greater than zero then it must be an Ethernet packet, so the display loop is entered. The size of the data package along with the read data is then displayed to the host terminal. To communicate successfully between the two mbeds, a crossed signal connection is required, as shown in Figure 12.8 and Table 12.5. Advanced Serial Communications 261 Table 12.5: mbed-to-mbed Ethernet wiring table Data broadcasting mbed Data receiving mbed RD TD RDþ TDþ TD RD TDþ RDþ Figure 12.9: Ethernet data successfully communicated between two mbeds and displayed on a host PC TheEthernet-writembedshouldrunProgramExample12.7, andthedata-receivingmbedruns 12.8. This is connected to Tera Term running on the host computer. When successfully completed, thehost PC terminal applicationshoulddisplay Ethernet datasimilarto that shown inFigure12.9. Notethat eventhoughonly two databytes weretransmittedthesizeof thedata packagereceivedis 60bytes, whichis theminimumEthernet datapackagesize(72) minusthe preamble, SOF and FCS bytes, which are of no real value once the message is received. n Exercise 12.7 Experiment with different datavaluesand arraysizes, ensuringthat each timethecorrect binary data can be read by the host PC application. n 12.5 Local Network and Internet Communications with the mbed It is possible to use the mbed as a network-enabled system, i.e. for both LAN and WAN communications. The remaining sections of this chapter show some examples of the mbed being used to access online files, to host files itself, and to communicate data and control actions through local networks and the Internet. We must, however, advise you of the challengesassociatedwithcoveringsuchavasttopic inthisbook. Itisimportantto showcase the power and ability of the mbed, but in many cases here this relies on a very wide set of 262 Chapter 12 knowledge and skills related to Internet and network theory, as well as software engineering in other languages. So from here onwards in this chapter we will give some interesting examples but without the capability to evaluate them or their underpinning technologies in depth. Further support information is provided on the book website to assist with compiling and completing the Internet communications examples. The Internet has transformed worldwide communications over the past 20 years, but rather thanbeingjustasimplenetworkforsharingonlineinformationandcommunicatingviaemail, the Internet nowadays facilitates advanced interactive applications. The mbed compiler, for example, is accessed entirely through the Internet, which means that no additional software needstobeinstalledforadevelopertoworkwiththembed. This, furthermore, facilitatescloud computingbecausethembedprogramsarestoredonadataserverwhichisheldandmanaged by ARM. This means that it is no longer the user’s responsibility to back up data, and developerscanworkonprojectsfromany locationintheworldwithouttheneedtocarry local copies of files and programs. This also helps with version control as there is only ever one versionof aspecific project, so thereis less risk of someoneworkingonanoutdatedversion. Developers can download and archive their programs locally too. With extended bandwidth and rapid data rates provided by the Internet, it is possible to keep communications open continuously and to streamdata while still allowing multi-tasking of otheronlineactivities. It ispossiblenowadaysto link small embeddedsystemsto theInternet andhencetonetworkdevicesthatareunderembeddedcontrol. Oncethelinkisthere, itcanbe used for many things: to monitor status or exert control, or even to cause programor data downloads. Examplesincludethewashingmachinethatcanalerttheengineertoanimpending fault, thevendingmachinethatcantell theHeadOfficeit isempty, themanufacturerwho can downloadanewversionof firmwaretoaninstalledburglaralarm, orthehomeownerwhocan switch on the oven fromthe office or check that the garage door is closed. 12.5.1 Using the mbed as an HTTP Client Several mbedlibraries exist to allow network communications. It is possibleto usethembed asanHTTP(hypertexttransferprotocol) clientinordertoaccessdatafromtheInternet. Todo this we rely on the network interface libraries as shown in Table 12.6. A standardEthernet socket (RJ45) isrequiredto connect thembedEthernetport to anetwork huborrouter. TheSparkfunEthernetbreakoutboard(Reference12.6) isusedinthisexample and can be connected to the mbed as shown in Figure 12.10. ProgramExample12.9enablesthembedtoconnecttoaremote(online)textfileandaccessatext stringfromwithinthat file. Thefileis storedat http://www.embeddedacademic.com/mbed/ mbedclienttest.txt. Youcanverify that it exists by accessingit throughastandardInternet browser. Advanced Serial Communications 263 Table 12.6: Network interface libraries for HTTP client operation Mbed library Library import path EthernetIF http://mbed.org/users/donatien/programs/EthernetNetIf/5z422 HTTPClient http://mbed.org/users/donatien/programs/HTTPClient/5yo73 Figure 12.10: RJ45 Ethernet connection for mbed /* Program Example 12.9: mbed HTTP client test */ #include "mbed.h" #include "EthernetNetIf.h" #include "HTTPClient.h" EthernetNetIf eth( IpAddr(192,168,0,101), //IP Address IpAddr(255,255,255,0), //Network Mask IpAddr(192,168,0,1), //Gateway IpAddr(192,168,0,1) //DNS ); HTTPClient http; HTTPText txt; Serial pc (USBTX,USBRX); int main() { pc.printf("\r\nSetting up network connection. \n\r"); eth.setup(); pc.printf("\r\nSetup OK. Querying data. \r\n"); // attempt to access file ‘mbedclienttest.txt’ through the Internet. HTTPResult r=http.get("http://www.embeddedacademic.com/mbed/mbedclienttest.txt", &txt); pc.printf("Result :\n\r\"%s\"\n\r", txt.gets()); } Program Example 12.9 mbed HTTP client test 264 Chapter 12 Figure 12.11: Host terminal results for client test program Table 12.7: Network interface libraries for HTTP server operation Mbed library Library import path EthernetIF http://mbed.org/users/donatien/programs/EthernetNetIf/5z422 HTTPServer http://mbed.org/users/donatien/programs/HTTPServer/5yhmt Note that the unique Internet protocol (IP) address for the mbed is set in the EthernetIF declaration; in this example it is chosen as 192.168.0.101. Predominantly, LANs use an IP with a default address of 192.168.0.0 and the router on that network will usually take the default address or the next availablevalue above the default address (i.e. 192.168.0.1). Each system on the network needs its own unique IP address based on this default, so the chosen value of 192.168.0.101 is unlikely to clash with any other network systems (unless there are more than 100 other systems). When the mbed is connected to an active Internet connection the messages shown in Figure 12.11 should be displayed on a host PC terminal application. 12.5.2 Using the mbed as an HTTP File Server As well as accessing files on an external server, we can use the mbed to host files to be accessedfromaremotePC. Forthis weneedto import andutilizethembedlibrariesdetailed in Table 12.7. Program Example 12.10 sets up the mbed as a file server. /* Program Example: 12.10 mbed file server setup */ #include "mbed.h" #include "EthernetNetIf.h" #include "HTTPServer.h" LocalFileSystem fs("webfs"); EthernetNetIf eth( IpAddr(192,168,0,101), //IP Address Advanced Serial Communications 265 IpAddr(255,255,255,0), //Network Mask IpAddr(192,168,0,1), //Gateway IpAddr(192,168,0,1) //DNS ); HTTPServer svr; int main() { eth.setup(); FSHandler::mount("/webfs", "/"); //Mount webfs path on root path svr.addHandler<FSHandler>("/"); //Default handler svr.bind(80); while(1) { Net::poll(); // poll for Internet data exchange requests } } Program Example 12.10 mbed file server setup Notice the important lines, which initialize the Cþ þ server handler routines: FSHandler::mount("/webfs", "/"); svr.addHandler<FSHandler>("/"); svr.bind(80); //Mount webfs path on root path //Default handler Also notice the Net::poll(); line, which continuously polls the network in order to respond whenever an external request to access the mbed server arrives. We need to create a text file to save onto the mbed, so that we can access it fromthe remote Internet browser. Create a .htm file called, for example, HOME.HTM and enter some exampletext, so that youwill knowwhentheInternet browserhascorrectly accessedthefile. An example is shown in Figure 12.12. Create this file in a standard text editor and save it to the mbed via the standard USB cable connection. Notethatthembedserverlibrariesonly supportMS-DOS8.3typefilenames. Youwill beable to access the mbed server from a remote browser by navigating to the specific IP address and webpage, in this example by entering the following address: http://192.168.0.101/HOME.HTM Figure 12.12: HOME.HTM file to be stored on the mbed server and remotely accessed 266 Chapter 12 We can now access the HOME.HTM file (stored on the mbed) from any other computer connected to the LAN. To do this we just need to open a web browser application (such as Internet Explorer) on a connected PC, and type in the navigation address shown above. Successful navigationtothisnetworkaddressshouldbringupthe.htmtextascontainedinthe HOME.HTM file. 12.5.3 Using Remote Procedure Calls to Modify mbed Outputs Remoteprocedurecalls(RPCs) definetheprocesswhereanactiononadeviceorcomputeris controlled from a remote location. Essentially, this means that, for example, RPCs can be made fromanetwork PC to switchthe mbed’s LEDs onandoff. Indeed, many of thembed’s outputs can be controlled and accessed by RPC calls from a remote network PC (see Reference 12.7). The mbed HTTPServer library supports this operation. The key aspects for RPC control on the mbed are: • Set up an mbed file server as described in Sections 12.5.1 and 12.5.2 above. • Define mbed interfaces in the extended format with the ‘name’ defined within, e.g. DigitalOut led1(LED1, "led1"); • MaketherequiredmbedinterfacesavailableoverRPC by addingtheRPC basecommand, e.g. Base::add_rpc_class<DigitalOut>(); • Define the RPC Handler, e.g. svr.addHandler<RPCHandler>("/rpc"); • Manipulate mbed interfaces remotely by using the following browser address format: http://<mbed-ip-address>/rpc/<Object name>/<Method name> <Value> If wetakeProgramExample12.10andapply therequiredRPC features describedabove, we arrive at Program Example 12.11. This enables remote control of a DigitalOut object assigned to the onboard LED1: /* Program Example 12.11 Remote */ #include "mbed.h" #include "EthernetNetIf.h" #include "HTTPServer.h" LocalFileSystem fs("webfs"); EthernetNetIf eth( IpAddr(192,168,0,101), IpAddr(255,255,255,0), IpAddr(192,168,0,1), IpAddr(192,168,0,1) ); Procedure Calls example //IP Address //Network Mask //Gateway //DNS Advanced Serial Communications 267 HTTPServer svr; DigitalOut led1(LED1, "led1"); int main() { Base::add_rpc_class<DigitalOut>(); eth.setup(); FSHandler::mount("/webfs", "/"); svr.addHandler<FSHandler>("/"); svr.addHandler<RPCHandler>("/rpc"); svr.bind(80); while(1) { Net::poll(); } } // define mbed object // RPC base command // Ethernet setup // Mount /webfs path on root //Default handler // Define RPC handler Program Example 12.11 Remote procedure calls example Thevalue of the mbed led1 object can now be changed via a web browser on a network PC, i.e. remotely. This is done by entering into a web browser the RPCs as shown in Table 12.8. n Exercise 12.8 Implement a programto enablemanipulation of a pulsewidth modulation (PWM) duty cycle by an RPC command. You will need to define a PWM object with the extended format, for example: PwmOut pulse(p21, "pulse"); You will also need to include the PWM RPC base command as follows: Base::add_rpc_class<PwmOut>(); Set the PWM period at the start of the program and check that the duty cycle, as observed on an oscilloscope, can be manipulated remotely. Connect thePWM output to a servo motor and show that theservo motor position can be controlled by RPC commands. n 12.5.4 Controlling the mbed using a Remote JavaScript Interface Manipulating mbed objects by entering address commands in the Internet browser is not an ideal methodforcommunicatingwiththembedonanetwork. Itisslowto typethecommand, Table 12.8: Commands for RPC control of mbed LED1 Action Remote procedure call Remotely switch led1 ON http://192.186.0.101/rpc/led1/write 1 Remotely switch led1 OFF http://192.186.0.101/rpc/led1/write 0 268 Chapter 12 Table 12.9: RPC library and header file details Mbed library Library import path Header files to include RPCInterface http://mbed.org/users/MichaelW/ libraries/RPCInterface/likpmz “RPCVariable.h”, “SerialRPCInterface.h” easy to enter thewrong address and not user intuitive. A better solution is to use a graphical user interface (GUI) with buttons and displays to allow manipulation and control of mbed objects. Itisalsouseful tobeableto display thestatusof mbedobjectsonawebpage, to allow remote monitoring. The mbed JavaScript interface (described in more detail at Reference 12.8) allows communicationbetweenthembedandaJava-enabledbrowser, usingtheRPC protocol. This type of program requires the library shown in Table 12.9 to be imported and the described header files also to be included in the project. ProgramExample12.12setsuptwo RPC variables, oneto holdLED statusdataandtheother to receive remote button-press data. /* Program Example 12.12 Using RPC variables for remote mbed control */ #include "mbed.h" #include "EthernetNetIf.h" #include "HTTPServer.h" #include "RPCVariable.h" #include "SerialRPCInterface.h" LocalFileSystem fs("webfs"); EthernetNetIf eth( IpAddr(192,168,0,101),//IP Address IpAddr(255,255,255,0),//Network Mask IpAddr(192,168,0,1), //Gateway IpAddr(192,168,0,1) //DNS ); HTTPServer svr; DigitalOut Led1(LED1); // define mbed object DigitalIn Button1(p21); // button int RemoteLEDStatus=0; RPCVariable<int> RPC_RemoteLEDStatus(&RemoteLEDStatus,"RemoteLEDStatus"); int RemoteLED1Button=0; RPCVariable<int> RPC_RemoteLED1Button(&RemoteLED1Button,"RemoteLED1Button"); int main() { Base::add_rpc_class<DigitalOut>(); eth.setup(); FSHandler::mount("/webfs", "/"); svr.addHandler<FSHandler>("/"); svr.addHandler<RPCHandler>("/rpc"); // // // // // RPC base command Ethernet setup Mount /webfs path root path Default handler Define RPC handler Advanced Serial Communications 269 svr.bind(80); printf("Listening. \n"); while (true) { Net::poll(); if ((Button1==1)j(RemoteLED1Button==1)) { Led1=1; RemoteLEDStatus=1; } else { Led1=0; RemoteLEDStatus=0; } } } Program Example 12.12 Using RPC variables for remote mbed control The RPC variables are created by the following lines of code: int RemoteLEDStatus=0; RPCVariable<int> RPC_RemoteLEDStatus(&RemoteLEDStatus,"RemoteLEDStatus"); int RemoteLED1Button=0; RPCVariable<int> RPC_RemoteLED1Button(&RemoteLED1Button,"RemoteLED1Button"); It canbeseeninProgramExample12.12 that if thepush-buttonconnectedto mbedpin21is pressed, LED1 is lit. The RPC variable RemoteLED1Button can also activate LED1, however, if it becomes set. Furthermore, the RPC variable RemoteLEDStatus is set to maintain the same value as LED1. A Javaapplication(aJ avaApplet) canbebuiltandlinkedtoa.htmfile, whichisservedby the mbed. The.htmfilegeneratesthewebpageshowninFigure12.13whenaccessedonthembed by a remote browser. Creating the .htmfile and Java application code is outside the scope of this book; however, these specific examples can be downloaded from the book website to allow you to implement the example. In this example, the small LED graphic will always be in the same state as LED1 on the mbed. Figure 12.13: Remote interface Java Applet: LED1 ¼off 270 Chapter 12 Figure 12.14: Remote interface Java Applet: LED1¼on If the user performs a mouse click within the button area on the webpage, the mbed’s LED1 will also toggle. This is because within the Java Applet it is possible to connect the user mouse click action to the RPC variable named RemoteLED1Button. Clicking the button area on the webpage sends RemoteLED1Button high and hence causes the if statement in Program Example 12.12 to be entered, lighting the LED on the mbed. Whenever LED1 on the mbed is lit, the LED indicator displayed on the Java webpage becomes filled in, as shown in Figure 12.14. This is because the Java Applet is capable of usingaconditional drawingcommandto fill theLED indicatorwheneverRemoteLEDStatus is set high. Here, we are now controlling the mbed LED1 output by a remote web application, and the JavaApplicationalso maintains acorrect status indication of thembed’s LED. This example is quitecomplex andprogrammingskillswithC/Cþ þ , HTML andJava, beyondthescopeof this book, are required to build on this example. This does, however, serve as an example of the power of the mbed as a device which can be uniquely accessed and controlled through networks and the Internet. Chapter Review • A number of serial communications protocols exist, each with its advantages and disadvantagesandeachaimedat specific applications. TheseincludeUART, SPI, I2C, USB and Ethernet. • Bluetooth communications allow standard serial messages to be communicated in a wireless manner. • The USB protocol is designed specifically for allowing plug-and-play communications between a computer and peripheral devices such as a keyboard or mouse. • There are several mbed USB libraries allowing the mbed to operate as a mouse or a keyboard, or as an audio or MIDI interface, for example. Advanced Serial Communications 271 • Ethernet is a high-speed serial protocol which facilitates networked systems and communications between computers, either within a local network or through the World Wide Web. • The mbed can communicate through Ethernet to access data from files stored on a data server computer. • Thembedcanbeconfiguredto act as anEthernet fileserveritself, allowingdatastoredon the mbed to be accessed through a network. • Thembed RPC interfaceand libraries allow variables and outputs to be manipulatedfrom an external remote interface, written in Java, for example. Quiz 1. 2. 3. 4. 5. 6. What is the communication range of a Class 1 Bluetooth device? What does the term MAC address refer to? What does MIDI stand for, and how is this relevant to USB communications? What is the MIDI note value for C2 (fundamental frequency of 65.3Hz)? Describe the Manchester digital communication format for Ethernet signals. Sketch the following Ethernet data streams, as they would appear on an analog oscilloscope, labeling all points of interest: (a) 0000 (b) 0101 (c) 1110 7. What are the minimum and maximum Ethernet data packet sizes, in bytes? 8. Draw a table listing the advantages and disadvantages of using USB or Ethernet for communicating between two mbeds. 9. What does the term RPC refer to? References 12.1. The official Bluetooth website. http://www.bluetooth.com 12.2. Roving Networks Advanced User Manual. Version 4.77, 21 November 2009. rn-bluetooth-um 12.3. Universal Serial Bus Specification, Revision 2.0. April 2000. Compaq, Hewlett-Packard, Intel, Lucent, Microsoft, NEC, Philips. 12.4. Summary of MIDI Messages. http://www.midi.org/techspecs/midimessages.php 12.5. Ethernet Working Group. IEEE 802.3. http://www.ieee802.org/3/ 12.6. Breakout Board for RJ45. http://www.sparkfun.com/products/716 12.7. Interfacing Using RPC. http://mbed.org/cookbook/Interfacing-Using-RPC 12.8. Interfacing with JavaScript. http://mbed.org/cookbook/Interfacing-with-JavaScript CHAPTER 13 An Introduction to Control Systems Chapter Outline 13.1 Control Systems 273 13.1.1 Closed and Open Loop Control Systems 274 13.1.2 Closed Loop Cruise Control Example 275 13.1.3 Proportional Control 276 13.1.4 Proportional Integral Derivative Control 278 13.2 Closed Loop Digital Compass Example 280 13.2.1 Using the HMC6352 Digital Compass 281 13.2.2 Implementing a 360 Degree Rotation Servo 283 13.2.3 Implementing a Closed Loop Control Algorithm 285 13.3 Communicating Control Data over the Controller Area Network 288 13.3.1 The Controller Area Network 288 13.3.2 CAN on the mbed 289 Chapter Review 294 Quiz 294 References 295 13.1 Control Systems We havealready implemented a number of electromechanical control systems, which can be broadly defined as electronic and/or software systems that ar e designed to control a designated physical variable. For example, in Chapter 4 we discussed a systemthat moved a servo to a desired position by applying the correct pulse width modulation (PWM) waveform. Electromechanical control systems are very common, with applications ranging from home and office equipment, to industrial machinery, automotivevehicles, robotics and aerospace. Think of how much control there must be in a humble inkjet printer: drawing in and guiding the paper, shooting the print cartridges backwards and forwards with extraordinary precision, and squirting just the right amount of ink, of the right color, in just the right place. The accuracy of a control system is a very important aspect, as errors and inaccuracy can have significant relevance to performance, wear and safety. The whole topic of control systems is a very detailed and broad field, which draws on advanced mathematical theory as well as electronics, digital communications, applied Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00013-1 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 273 274 Chapter 13 mechanics, and sensor and actuator design. It is not possible to give a thorough insight into control systems in this book, but the mbed is a valuable device which can be used to implement some simple control algorithms and communication methods. This chapter thereforeacts as astartingpoint forthe readerwho may wish to go onto study orimplement control systems at a later date. 13.1.1 Closed and Open Loop Control Systems Closed loop control systems employ internal error analysis to achieve accurate control of actuators, given continuous sensor input readings. For example, this means that the system measures the position of an actuator, compares it with a signal representing the position it is meantto beat(calledthesetpoint), andfromthisinformationtriesto movetheactuatorto the correct position. The fundamental components of a closed loop system are therefore an actuator, whichcausessomeformof action; asensor, whichmeasurestheeffectof theaction; and a controller, to compute the difference between setpoint and actual position. Although wesay position, any physical variablecanbecontrolled. Forexample, aheaterelementmight be used to heat an oven to a specified temperature and a temperature sensor used to measure the actual heat of the oven. If the closed loop controller tells the oven to be at 200 C then the heater will provide heat until the sensor signals the controller that 200 C has been achieved. If the sensor measurement shows that the actuator has achieved its desired action (i.e. 200 C is achieved), then the error between the desired setpoint and the actual reading is zero and no further action is required. If, however, the sensor reads that the desired action has not been achieved (e.g. the temperature is only 190 C), then the control system knows that more action is required to meet the desired setpoint. Anopenloopcontrol systemis onethat employsno analysis sensorandrelies onacalibrated actuator setting to achieve its desired action. For example, a 5V electric motor might rotate at different speeds over the voltage input range, say 0V gives 0 revolutions per second (rps) and 5V gives 100rps. If we want to rotate the motor at 50rps we might simply assume thattheresponsecharacteristicof themotorislinear(orhaveacalibratedlook-uptableforits response profile) and provide 2.5V. However, we will not actually know if the motor is rotating at the desired speed; for different operating temperatures, with different friction loading and with component drift over time, the speed achieved given 2.5V input cannot be accurately predicted. Here, an improved closed loop system with a speed sensor could be used to modify the input voltage and ensure that an accurate 50rps is achieved. Advantages of closed loop systems are improved accuracy of a controlled variable and the ability to automatically makecontinuousadjustment. Infact, many actuators arequiteerratic and non-linear in terms of performance, so in many cases closed loop control is a necessity rather than a desire. Closed loop systems built around fast microcontrollers can also allow advanced control of systems that were previously thought uncontrollable. For example, the An Introduction to Control Systems 275 Figure 13.1: The Segway personal transporter (www.segway.com). (Imagereproduced with permission of SegwayInc.) Segway personal transportation systems (Figure 13.1, Reference 13.1) use sensitive gyroscopes to ensure that the standing platform always remains horizontal. If weight shifts forward (and the gyroscope shows an imbalance) then the motor in the wheels moves forwards marginally to compensate and stops moving when a horizontal position has been achieved again. The microcontroller, sensors and actuators inside read and compute so rapidly that this process can be performed faster than a human’s motion can displace their weight, so the controller can always ensure that the platform stays stable. 13.1.2 Closed Loop Cruise Control Example Anotherexample of closed loop control is cruisecontrol inmany automotivevehicles. Here, thedriverchoosesadesiredspeedandthevehicleautomatically maintainsthatspeeduntil the driver disables the mode, either by switching it off or by applying the brake. A key point to noteis that theactuatorperformsadifferent operationfromthespecific sensor reading that is being used for comparison with the setpoint. For example, the setpoint might be a vehicle speed of 80kph, but the actuator is actually the electronic throttle valve, which determinestheamountof airandhencefuel thatisdrawnintotheengineoneachpistoncycle. So a complex chain of events occurs, from automatically moving the throttle, to sucking air and fuel into the engine, engine combustion, torque being applied to the wheels, the vehicle moving, and the vehicle motion finally being measured and converted to a horizontal speed value in kph. Many factors affect the accuracy of this process, for example changes in air pressure, fuel type, engine wear, tire size and tire pressure, as well as road friction and 276 Chapter 13 environmental factors suchas dragandgravity. Anopenloopsystemcouldneverbepossible for cruise control. A closedloopcontrol systemcanbequitesimple. All weneedto do, givenamicroprocessorbased system, is to writeacontrol algorithmwhichtakes asetpoint (desiredspeed chosenby the driver) and calculates the error between the setpoint and the actual speed. The algorithm then uses this error to calculate the required action. For example, if the error is negative (actual speedis less thanthedesiredsetpoint) thentheactionmust bepositiveto increasethe amount of fuel to the engine, increase the torque to thewheels and increase the car speed. If the error is positive, then the action must be negative, to reduce the car speed to the setpoint. Theuseof negativefeedback, wherethemeasuredpositionissubtractedfromthesetpoint (in order to calculate the error), is therefore found in most closed loop control algorithms. The mechanical system, between the actuator and the sensor, involves a chain of events with an inherent response time. For a cruise control system, the response time is the time it takes for anincreaseinfuel injectedto the engineto causeanincrease inspeedof thevehicle e in some cases this might be of the order of seconds, or at least hundreds of milliseconds. The slow response time can cause problems for an automatic control system, because once the desired setpoint is achieved, it is likely to overshoot. With cruise control, once the desired speedhasbeenachieveditwill takeasmall amountof timefortheengineto reduceitstorque output (as fuel will already have been injected into the engine), so the controller could overshoot andcauseanerrorintheoppositedirection. Thecontrollerwill automatically then attempt to reversetheactionandreducetheerrorback towardszero again, butmay overshoot in the opposite direction too. In a poorly designed cruise control system the controller may never even achieve a satisfactory and steady 80kph as desired by the driver. Indeed, the system may oscillate continuously between, say, 78 and 82kph, which would be an unpleasant driving experience. It follows that the performance of the control system depends on the effectiveness of the control algorithmemployed. Designandtuningof thecontrol algorithmisadelicateprocess, requiring knowledge of the system characteristics and usually experimental testing to understand response times. When final calibration is performed effectively, however, very stable and responsive control systems can be developed. 13.1.3 Proportional Control The simplest form of closed loop control uses a proportional algorithm to form a linear relationship between the measured error and the actuator control. Figure 13.2 describes the electromechanical process of a closed loop cruise control system. The driver tells the microcontroller the speed at which they would like the vehicle to cruise. At the same time, the actual vehicle speed is calculated from a wheel speed sensor reading. The speed An Introduction to Control Systems 277 Figure 13.2: Closed loop cruise control example. PWM: pulse width modulation; ADC: analog-to-digital converter setpoint is compared to the actual vehicle speed to calculate the error, which is then multiplied by a calibrated value K. The calculated value is then used to set a PWM output of the microcontroller, and there may be a conversion look-up table here to ensure that a suitable PWM output is set. The PWM output controls a solenoid, which can move the engine’s throttle position. The position of the throttle valve determines how much air and fuel are drawn into the engine, and hence the amount of torque or power generated. The engine torque, via the vehicle gearbox, determines how much power is delivered to the wheels, which subsequently dictates the speed of the vehicle. If a setpoint is chosen then, with a continuously sampling microcontroller, the control loop will automatically selfadjust so that a speed error of zero is achieved. In reality, a zero error is not quite achieved, but the control loop will get as close as possible. If suddenly the setpoint is changed, for example from 80kph to 90kph, there is as an immediate step change in the setpoint. It will take some time for the vehicle to speed up to the new setpoint, and the time taken for the step response is dependent on a number of factors. It will depend predominantly on the value of K, the physical response time of the mechanical system and the speed of the microprocessor software loop. 278 Chapter 13 Figure 13.3: Proportional control system Figure13.2also showstheelementsof theelectronic control system(i.e. themicrocontroller) andthemechanical system, whichissometimesreferredto asaplant. Inmany casestheplant itself is modeled mathematically and implemented in another microcontroller, so that engineers can test their control algorithm in simulation before implementing it on a real vehicle. A moregeneral representationof theclosed loopcontrol systemis shownin Figure13.3. We can see that when the error is positive (i.e. the measured value is above the setpoint), the control value is reduced (owing to negative feedback) and vice versa for negative errors. Furthermore, whentheerrorislarge, thecontrol valueischangedby alargeamount; whenthe error is small, the control value is adjusted by only a small amount. The value of the gain determines how quickly the system responds to errors. Thefactthatthecontrol valueisalteredproportionally isagoodthingwhentheerrorislarge; however, this causes problems when the error is small. As the error gets smaller, the control value adjustment get smaller too, which results in the desired setpoint never actually being achieved. With proportional only control there is always therefore a steady-state error. The steady-state error can be reduced by making the gain larger, but unfortunately this could easily result in overshoot and a longer settling period, and even continuous instability if the gainistoo high. Figure13.4showsanexamplestepresponseof aproportional control system with high and low gain values. To overcome this error with controlled overshoot and stability it is necessary to add integral and derivative terms to the control algorithm. 13.1.4 Proportional Integral Derivative Control Proportional integral derivative(PID) control is similarto proportional control, but with the addition of algorithm components relating to the integral and derivative values of the error An Introduction to Control Systems 279 (a) (b) 1.8 1.8 1.6 response 1.4 1.4 1.2 1.2 amplitude amplitude 1.6 1 0.8 input 0.6 1 0.8 0.6 0.4 0.4 0.2 0.2 0 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 0 response input 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 time (s) time (s) Figure 13.4: Step response with (a) high proportional gain; (b) low proportional gain data. This adds an element of history to the algorithm, rather than it being responsive to the current error value alone. A PID control system is shown in Figure 13.5. Figure13.6 shows that theerroris integrated andmultipliedby anintegral gainvalueas well as differentiated and multiplied by a differential gain. These are then summed together with the proportional gain term to give a control value which takes into account not only Figure 13.5: PID control system 280 Chapter 13 1.8 1.6 1.4 amplitude 1.2 1 0.8 0.6 response input 0.4 0.2 0 0 0.2 0.4 0.6 0.8 1 time (s) 1.2 1.4 1.6 1.8 2 Figure 13.6: PID controller tuned to give step response with low overshoot and low steady-state error current position, but also the rate of change of the position and the longer term history of change. Nowthetuningof thesystembecomes even morecomplex, but theresults can bean accurate control system with low steady error and low overshoot. The gain terms can be calculated by experimentation and by employing software tools. Complex mathematical methods can help to determine the best PID gain values (see Reference 13.2, for example), althoughsomefinemanual tuningis oftenrequiredalso. Figure13.6shows thestepresponse of aPID control systemwhichhas its gainvalues tuned to giveafast responsetimewith low overshoot and low steady-state error. 13.2 Closed Loop Digital Compass Example A closedloopsystemrequiresasensorandanactuator,whereby thesensor’spositionorstateis altered by the actuator’s action. A simple practical example is that of a digital compass integrated circuit chip, positioned onaservo. As the servo rotates, thecompass readings will alteraccordingly.Wecandesignaclosedloopsystemtoautomaticallyadjusttheservoposition to a desired compass reading and use a simple algorithmto ensure accurate positioning and smooth movement. Implementing a full PID closed loop controller is rather complex and outside the scope of this book. However, it is possible to implement a simple proportional control algorithmfor the purpose of introducing closed loop control on the mbed. Inthis example, wewill use thembedwithanHMC6352 digital compass modulewitha360 degreerotationservo. Youwill also need a6V battery supply fortheservo. It is important to An Introduction to Control Systems 281 Figure 13.7: Closed loop compass system think carefully about connections and wiring to ensure that the wires do not become tangled as the servo rotates. The compass sensor also needs to be kept as far away as possible from any unwanted magnetic fields. An example test setup is shown in Figure 13.7. 13.2.1 Using the HMC6352 Digital Compass Honeywell’sHMC6352compassisanotherhighly integratedsensor, similarinconceptto the ADXL345 accelerometer and TMP102 temperature sensor introduced in Chapter 7. Fully integrated onto a single integrated circuit (IC), it contains sensors, signal conditioning, microprocessorandinter-integratedcircuit(I2C) serial interface. Thetwo sensors, mountedat right angles to sense the components of the surrounding magnetic field, are based on the magnetoresistive principle. This relies on the fact that the apparent resistance of a conductor canbeseento changeinthepresenceof amagnetic field. Weuseit onatiny breakout board, as shown in Figure 13.8. Full information is given in Reference 13.3. Figure 13.8: HMC6352 mounted on a breakout board. (Image reproduced with permission of Sparkfun Electronics) 282 Chapter 13 Table 13.1: Pin connections for HMC6352 digital compass HMC6352 pin mbed pin 2 SCL (I C) 27 SDA (I2C) 28 VCC (3.3 V) 40 GND (0 V) 1 The HMC6352 compass can be connected to the mbed via an I2C interface, as described by the pin connections in Table 13.1. Before building a complete system, we will first write a program to ensure that the compass initializes and reads data correctly. As detailed in the HMC6352 datasheet (Reference 13.3), the base address for the compass is 0x42. The datasheet also describes that in order to initialize the IC we write an ASCII ‘G’ (0x47) commandto informthedevicethatwewishtowriteto aparticularRAMaddress. This is followed by the operation mode register address (0x74), followed by the operation mode control byte. Wewill initialize the compass to update in continuous mode at a rate of 20Hz, and we also want to enable the Set/Reset function. This gives a data bytevalue of 0x72. The compass setup can therefore be executed by an I2C write message containing the three command bytes as a single array, i.e: cmd[0] = 0x47; cmd[1] = 0x74; cmd[2] = 0x72; // ‘ G’ write to RAM address // Operation mode register address // Op mode = 20H, no S/R, continuous A test program to set up and read the HMC6352 is shown in Program Example 13.1. /* Program Example 13.1: HMC6352 Compass Setup and Read */ #include "mbed.h" // mbed objects I2C compass(p28, p27); // sda, scl Serial pc(USBTX, USBRX); // tx, rx // variables const int addr = 0x42; // define the I2C write Address char cmd[3]; // command array for read and write float pos; // measured position // main code int main() { cmd[0] = 0x47; // ’ G’ write to RAM address cmd[1] = 0x74; // Operation mode register address cmd[2] = 0x72; // Op mode = 20H, no S/R, continuous compass.write(addr,cmd, 3); // Send operation while (1) { compass.read(addr, cmd, 2); // read the two-byte echo result An Introduction to Control Systems 283 pos = 0.1 * ((cmd[0] << 8) + cmd[1]); if (pos>180){ pos=pos-360; } pc.printf("deg = %.1f\n", pos); wait(0.3); //convert to degrees } } Program Example 13.1 HMC6352 compass setup and read To read data from the compass we use an infinite loop and output data values to a host PC terminal application. Inside the infinite loop we simply perform a 2-byte read which returns the 16-bit data value (in tenths of a degree). To form a single number from these 2 bytes we shift the first byte left by 8 (as it is the more significant byte) and add the second byte; thisformsa16-bitnumber. Inthesamelineof codethisisthenmultipliedby 0.1, togive a result in degrees. It is actually more useful to have degrees in the range 180 to þ 180 (rather than 0 to 360), so values greater than 180 have the 360 subtracted. With the compass IC connected to mbed pins 27 and 28, Program13.1 should initialize and run, allowingyouto verify that correct compassreadings areshownonthePC terminal. Zero degrees indicates north and 180 degrees (or 180 degrees) indicates south, and hence 90 degrees represents due east and 90 degrees represents due west. Be careful to ensure that large magnets or power sources do not interfere with the compass’s sensitivity. If you are in a steel-framed building or a well-equipped laboratory, you may find that the earth’s field is totally overwhelmed by what is around you! 13.2.2 Implementing a 360 Degree Rotation Servo Wecanimplementanopenlooppositioncontrollerwitha360degreeservoandapotentiometer to control. Servoswith360degreemotioncanbesourced(as detailedinAppendix D), or astandard180degreemotionservocanbemodifiedtoallowcompleterotation, asdescribedby Reference13.4. The360degreeservo requiresthesamembedconnectionsasthestandard180 degreeservo(asshowninFigure4.10). However, the360degreeversionisamoreerraticdevice andmorechallengingtocontrol. WhenconnectingaPWMsignal tothedevicealowduty cycle signal will causetheservotocontinuously turnanti-clockwise, whereasahigherduty cyclewill causetheservotorotatecontinuouslyclockwise.Therewill beasinglePWMdutyvaluewhichis a‘zero’ point at whichtheservo holds stationary. We will now implement a scheduled program to allow different rate functions. In particular, we will use a fast rate function to control the servo positioning and to read the sensor data (100Hz), but a slower rate function to send data to the host terminal application (5Hz). We will therefore use two Ticker objects and two task functions to control and implement the program timing. In this program we will use a potentiometer to 284 Chapter 13 allow open loop control of the servo; we will also read and display compass data to the screen to quantify the direction in which the compass is pointing. We therefore need to define an analog input (to read the potentiometer) and a PWM output (to actuate the servo). We will also need to implement the same HMC6352 initialization and read commands as used in Program Example 13.1. Start a new project and enter the code shown in Program Example 13.2. /* Program Example: 13.2 Open Loop Compass */ #include "mbed.h" //***** mbed objects ***** I2C compass(p28, p27); // sda, scl PwmOut PWM(p25); AnalogIn Ain(p20); Serial pc(USBTX, USBRX); // tx, rx Ticker s100hz_tick; // 100 Hz (10ms) ticker Ticker s5hz_tick; // 5 Hz (200ms) ticker //***** variables ***** const int addr = 0x42; // define the I2C write Address char cmd[3]; float pos; // measured position float ctrlval; // PWM control value //***** function prototypes ***** void s100hz_task(void); // 100 Hz task void s5hz_task(void); // 5 Hz task //***** main code ***** int main() { // initialize and setup data PWM.period(0.02); cmd[0] = 0x47; // ’ G’ write to RAM address cmd[1] = 0x74; // Operation mode register address cmd[2] = 0x72; // Op mode = 20H, S/R, continuous compass.write(addr,cmd, 3);// Send operation s100hz_tick.attach(&s100hz_task,0.01); // attach 100 Hz task s5hz_tick.attach(&s5hz_task,0.2); // attach 5 Hz task while(1){ // loop forever } } //***** function 100hz_task ***** void s100hz_task(void) { compass.read(addr, cmd, 2); // read the two-byte compass data pos = 0.1 * ((cmd[0] << 8) + cmd[1]); //convert to degrees if (pos>180) pos=pos-360; convert to 180deg ctrlval=Ain; // set control value (also try ctrlval=Ain/4) PWM=ctrlval; // output control value to PWM } An Introduction to Control Systems 285 //***** function 5hz_task ***** void s5hz_task(void) { pc.printf("deg = %.1f PWM = %.4f\n", pos, ctrlval); } Program Example 13.2 Open loop compass If a potentiometer input is now connected to pin 20 and the PWM output on pin 25 is connected to a powered servo, your compiled code should allow the potentiometer to move the servo clockwise and anti-clockwise. Position data will also be sent to a host PC running Tera Term. You will notice that the motion of the servo is quite sensitive and erratic; it is actually very difficult to achieve an exact stationary position. Indeed, the analog input gives values between 0.0 and 1.0, but we know fromour experience of servos in Chapter 4 that the servo only usesthePWMduty cyclerangeof about5to 20%. Itisthereforepossibleto decreasethe open loop sensitivity by implementing either a scaling factor or some hard limits to the possible PWM control values. n Exercise 13.1 1. Modify Program Example 13.2 so that the control value ctrlval is only a fraction of Ain by dividing by a fixed number. Try different values and see whether the control and stability can be improved. 2. Looking at theTera Termoutput, find thePWM value(ctrlval) that causes theservo to hold stationary. This is a constant for theservo you areusing. Makea noteof this ‘zero’ value, as we will need it later on, at which time we will call it PWM_zero. n 13.2.3 Implementing a Closed Loop Control Algorithm We can use a simple proportional control algorithm to implement a closed loop system. To demonstrate this we will set our desired compass position to be 0 degrees, i.e. the compass will always point north (much like a real compass). The servo will move the position of the compass automatically to ensure that it does this. First, we will need to define a few variables for calculating error, the desired setpoint (¼0) and associated PWM control value, as follows: float float float float float setpos=0; // desired setpoint position = zero (North) error; // calculated error ctrlval; // PWM control value kp=0.0002; // proportional gain (to be tuned) PWM_zero=0.075; // zero value (as deduced in Exercise 13.1) ProgramExample13.3implementstheclosedloopalgorithm, whichretainsmuchof thecode from Program Example 13.2. 286 Chapter 13 /* Program Example 13.3: Closed loop compass program */ #include "mbed.h" // mbed objects I2C compass(p28, p27); PwmOut PWM(p25); AnalogIn Ain(p20); Serial pc(USBTX, USBRX); Ticker s100hz_tick; Ticker s5hz_tick; // variables const int addr = 0x42; char cmd[3]; float pos; float setpos=0; float error; float ctrlval; float kp=0.0002; float PWM_zero=0.075; // sda, scl // tx, rx // 100 Hz (10ms) ticker // 5 Hz (200ms) ticker // define the I2C write Address // measured position // setpoint position = zero (North) // calculated error // PWM control value // proportional gain // zero value // function prototypes void s100hz_task(void); void s5hz_task(void); // 100 Hz task // 5 Hz task // main code int main() { // initialize and setup data PWM.period(0.02); cmd[0] = 0x47; // ’ G’ write to RAM address cmd[1] = 0x74; // Operation mode register address cmd[2] = 0x72; // Op mode = 20H, S/R, continuous compass.write(addr,cmd, 3); // Send operation // assign timers s100hz_tick.attach(&s100hz_task,0.01); //attach 100 Hz task to 10ms tick s5hz_tick.attach(&s5hz_task,0.2); //attach 5Hz task to 200ms tick while(1){ // loop forever } } // function 100hz_task void s100hz_task(void) { compass.read(addr, cmd, 2); // read the two-byte echo result //convert data to degrees pos = 0.1 * ((cmd[0] << 8) + cmd[1]); if (pos>180) pos=pos-360; error = setpos - pos; // get error ctrlval = (kp * error); // calculate ctrlval (proportional) ctrlval = ctrlval + PWM_zero; // add control value to zero position PWM = ctrlval; // output to PWM } An Introduction to Control Systems 287 // function 5hz_task void s5hz_task(void) { pc.printf("deg = %.1f error=%.1f ctrlval=%.4f\n",pos,error,ctrlval); } Program Example 13.3 Closed loop compass program The 100Hz task includes the closed loop control algorithm. Immediately after the pos variable has been calculated, the error between the actual and desired setpoint positions, i.e. the proportional control value ctrlval, is calculated as follows: error = setpos - pos; ctrlval = (kp * error); // get error // calculate ctrlval (proportional) The control value is a calculated position that automatically adjusts to make up for the difference between the desired and actual in a smooth and controlled manner. However, we first need to add the zero position to the control value in the following line: ctrlval = ctrlval + PWM_zero; // add control value to zero position Thezero position, PWM_zero, is asimplecalibratablevaluewhichwededucedinthesecond partof Exercise13.1. ItdefinesthePWMduty cyclethatholdstheservoinastationary position. Itnowactsasanoffsetto thecontrol value, so anegativeerrorcausestheservo to rotateto one sideof thezero position, andapositivevaluecausesitto rotateto theotherside. Whenthereis zero errorinthecontrol algorithmtheservo stays still. Inthis examplethezero offset valueis calibratedas PWM_zero[ 0.075, althoughyourownservo may requireadifferent value. n Exercise 13.2 1. Modify the value of Kp and see how this affects the system stability. In general, if Kp is too large then overshoot and instability are observed, whereas if Kp is too small, then the servo response is slow and inaccurate. 2. Investigate the required accuracy of the PWM_zero value. Are three decimal places sufficient or does refining this value to four or five decimal places enhance the controller’s performance? n n Exercise 13.3 1. LCD output e Add a liquid crystal display(LCD) to your systemto displayposition, error and PWM data. You can also use the 6 V servo battery pack as a portable supply voltage for the mbed. This will allow you to disconnect the mbed from the host PC and have a fully mobile digital compass. 2. Position control e Develop your system to allow a user to input a desired position (in degrees) in a terminal application, and the servo will immediately move to that position. n 288 Chapter 13 13.3 Communicating Control Data over the Controller Area Network 13.3.1 The Controller Area Network The Controller Area Network (CAN) is another type of serial communications protocol that was developed within the automotive industry to allow a number of electronic units on a single vehicle to share essential control data. A vehicle nowadays uses many microcontrollers for autonomous control systems. Each microcontroller systemis referred to as an electronic control unit (ECU) and these include the engine management ECU, an anti-braking system (ABS) ECU, a dashboard ECU, active suspension and the radio/CD player, forexample. Eachof theseECUsmanagesitsowncontrol strategies, butthey all need to access informationrelevant to their own operation, for example drawn fromengine speed, throttle position, brake pedal position and engine temperature. However, an automotive vehicle generates a high level of electromagnetic interference and a wide temperature and humidity range; this is a hostile environment for any signal and indeed for any electronic device. Moreover, very highreliability isessential asvehiclesaresafety-critical systems. The serial standards developed for the benign environment of home or office, such as UART, SPI and I2C, are completely inappropriate for this hostile environment, and a new standard was therefore needed. Initially, CAN was developed by the German company Bosch. They publishedVersion2.0of thestandardin1991, andin1993itwasadoptedby theInternational Organization for Standardization (ISO), as ISO 11898. At the time of writing, CAN specificationVersion2.0B canbedownloadedfromtheBoschwebsite(Reference 13.5). The CAN standard has a high level of data security, it is inevitably complex and just the briefest overview is given here. The main features are listed below. • Communication is asynchronous, half duplex, with (for a given system) a fixed bit rate. The maximum for this is 1Mbit/s. • The configuration is ‘peer to peer’, i.e. all nodes are viewed as equals. There is, however, a mechanism for prioritization. Master and slave designation is not used. • Logicvaluesonthebusaredefinedas‘dominant’ or‘recessive’, wheredominantoverrides recessive. Physical interconnect is not otherwise defined. • The bus access is flexible. With all nodes being peers, any can start a message. An ingenious arbitrationprocess is appliedinthecaseof simultaneous access, whichdoes not lead to loss of time or data. The arbitration process recognizes prioritization. • There is an unlimited number of nodes. • Bus nodes do not have addresses, but apply ‘message filtering’ to determine whether data on the bus is relevant to them. • Data is transferred in frames, which have a complex format. This starts with identifier bits, during which arbitration can take place. Eight data bytes are allowed per frame. • There is an exceptionally high level of data security, with exhaustive error checking. A node that recognizes that it is faulty can disconnect itself from the bus. An Introduction to Control Systems 289 Figure 13.9: An example vehicle CAN bus network Figure13.9 shows anexamplevehicleCANbus network. Thetypes of control datathat need sharing along the bus can vary. For example, the dashboard ECU will need to access data includingenginespeed, enginetemperature, vehiclespeedanddiagnostic information, which will be predominantly provided by sensors attached to the engine management and gearbox ECUs, aswell asdooropen/closeddatafromthedoorECUs. Furthermore, if thisvehicleisto implementanautomatic doorlock strategy onceathresholdvehiclespeedhasbeenachieved, then the door lock ECUs will need to access vehicle speed data from the CAN bus. So it can be seen that a very reliable and thorough communications protocol for sharing control data around an automotive vehicle is required, and CAN provides this. CAN is also usedinindustrial andfactory applicationswherenoiseissuesandreliability requirements are similar to those of the automotive industry. 13.3.2 CAN on the mbed The mbed has two CAN controller interfaces on pins 9e10 and 30e29; note that only the lattertwopinsappearasaCANinterfaceinFigure2.1. Thepinsrefertoreceive(RD orRXD) andtransmit (TD orTXD) signals, respectively. TheCANinterfacecanbeusedto writedata words out of a CAN port and will return the data received from another CAN device. The 290 Chapter 13 Table 13.2: Selected CAN API functions Function CAN CANMessage Usage Creates a CAN interface connected to specific pins Creates an empty CAN message (for reading) or a CAN message with specific content (for writing): id the message ID data len space for 8-byte payload length of data in bytes format type frequency write read defines if the message has standard or extended format defines the type of a message Set the frequency of the CAN interface Write a CANMessage to the bus. Returns 0 if write failed, 1 if write was successful Read a CANMessage from the bus. Returns 0 if no message arrived, 1 if message arrived CAN clock frequency can also be configured. A selection of the CAN application programming interface (API) functions is shown in Table 13.2. When using the mbed CAN API, we first have to define a CAN object and then define a message (CANMessage) to be written to or read from the CAN bus. The mbed CAN controllers alone, however, cannot beusedto communicatedirectly withaCANnetwork. To do this weneedto usethembedCANinterfaceto control aspecific CAN transceiver IC such as the Microchip MCP2551. This is shown in Figure 13.10 and described in Reference 13.6. The CAN bus implementation used is differential, and connects to the CANH and CANL pins. An external resistor connected at Rs controls the slew rate of the data signal, with aslowerrateminimizingelectromagneticinterference, althoughforsimpletestingthiscanbe connected directly to ground. The mbed connects from its CAN controllers to the transceiver’s RXD and TXD pins. Figure 13.10: Microchip MCP2551 CAN transceiver IC An Introduction to Control Systems 291 Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 MCP2551 TXD Rs VSS CANH VDD CANL RXD VREF MCP2551 The CAN bus Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller mbed B: Read TXD Rs VSS CANH VDD CANL RXD VREF Gnd Vin Vb nR 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 mbed Microcontroller mbed A: Write Vout Vu IFIF+ RDRD+ TDTD+ DD+ 30 29 28 27 26 25 24 23 22 21 Figure 13.11: Hardware build for mbed-to-mbed CAN communication To demonstrate CAN with the mbed we will communicate some data between two mbeds over a CANnetwork. One mbed will send data to the CANbus while the other will receive data from the CAN bus. The hardware connections required to create a simple CAN network test are shown in Figure 13.11 and Table 13.3. Notice that the ‘CAN bus’ is defined as the wires CANH and CANL, which sometimes require a termination resistance of 100e200U between them over long wires. In this simple, noise-free example the short connections mean that a termination resistor is not necessary. Note also that we use the mbed CAN controller on pins 30 and 29 for the send system and the CAN controller uses pins 9 and 10 e these are arbitrarily chosen, predominantly to make the hardware connection diagram neat! Having built the CAN test system described in Figure 13.11 and Table 13.3, Program Example 13.4 can be implemented to regularly send data values to the CAN bus. /* Program Example 13.4: CAN data write e sends an incrementing count value to the CAN bus every second */ #include "mbed.h" Serial pc(USBTX, USBRX); // tx, rx for Tera Term output DigitalOut led1(LED1); // status LED CAN can1(p30, p29); // CAN interface char counter = 0; int main() { printf("send. "); while (1) { // send value to CAN bus and monitor return value to check if CAN // message was sent successfully. If so display, increment and toggle 292 Chapter 13 if (can1.write(CANMessage(1, &counter, 1))) { pc.printf("Message sent: %d\n", counter); // display counter++; // increment led1 = !led1; // toggle status LED }else{ can1.reset(); } wait(1); } } Program Example 13.4 CAN data write Here, onevery importantlineof codeistheif statement, whichperformsanumberof actions: if (can1.write(CANMessage(1, &counter, 1))) { First, this line creates a CANMessage with id[ 1, holding the data from the address of variable counter and of length 1 byte. The message is then written to the CAN bus and the Table 13.3: Pin connections for mbed-to-mbed CAN communications MCP2551 pin Description Pin connection Write system 1 TXD Transmit Data Input mbed p29 CAN TD 2 VSS Ground mbed p1 GND 3 VDD Supply Voltage mbed p39 Vu (5V) 4 RXD Receive Data Output mbed p30 CAN RD 5 Rs Reference Output Voltage mbed p1 GND 6 CANL CAN Low-Level Voltage I/O CAN bus low 7 CANH CAN High-Level Voltage I/O CAN bus high 8 VREF Slope-Control Input e Read system 1 TXD Transmit Data Input mbed p10 CAN TD 2 VSS Ground mbed p1 GND 3 VDD Supply Voltage mbed p39 Vu (5V) 4 RXD Receive Data Output mbed p9 CAN RD 5 Rs Reference Output Voltage mbed p1 GND 6 CANL CAN Low-Level Voltage I/O CAN bus low 7 CANH CAN High-Level Voltage I/O CAN bus high 8 VREF Slope-Control Input e An Introduction to Control Systems 293 return value of the write operation is monitored. Only if the write operation returns a successful response (by returning a value 1) does the counter increment and light-emitting diode (LED) toggle. Program Example 13.5 creates an empty CANMessage. It continuously monitors the CAN bus and displays any read CAN messages to Tera Term on a host PC. /* Program Example 13.5: CAN data read e reads CAN messages from the CAN bus */ #include "mbed.h" Serial pc(USBTX, USBRX); // tx, rx for Tera Term output DigitalOut led2(LED2); // status LED CAN can1(p9, p10); // CAN interface int main() { CANMessage msg; // create empty CAN message printf("read. \n"); while(1) { if(can1.read(msg)) { // if message is available, read into msg printf("Message received: %d\n", msg.data[0]); // display message data led2 = !led2; // toggle status LED } } } Program Example 13.5 CAN data read You can now implement the hardware connections shown and Program Examples 13.4 and 13.5 to show two mbeds communicating over CAN. n Exercise 13.4 1. Enhance the CAN write program to send a second data value to the CAN bus. Give the second data value a different ID value and make it two bytes in size and at a different message rate (say every 5 seconds). Evaluate how the CAN reader program interprets the CAN messages it receives. 2. Implement a procedure in the CAN reader program so that it can interpret the two different CAN messages based on the message ID, and uniquely display a text message in Tera Term based on the ID of the message received. n For a practical implementation of a CAN messaging system, such as for an automotive system, a CAN specification will define the messages that can be communicated between ECUs. Eachmessage, forexamplevehiclespeed, enginespeed, enginetemperatureanddoor open/closed status, will have a unique ID as well as a definition of the size of the data and any conversion equation required in order to turn the raw data into a sensible value. Each ECU will bepre-programmedwiththeCANspecificationso that whenamessageis received it can immediately know what the message is and how to interpret the data. 294 Chapter 13 Several CAN interface devices have been developed and are available commercially for example to read diagnostic information from vehicles. It is also possible to use an mbed to read and write data messages to and from a vehicle CAN bus with the correct interface, and hence even control a vehicle this way. Of course, to do this you will need to know the CAN specification for the vehicle that is being interfaced with. A number of interesting examples and an mbed CAN interface board can be found in Reference 13.7. Chapter Review • Closed loop control systems use negative feedback of sensor data to ensure that a specific actuator position is accurate. • When responding to a step change in desired setpoint, a closed loop control system may respond too slowly or overshoot, or have a steady-state error. Tuning the control algorithm can ensure a best-possible step response. • The time taken for the step response is dependent on the control algorithm design, the physical response time of the mechanical system and the speed of the microprocessor software loop. • Proportional, integral and derivative control can be tuned to give smooth control of many electromechanical systems. • Control data can be shared on a network of electronic control units (ECUs) over the Controller Area Network (CAN) protocol. • An automotive vehicle may have a number of ECUs for controlling, for example, enginemanagement systems, brakesystems, thedashboard, airbagcontrol anddoorlocks. These can all be connected by CAN. • CAN is an extremely reliable communications protocol with high tolerance to noise and interference. • To implement CAN on the mbed, additional CAN transceiver ICs must be used to create the CAN bus. Quiz 1. 2. 3. 4. 5. What are the main differences between an open loop and a closed loop control system? What do the terms setpoint, plant and negative feedback refer to in closed loop control? Where and why might closed loop control be required in the design of a helicopter? What does ‘the step response’ of a control system refer to? What benefits does CAN communication have over other serial protocols such as I2C and USB? 6. Give five example ECUs that may be found on a modern car. An Introduction to Control Systems 295 References 13.1. The Segway website. http://www.segway.com 13.2. Copeland, B. R. (2008). The Design of PID Controllers using ZieglereNichols Tuning. http://www.eng. uwi.tt/depts/elec/staff/copeland/ee27B/Ziegler_Nichols.pdf 13.3. 2-Axis Compass with Algorithms. HMC6352. Document #900307. Rev. D. January 2006. http://www. magneticsensors.com/ 13.4 Servo modification for 360 degree rotation. http://www.embeddedtronics.com/servo.html 13.5. The CAN section of the Bosch website. www.can.bosch.com 13.6. Microchip Technology (2003). MCP2551 High-Speed CAN Transceiver Data Sheet. Document DS21730E. 13.7. mbed CAN-Bus Demo Board. http://mbed.org/forum/news-announce CHAPTER 14 Letting Go of the mbed Libraries Chapter Outline 14.1 Introduction 297 14.2 Control Register Concepts 298 14.3 Digital Input/ Output 299 14.3.1 mbed Digital Input/Output Control Registers 299 14.3.2 A Digital Output Application 301 14.3.3 Adding a Second Digital Output 302 14.3.4 Digital Inputs 303 14.4 Getting Deeper into the Control Registers 305 14.4.1 Pin Select and Pin Mode Registers 305 14.4.2 Power Control and Clock Select Registers 308 14.5 Using the DAC 310 14.5.1 mbed DAC Control Registers 310 14.5.2 A DAC Application 311 14.6 Using the ADC 312 14.6.1 mbed ADC Control Registers 313 14.6.2 An ADC Application 313 14.6.3 Changing ADC Conversion Speed 317 14.7 A Conclusion on using the Control Registers 318 Chapter Review 319 Quiz 319 Reference 319 14.1 Introduction The mbed library contains many useful functions, which allow us to write simple and effectivecode. Thisseems agoodthing, but it is also sometimeslimiting. What if wewant to use a peripheral in a way not allowed by any of the functions? Therefore it is useful to understand how peripherals can be configured by direct access to the microcontroller’s registers. In turn, this leads to a deeper insight into some aspects of how a microcontroller works. As a by-product, and because we will be working at the bit and byte level, this study develops further skills in C programming. Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00014-3 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 297 298 Chapter 14 It is worthissuingavery clearhealthwarningat this early stage: this chapteris insomeways more complex than any of the others that have gone before. It introduces some of the complexity of theLPC1768microcontroller, whichliesattheheartof thembed, acomplexity which the mbed designers rightly wish to keep from you. Your own curiosity, ambition or your professional needs may, however, lead you to want to work at this deeper level. Working with the complexity of this chapter may result in two opposing feelings. One is a sense of gratitude to the writers of the mbed libraries, that they have saved you the complexity of controlling the peripherals directly. At the opposite extreme, getting to grips with the chapter should also be a very liberating experience, like throwing away the water wingsafteryouhavelearnt to swim. At themomentyouprobably think that youcannot write any program unless you have the library functions at the ready. When you are through with this chapter youwill realize that you are no longerdependent on the library; youuse it when you want, and write your own routines when you want e the choice becomes yours! This chapter may be read in sequencewith all other chapters. Alternatively, it can be read in different sections as extensions of earlier chapters. We will refer to Reference 2.3, the LPC1768 datasheet, and even more Reference 2.4, its user manual. Because we are now workingatmicrocontrollerlevel, ratherthanmbedlevel, wewill havetotakemorecareabout how the microcontroller pins connect with the mbed pins. Therefore you will also need to have the mbed schematics, Reference 2.2, ready. 14.2 Control Register Concepts It is useful at this stageto understandalittle more about how the microcontroller central processingunit(CPU)interactswithitsperipherals.Eachof thesehasoneormoresystemcontrol registers which act as thedoorway betweenthe CPU and the peripheral. To the CPU, these registerslookjustlikememory locations.They canusually bewrittentoandreadfrom,andeach has its ownaddress withinthe memory map. The cleverpart is that eachof the bits inthe registeriswiredacrosstotheperipheral. They mightcarry control information, sentby theCPU to the peripheral, orthey might return status information fromtheperipheral. They might also provideanessential pathfor data. Thegeneral idea of this is illustrated in Figure 14.1. The microcontrollerperipherals also usually generate interrupts, for example to flag whenan analog-to-digital conversion is complete oranew word has been received by aserial port. Early in any program, the programmer must write to the control registers, to set up the peripherals to the configuration needed. This is called initialization, and turns the control registers froma general-purpose and non-functioning piece of hardware into something that is useful for the project in hand. In the mbed, this task is undertaken in the mbed utilities; in thischapter, wemoveto doingthisworkourselves. Inall of this, animportantquestionarises: what happens in that short period after power has been applied, but before the peripherals Letting Go of the mbed Libraries 299 Register’s Unique Address Control Information Status Information Peripheral Peripheral The CPU Data Bus Data Interchange Interrupt(s) Figure 14.1: The principle of a control register havebeenset upby theprogram? At thistimeanembeddedsystemispowered, but not under complete control. Fortunately, all makers of microcontrollers design in a reset condition for each control register. This generally puts a peripheral into a predictable, and often inactive, state. We can look this up, and write the initialization code accordingly. On some occasions, the reset state may be the state that we need. A central theme of this chapter is the exploration and use of some of the LPC1768 control registers. Although we draw information from the LPC1768 data, the chapter is self-contained, withall necessary dataincluded. However, weshowwhichtableinthemanual the data is taken from, so it is easy to cross-refer. We hope this gives you the confidence and ability to move on to explore and apply the other registers. 14.3 Digital Input/Output 14.3.1 mbed Digital Input/Output Control Registers Thedigital input/output (I/O) is auseful placeto start ourstudy of control registers, as this is simpler than any other peripherals on the LPC1768. This has its digital I/O arranged nominally as five 32-bit ports; yes, that implies a stunning 160 bits. Only parts of these are 300 Chapter 14 used, however, for example Port 0 has 28 bits implemented, Port 2 has 14, and Ports 3 and 4 have only two each. In the end, among its 100 pins, the LPC1768 has around 70 general purposeI/Opinsavailable. However, thembedhasonly 40accessiblepins, soonly asubsetof themicrocontrollerpinsactually appearsonthembedinterconnect, many of whichareshared with other features. As we have seen, it is possible to set each port pin as an input or as an output. Each port has a 32-bit register that controls the direction of each of its pins. These are called the FIODIR registers. To specify which port the register relates to, the port number is embedded within the register name, as shown in Table 14.1. For example, FIO0DIR is the direction register for Port 0. Each bit in this register then controls the corresponding bit in the I/O port, for example bit 0 in the direction register controls bit 0 in the port. If the bit in the direction register is set to 1, then that port pin is configured as an output; if the bit is set to 0, the pin is configured as an input. It is sometimes moreconvenient not to work withthefull 32-bit directionregister, especially whenwemight just bethinkingof oneortwo bitswithintheregister. Forthisreasonit is also possible to access any of the bytes within the larger register, as single-byte registers. These registers have a number code at their end. For example, FIO2DIR0 is byte 0 of the Port 2 direction register, also seen in Table 14.1. Fromthe table you can see that the address of the whole word is shared by the address of the lowest byte. Table 14.1: Example digital I/ O control registers Register name Register function Register address FIOnDIR Sets the data direction of each pin in Port n, where n takes value 0 to 4. A port pin is set to output when its bit is set to 1, and as input when it is set to 0. Accessible as word. Reset value¼0, i.e. all bits are set to input on reset e FIO0DIR FIO2DIR Example of above for Port 0 Example of above for Port 2 0x2009C000 0x2009C040 FIOnDIRp Sets the data direction of each pin in byte pof Port n, where ptakes value0 to 3. A port pin is set to output when its bit is set to 1. Accessible as byte e FIO0DIR0 FIO0DIR1 FIO2DIR0 Example of above, Port 0 byte 0 Example of above, Port 0 byte 1 Example of above, Port 2 byte 0 0x2009C000 0x2009C001 0x2009C040 FIO0PIN0 Sets the data value of each bit in least significant byte of Port 0 or 2. Accessible as byte. Reset value¼0 0x2009C014 FIO2PIN0 0x2009C054 Letting Go of the mbed Libraries 301 A second set of registers, called FIOPIN, holds the data value of the microcontroller’s pins, whether they have been set as input or output. Again, two are seen in Table 14.1, with the same naming pattern as the FIODIR registers. If a port bit has been set as an output, then writing to its corresponding bit in its FIOPIN register will control the logic value placed on that pin. If thepinhasbeensetasinput, thenreadingfromthatbitwill tell youthelogic value assertedat thepin. TheFIODIR andFIOPINregistersaretheonly two registersetsweneed to worry about for our first simple I/O programs. 14.3.2 A Digital Output Application A digital output can be configured and then tested simply by flashing a light-emitting diode (LED). We did this near the beginning of the book, in Program Example 2.1. We will look at the complete method for making this happen, working directly with the microcontroller registers. This first program, Program Example 14.1, will use Port 2 pin 0 as the digital output. The mbed schematic (Reference 2.2) shows that this pin is routed to the mbed pin 26. Follow through Program Example 14.1 with care. Notice that for once we are not writing #include "mbed.h"! At the program’s start the names of two registers from Table 14.1 are defined to equal the contents of their addresses. This is done by definingtheaddressesaspointers(seeSectionB.8.2), usingthe* operator. Theformatof thisis not entirely simple, and for the present purposes we can use it as shown. Further information can, however, be found in Reference 14.1. Having defined these pointers, we can now refer to the register names in the code rather than worrying about the addresses. The C keyword volatile is also applied. This is used to define a data type whose value may change outside program control. This is a common occurrence in embedded systems, and is particularly applicable to memory-mapped registers, such as we are using here, which can be changed by the external hardware. C code feature Within the main( ) function the data direction register of Port 2, byte 0 is set to output, by setting all bits to Logic 1. A while loop is then established, just as in ProgramExample 2.1. Within this loop, pin 0 of Port 2 is set high and low in turn. Check the method of doing this, if you are not familiar with it, as this shows one way of manipulatingasinglebit withinalargerword. To set thebit high, it is ORedwithLogic 1. All other bits are ORed with Logic 0, so will not change. To set it low, it is ANDed with binary 11111110. Thishastheeffectof returningtheleastsignificantbit(LSB) to 0, whileleavingall other bits unchanged. The 1111 1110 value is derived by taking the logic inversion of 0x01, using the C ~operator. C code feature The delay function should be self-explanatory, and is explored more in Exercise 14.1. Its function prototype appears early in the program. 302 Chapter 14 /*Program Example 14.1: Sets up a digital output pin using control registers, and flashes an led. */ // function prototypes void delay(void); //Define addresses of digital i/o control registers, as pointers to volatile data #define FIO2DIR0 (*(volatile unsigned char *)(0x2009C040)) #define FIO2PIN0 (*(volatile unsigned char *)(0x2009C054)) int main() { FIO2DIR0=0xFF; // set port 2, lowest byte to output while(1) { FIO2PIN0 j= 0x01; // OR bit 0 with 1 to set pin high delay(); FIO2PIN0 &= ~0x01; // AND bit 0 with 0 to set pin low delay(); } } //delay function void delay(void){ int j; //loop variable j for (j=0;j<1000000;j++) { j++; j--; //waste time } } Program Example 14.1 Manipulating control registers to flash an LED Connect anLED between an mbed pin 26 and 0 V, and compile, download and run the code. Press reset and the LED should flash. n Exercise 14.1 With an oscilloscope, carefully measure the duration of the delay function in Program instructions. Adjust the Example14.1. Estimatetheexecution timefor thejþ þ and j delay function experimentally so that it is precisely 100 ms. Then create a new 1 s delay function, which works by calling the 100 ms one 10 times. Now write a library delay routine, which gives a delay of n ms, where n is the parameter sent. n 14.3.3 Adding a Second Digital Output Following the principles outlined above, we can add further digital outputs. Here, we add a second LED and make a flashing pattern. Port 2 pin 1 is used, which connects to mbed pin 25. AddasecondLED to thispin, preferably of adifferentcolor. Wehavealready definedthe Letting Go of the mbed Libraries 303 direction control and pin I/O registers for Port 2, so we do not need to add any new registers. We do, however, add a variable to allow us to generate an interesting flashing pattern. Copy Program Example 14.1 to a new program, and add into it the following variable declaration, prior to the main program function: char i; Also add the for loop of Program Example 14.2 at the end of the while loop. Notice that now we are toggling bit 1 of the FIO2PIN0 register. We do this as before by ORing with 0x02, and then ANDing with the inverse of 0x02. This is where our second LED is connected. for (i=1;i<=3;i++){ FIO0PIN0 j= 0x02; delay(); FIO0PIN0 &= ~0x02; delay(); } // set port 2 pin 1 high (mbed pin 25) // set port 2 pin 1 low Program Example 14.2 (code fragment) Controlling a second LED output Runtheprogram. ItshouldflashthefirstLED once, followedby threeflashesof thesecond. If you have LEDs of different colors this will give you a pattern something like: green e red e red e red e green e red e red e red e green e . n Exercise 14.2 In the mbed circuit diagrams (Reference 2.2) identify the LPC1768 pins that drive the onboard LEDs. RewriteProgramExample14.2 so that theonboard LEDs areactivated, instead of using external ones. n 14.3.4 Digital Inputs We can create digital inputs simply by setting a port bit to input, using the correct bit in an FIODIR register. Program Example 14.3 now develops the previous example, by including a digital input from a switch. The state of the switch changes the loop pattern, determining which LED flashes three times and which flashes just once in a cycle. This then gives a control system which has outputs that are dependent on particular input characteristics. It uses the outputs already used, and adds bit 0 of Port 0 as a digital input. Looking at the schematic, we can see that this is pin 9 of the mbed. It should not be difficult to follow Program Example 14.3 through. As before, we see the necessary register addresses defined. Directly inside the main function Port 0 byte 0 is set as a digital input, noting that a Logic 0 sets the corresponding pin to input. We have set all 304 Chapter 14 of byte 0 to input by sending 0x00; we could of course set each pin within the byte individually if needed. Moreover, this setting is not fixed; we can, if needed, change a pin from input to output as a program executes. After all this, a reading of Table 14.1 reminds us that the reset value of all ports is as input; therefore, this little bit of code is not actually necessary e try removing it when you run the program. However, it is good practice to reassert values that are said to be in place due to the reset; it gives you the confidence that the value is in place, and it is a definite statement in the code of a setting that you want. The while loop then starts, and at the beginning of this we see the if statement testing the digital input value. The if condition uses a bit mask to discard the value of all the other pins on Port 0 byte 0 and simply returns a high or low result dependent on pin 8 alone. The variablesa andb will holdvalueswhichwill changedependingontheswitchposition. A little later, we see the a and b values used to define the port values for the green and red LEDs. If b has beenset to 0x01beforethefor loop, thenthered LED will flashthreetimes; if it has been set to 0x02, then the green LED will flash three times. /* Program Example 14.3: Uses digital input and output using control registers, and flashes an LED. LEDS connect to mbed pins 25 and 26. Switch input to pin 9. */ // function prototypes void delay(void); //Define Digital I/O registers #define FIO0DIR0 (*( volatile unsigned char *)(0x2009C000)) #define FIO0PIN0 (*( volatile unsigned char *)(0x2009C014)) #define FIO2DIR0 (*(volatile unsigned char *)(0x2009C040)) #define FIO2PIN0 (*(volatile unsigned char *)(0x2009C054)) //some variables char a; char b; char i; int main() { FIO0DIR0=0x00; // set all bits of port 0 byte 0 to input FIO2DIR0=0xFF; // set port 2 byte 0 to output while(1) { if (FIO0PIN0&0x01==1){ // bit test port 0 pin 0 (mbed pin 9) a=0x01; // this reverses the order of LED flashing b=0x02; // based on the switch position } else { a=0x02; b=0x01; } FIO2PIN0 j= a; delay(); FIO2PIN0 &= ~a; delay(); Letting Go of the mbed Libraries 305 for (i=1;i<=3;i++){ FIO2PIN0 j= b; delay(); FIO2PIN0 &= ~b; delay(); } } } void delay(void){ //program continues //end while loop //delay function. Program Example 14.3 Combined digital input and output To run this program, set up the circuit of Figure 3.6, except that the green and red LEDs shouldconnecttombedpins25and26, respectively, andtheswitchinputisonpin9. Compile andrun. Youshouldseethat thepositionof theswitchtogglestheflashingLEDs betweenthe patterns green e red e red e red e green e red e red e red e green e . and green e green e green e red e green e green e green e red e green e . n Exercise 14.3 Rewrite Program Example 14.3 so that it runs on the exact circuit of Figure 3.6. n 14.4 Getting Deeper into the Control Registers Tocontinuewiththischapterweneedtogetfurtherintotheuseof control registers.Thissection therefore looks at some of the registers that control features across the microcontroller e informally called ‘global’ registers e that will be used in later sections. These relate to the allocation of pins, setting clock frequency and controlling power. This is by no means a complete survey, and wewill not even see or make use of many of the features of this microcontroller. 14.4.1 Pin Select and Pin Mode Registers One of the reasons that modern microcontrollers are so versatile is that most pins are multifunctional. They can be allocated to different peripherals and used in different ways. Withthembedlibrary, this flexibility is (quitereasonably) moreorless hiddenfromtheuser; 306 Chapter 14 Table 14.2: PINSEL1 register PINSEL1 Pin name Function when 00 Function when 01 Function when 10 Function when 11 Reset value 1:0 P0.16 GPIO Port 0.16 RXD1 SSEL0 SSEL 00 3:2 P0.17 GPIO Port 0.17 CTS1 MISO0 MISO 00 5:4 P0.18 GPIO Port 0.18 DCD1 MOSI0 MOSI 00 7:6 1 P0.19 GPIO Port 0.19 DSR1 Reserved SDA1 00 9:8 P0.201 GPIO Port 0.20 DTR1 Reserved SCL1 00 11:10 P0.211 GPIO Port 0.21 RI1 Reserved RD1 00 13:12 P0.22 GPIO Port 0.22 RTS1 Reserved TD1 00 15:14 1 P0.23 GPIO Port 0.23 AD0.0 I2SRX_CLK CAP3.0 00 17:16 P0.241 GPIO Port 0.24 AD0.1 I2SRX_WS CAP3.1 00 19:18 P0.25 GPIO Port 0.25 AD0.2 I2SRX_SDA TXD3 00 21:20 P0.26 GPIO Port 0.26 AD0.3 AOUT RXD3 00 23:22 P0.271,2 GPIO Port 0.27 SDA0 USB_SDA Reserved 00 25:24 1,2 P0.28 GPIO Port 0.28 SCL0 USB_SCL Reserved 00 27:26 P0.29 GPIO Port 0.29 USB_Dþ Reserved Reserved 00 29:28 P0.30 GPIO Port 0.30 USB_D_ Reserved Reserved 00 31:30 e Reserved Reserved Reserved Reserved 00 1 Not available on 80-pin package. Pins P0.27 and P0.28 are open drain for I2C bus compliance. RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table79: Pinfunctionselect register 1 (PINSEL1 e address0x4002 C004) bit description, with permission of NXP. 2 the libraries tidily make the allocations for you, without you even knowing. If they did not, youwouldbefacedwithabewilderingchoiceof possibilitiesevery timeyoutriedto develop an application. As our expertise grows, however, it is good to know that some of these possibilities are available. Two important sets of registers used in the LPC1768 are called PINSEL and PINMODE. ThePINSEL registercanallocateeachpinto oneof fourpossibilities. Anexampleof part of one register that we will be using soon, PINSEL1, is shown in Table 14.2. This controls the upper half of Port 0. The first column shows the bit number within the register; each line details two bits. The second column shows the microcontroller pin that is being controlled. The two bits under consideration can have four possible combinations; each of these connects the pin in a different way. These are shown in the next four columns. Do not worry if some of the abbreviations shown have little meaning to you; we will pick out the ones we need, when we need them. Letting Go of the mbed Libraries 307 Table 14.3: PINMODE0 register PINMODE0 Symbol 1:0 P0.00MODE 3:2 Value Description Reset value Port 0 pin 0 on-chip pull-up/down resistor control 00 00 P0.0 pin has a pull-up resistor enabled 01 P0.0 pin has repeater mode enabled 10 P0.0 pin has neither pull-up nor pull-down 11 P0.0 pin has a pull-down resistor enabled P0.01MODE Port 0 pin 1 control, see P0.00MODE 00 continued to P0.15MODE RedrawnfromNXP SemiconductorsUM10360LPC17xxUser Manual, Table87: PinModeselect register 0 (PINMODE0 e address0x4002 C040) bit description, with permission of NXP. Let us take as an example the line showing the effect of bits 21:20, i.e. line 11 of the table; these control bit 26 of Port 0. Column 3 shows that if the bits are 00, the pin is allocated to Port 0 bit 26, i.e. the pin is connected as general-purpose I/O. Importantly, the final column showsthatthisisalso thevaluewhenthechipisreset. Inotherwords, aslongasweonly want to use digital I/O, we do not need to worry about this register at all, as the reset value is the valuewewant. If the bits are set to 01, the pin is allocated to input 3 of the analog-to-digital converter (ADC). If set to 10, the pin is used for analog output, i.e. the digital-to-analog converter (DAC) output. If set to 11, the pin is allocated as Receiver input for universal asynchronous receiver/transmitter (UART) 3. Turning to the PINMODE registers, partial details of one of these are shown in Table 14.3. This is PINMODE0, whichcontrols theinput characteristics of thelowerhalf of Port 0. The patternisthesameforevery pin, sothereisno needforrepetition. Itiseasy toseethatpull-up and pull-down resistors (as seen in Figure 3.5) are available, and this is explored in Program Example 14.4. The repeater modeis a neat little facility which enables pull-up resistor when the input is a Logic 1, and pull-down if it is low. If the external circuit changes so that the input is no longer driven, then the input will hold its most recent value. n Exercise 14.4 Change the hardware for Program Example 14.3 so that you use an SPST (single-pole, single-throw) switch, for example a push-button, instead of the toggle (single-pole, double-throw, SPDT) switch. Connect it first between pin 9 and ground, and run the program with no change. This should run as before, because you are depending on 308 Chapter 14 the pull-up resistor being in place owing to the reset value of the PINMODE register. In diagrammatic terms, you have moved from the switch circuit of Figure 3.5a to that of Figure 3.5b. Now change the setting of PINMODE0 so that the pull-down resistor is enabled, and connect the switch between pin 9 and 3.3 V, i.e. applying Figure 3.5c. The program should again work, but with the changed input mode selection. n 14.4.2 Power Control and Clock Select Registers Power control and clock frequency are very closely linked. Every clock transition causes the circuit of the microcontroller to take a tiny pulse of current; the more transitions, the more the current taken. Hence, a processor or peripheral running at a high clock speed will cause high power consumption; one running at a low clock frequency will consume less power. Onewithits clock switchedoff, evenif it is powered up, will (if apurely digital circuit using CMOS technology) take negligible power. To conserve power, it is possible to turn off the clock source to many of the LPC1768 peripherals. This power management is controlled by the PCONP register, seen in part in Table 14.4. Where a bit is set to 1, the Table 14.4: Power Control register PCONP (part of) Bit Symbol Description Reset value 0 e Reserved NA 1 PCTIM0 Timer/Counter 0 power/clock control bit 1 2 PCTIM1 Timer/Counter 1 power/clock control bit 1 3 PCUART0 UART0 power/clock control bit 1 4 PCUART1 UART1 power/clock control bit 1 5 e Reserved NA 6 PCPWM1 PWM1 power/clock control bit 1 2 7 PCI2C0 I C0 interface power/clock control bit 1 8 PCSPI SPI interface power/clock control bit 1 9 PCRTC RTC power/clock control bit 1 10 PCSSP1 SSP 1 interface power/clock control bit 1 11 e Reserved NA 12 PCADC A/D converter (ADC) power/clock control bit Note: Clear the PDN bit in the AD0CR before clearing this bit, and set this bit beforesetting PDN 0 continued to bit 28 RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table46: Power Control for Peripheralsregister (PCONP e address 0x400F C0C4) bit description, with permission of NXP. Letting Go of the mbed Libraries 309 peripheral is enabled; when set to 0 it is disabled. It is interesting to note that some peripherals, such as the serial peripheral interface (SPI), are reset in the enabled mode, and others, such as the ADC, are reset disabled. Asidefrombeingabletoswitchtheclocktoaperipheral onoroff, thereissomecontrol overthe peripheral’sclock frequency itself. Thiswill control theperipheral’sspeedof operationaswell as its power consumption. This clock frequency is controlled by the PCLKSEL registers. Peripheral clocksarederivedfromtheclockthatdrivestheCPU,whichiscalledCCLK. Forthe mbed, CCLK normally runsat96MHz. Partial detailsof PCLKSEL0areshowninTable14.5, which shows that two bits are used per peripheral to control the clock frequency to each. ThefourpossiblecombinationsareshowninTable14.6. ThisshowsthattheCCLK frequency itself can be used to drive the peripheral. Alternatively, it can be divided by 2, 4 or 8. CCLK is derived fromthe main oscillator circuit, and can be manipulated in a number of interesting ways; however, we do not go into the details of that in this book. Table 14.5: Peripheral Clock Selection register PCLKSEL0 1 Bit Symbol Description Reset value 1:0 PCLK_WDT Peripheral clock selection for WDT 00 3:2 PCLK_TIMER0 Peripheral clock selection for TIMER0 00 5:4 PCLK_TIMER1 Peripheral clock selection for TIMER1 00 7:6 PCLK_UART0 Peripheral clock selection for UART0 00 9:8 PCLK_UART1 Peripheral clock selection for UART1 00 11:10 e Reserved NA 13:12 PCLK_PWM1 Peripheral clock selection for PWM1 00 15:14 PCLK_I2C0 Peripheral clock selection for I2C0 00 17:16 PCLK_SPI Peripheral clock selection for SPI 00 19:18 e Reserved NA 21:20 PCLK_SSP1 Peripheral clock selection for SSP1 00 23:22 PCLK_DAC Peripheral clock selection for DAC 00 25:24 PCLK_ADC Peripheral clock selection for ADC 00 27:26 PCLK_CAN1 Peripheral clock selection for CAN11 00 29:28 PCLK_CAN2 Peripheral clock selection for CAN21 00 31:30 PCLK_ACF Peripheral clock selection for CAN acceptance filtering1 00 PCLK_CAN1 and PCLK_CAN2 must have the same PCLK divide value when the CAN function is used. RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table40: Peripheral Clock Selectionregister (PCLKSEL0 e address 0x400F C1A8) bit description, with permission of NXP. 310 Chapter 14 Table 14.6: Peripheral Clock Selection register bit values PCLKSEL0 and PCLKSEL1 individual peripheral’s clock select options Function Reset value 00 PCLK_peripheral ¼CCLK/4 00 01 PCLK_peripheral ¼CCLK 10 PCLK_peripheral ¼CCLK/2 11 PCLK_peripheral ¼CCLK/8, except for CAN1, CAN2 and CAN filtering when “11” selects¼CCLK/6 RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table42: Peripheral ClockSelectionregister bit values, with permission of NXP. 14.5 Using the DAC We now turnto controlling the DAC throughits registers, tryingto replicateand develop the work doneinChapter4. Remindyourself of thegeneral block diagramof theDAC, asseenin Figure4.1.ItisworthmentioningherethatthepositivereferencevoltageinputtotheLPC1768, sharedby bothADCandDAC, iscalledVREFP, andappearsonpin12of themicrocontroller. A careful look at the mbedcircuit diagrams (Reference 2.2) shows that this is connected to the power supply 3.3 V, filtered to limit noise input. This is asensibleconnection, and we are unabletochangeit.Thenegativereferencevoltageinput,calledVREFN,appearsonpin15of the microcontroller. Onthe mbedit is connected directly to ground. 14.5.1 mbed DAC Control Registers Aswithall peripherals, theDAC hasaset of registersthat control itsactivity. Intermsof the ‘global’ registersthatwehavejustseen, theDACpowerisalwaysenabled, sothereisnoneed toconsiderthePCONP register. TheonlypinthattheDACoutputisavailableonisPort0pin 26, sowemustallocatethispinappropriately throughthePINSEL1register, asseeninTable 14.2. TheDAC output is labeledAOUT here. It is no surpriseto seeinthembedschematics that this pin is connected to mbed pin 18, the only mbed analog output. The only register specific to the DAC that we will use is the DACR register. This is comparatively simpleto grasp, andisshowninTable14.7. Wecanseethatthedigital inputto the DAC must be placed in here, in bits 6e15. Most of the rest of the bits are unused, apart from the bias bit, explained in the table. Applying Equation 4.1 to this 10-bit DAC, its output is given by: V0 ¼ðVREFP DÞ=1024 ¼ð3:3 DÞ=1024 where D is the value of the 10-bit number placed in bits 15e6 of the DACR register. 14.1 Letting Go of the mbed Libraries 311 Table 14.7: The DACR register Bit Symbol 5:0 Description Reset value e Reserved, user software should not write ones to reserved bits. Thevalueread froma reserved bit is not defined NA 15:6 VALUE After the selected settling time after this field is written with a new VALUE, the voltage on the AOUT pin (with respect to VSSA) is VALUE ((VREFP VREFN)/1024) þ VREFN 0 16 BIAS1 0 The settling time of the DAC is 1 ms maxand the maximum current is 700 mA. This allows a maximum update rate of 1 MHz 0 1 The settling time of the DAC is 2.5 ms max, and the maximum current is 350 mA. This allows a maximum update rate of 400 kHz 0 Reserved, user software should not write ones to reserved bits. Thevalueread froma reserved bit is not defined NA 31:17 Value e 1 The settling times noted in the description of the BIAS bit are valid for a capacitance load on the AOUT pin not exceeding 100 pF. A load impedance value greater than that value will cause settling time longer than the specified time. RedrawnfromNXP SemiconductorsUM10360LPC17xxUser Manual, Table539: D/A Converter register (DACRe address0x4008C000) bit description, with permission of NXP. 14.5.2 A DAC Application Let’s try now a simple program to drive the DAC, accessing it through the microcontroller control registers. ProgramExample14.4replicatesthesimplesawtoothoutput, whichwefirst achieved in Program Example 4.2. The program follows the familiar pattern of defining register addresses, and then setting these appropriately early in the main function. The PINSEL1 register is set to select DAC output on port bit 0.26. An integer variable, called dac_value, is then repeatedly incremented and transferred to the DAC input, in register DACR. It has to be shifted left six times, to place it in the correct bits of the DACR register. Betweeneachnewvalueof DAC input adelay is introduced. Theeffect of this is exploredin Exercise 14.5. /* Program Example 14.4: Sawtooth waveform on DAC output. View on oscilloscope. Port 0.26 is used for DAC output, i.e. mbed Pin 18 */ // function prototype void delay(void); // variable declarations int dac_value; //the value to be output //define addresses of control registers, as pointers to volatile data #define DACR (*(volatile unsigned long *)(0x4008C000)) 312 Chapter 14 #define PINSEL1 (*(volatile unsigned long *)(0x4002C004)) int main(){ PINSEL1=0x00200000; //set bits 21-20 to 10 to enable analog out on P0.26 while(1){ for (dac_value=0;dac_value<1023;dac_value=dac_value+1){ DACR=(dac_value<<6); delay(); } } } void delay(void) //delay function. //program continues Program Example 14.4 Sawtooth output on the DAC Compile the program and run it on an mbed; no external connections are needed. View the output from the mbed pin 18 on an oscilloscope. n Exercise 14.5 Measure the period of the sawtooth waveform. How does it relate to the delay value you measured in Exercise 14.1? Try varying the period by varying the delay value, or removing it altogether. Can you estimate how long a single digital-to-analog conversion takes? n 14.6 Using the ADC We now turn to controlling the ADC throughits registers, trying to replicate and develop the work doneinChapter5. Itisworthglancingback atFigure5.1, asthisrepresentsmany of the featuresthatwewill needto control. Thiswill includeselecting(oratleastknowingthevalue of) the voltage reference, clock speed and input channel, starting a conversion, detecting a completion and reading the output data. The ADC has a set of registers that control all this activity. The LPC1768 has eight inputs to its ADC, which appear e in order frominput 0 to input 7 e on pins 9e6, 21, 20, 99 and 98 of the microcontroller. A study of the mbed circuit shows that the lower six of these are used, connected to pins 15e20 inclusive of the mbed. 14.6.1 mbed ADC Control Registers The LPC1768 has a number of registers that control its ADC, particularly in its more sophisticated operation. However, wewill only apply two of these, the ADC control register (ADCR) andtheGlobal DataRegister(ADGDR). ThesearedetailedinTables14.8and14.9. As we have seen, the ADC can also be powered down; indeed, on microcontroller reset it is Letting Go of the mbed Libraries 313 Table 14.8: The AD0CR register Bit Symbol 7:0 Value Description Reset value SEL Selects which of the AD0.7:0 pins is (are) to be sampled and converted. For AD0, bit 0 selectsPin AD0.0, and bit 7 selects pin AD0.7. In software-controlled mode, onlyone of these bits should be 1. In hardware scan mode, any value containing 1 to 8 ones is allowed. All zeroes is equivalent to 0x01 0x01 15:8 CLKDIV TheAPB clock(PCLK_ADC0) isdivided by(thisvalueplus one) to produce the clock for the A/D converter, which should be less than or equal to 13 MHz. Typically, software should program the smallest value in this field that yieldsaclockof 13 MHzor slightlyless, but in certain cases (such as a high-impedanceanalog source) a slower clock may be desirable 0 16 BURST The AD converter does repeated conversions at up to 200 kHz, scanning(if necessary) through thepinsselected by bits set to ones in the SEL field. The first conversion after thestart corresponds to theleast significant 1 in the SEL field, then higher numbered 1-bits (pins) if applicable. Repeated conversions can be terminated by clearing this bit, but the conversion that’s in progress when this bit is cleared will be completed 0 1 Remark: START bits must be 000 when BURST ¼1 or conversions will not start 0 20:17 e 21 PDN Conversionsaresoftwarecontrolled and require65 clocks Reserved, user softwareshould not writeones to reserved bits. The value read from a reserved bit is not defined NA 1 The A/D converter is operational 0 0 The A/D converter is in power-down mode 23:22 e Reserved, user softwareshould not writeones to reserved bits. The value read from a reserved bit is not defined NA 26:24 START When the BURST bit is 0, these bits control whether and when an A/D conversion is started: 0 000 No start (this value should be used when clearing PDN to 0) 001 Start conversion now Further moreadvanced optionsfor START control areavailable, which also then applyEDGE RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table531: A/D Control Register (AD0CRe address0x4003 4000) bit description, with permission of NXP. 314 Chapter 14 switchedoff. Therefore, to enableit wewill haveto set bit 12inthePCONP register, seenin Table 14.4. 14.6.2 An ADC Application Program Example 14.5 provides a good opportunity to see many of the control registers in action. Channel 1 of the ADC is applied, which connects to pin 16 of the mbed. The configuration of the ADC must be done with care, so let’s read the program with diligence, starting fromthe comment ‘initialize the ADC’. The ADC channel wewant ismultiplexedwithbit 24of Port 0, so first wemust allocatethispinto the ADC. This is done through bits 17 and 16 of the PINSEL1 register (Table 14.2). We then enable the ADC, through the relevant bit in the PCONP register (Table 14.4). There follows quite a complex process of configuring the ADC, through the AD0CR register. We could set this register by transferring a single word. Instead, we shift in the relevant bits in turn. Check each with Table 14.8. C code feature The data conversion then starts in the while loop which follows. The comments contained in the program listing should give you a good picture of each stage. /* Program Example 14.5: A bargraph meter for ADC input, using control registers to set up ADC and digital I/O */ // variable declarations char ADC_channel=1; // ADC channel 1 int ADCdata; //this will hold the result of the conversion int DigOutData=0; //a buffer for the output display pattern // function prototype void delay(void); //define addresses of control registers, as pointers to volatile data //(i.e. the memory contents) #define PINSEL1 (*(volatile unsigned long *)(0x4002C004)) #define PCONP (*(volatile unsigned long *)(0x400FC0C4)) #define AD0CR (*(volatile unsigned long *)(0x40034000)) #define AD0GDR (*(volatile unsigned long *)(0x40034004)) #define FIO2DIR0 (*(volatile unsigned char *)( 0x2009C040)) #define FIO2PIN0 (*(volatile unsigned char *)( 0x2009C054)) int main() { FIO2DIR0=0xFF;// set lower byte of Port 2 to output, this drives bargraph //initialize the ADC PINSEL1=0x00010000; //set bits 17-16 to 01 to enable AD0.1 (mbed pin 16) PCONP j= (1 << 12); // enable ADC clock AD0CR = (1 << ADC_channel) // select channel 1 j (4 << 8) // Divide incoming clock by (4+1), giving 4.8MHz j (0 << 16) // BURST = 0, conversions under software control Letting Go of the mbed Libraries 315 j (1 << 21) j (1 << 24); // PDN = 1, enables power // START = 1, start A/D conversion now while(1) { AD0CR = AD0CR j 0x01000000; // infinite loop //start conversion by setting bit 24 to 1, //by ORing // wait for it to finish by polling the ADC DONE bit while ((AD0GDR & 0x80000000) == 0) { //test DONE bit, wait till it’ s 1 } ADCdata = AD0GDR; // get the data from AD0GDR AD0CR &= 0xF8FFFFFF; //stop ADC by setting START bits to zero // Shift data 4 bits to right justify, and 2 more to give 10-bit ADC // value - this gives convenient range of just over one thousand. ADCdata=(ADCdata>>6)&0x03FF; //and mask DigOutData=0x00; //clear the output buffer //display the data if (ADCdata>200) DigOutData=(DigOutDataj0x01); //set the lsb by ORing with 1 if (ADCdata>400) DigOutData=(DigOutDataj0x02); //set the next lsb by ORing with 1 if (ADCdata>600) DigOutData=(DigOutDataj0x04); if (ADCdata>800) DigOutData=(DigOutDataj0x08); if (ADCdata>1000) DigOutData=(DigOutDataj0x10); FIO2PIN0 = DigOutData; delay(); // pause } // set port 2 to Digoutdata } void delay(void){ //program continues //delay function Program Example 14.5 Applying the ADC as a bargraph Connect an mbed with a potentiometer between 0 and 3.3 V with the wiper connected to mbed pin 16. Connect five LEDs between pin and ground, from pin 22 to pin 26 inclusive. Compile and download your code to the mbed, and press reset. Moving the potentiometer should alter the number of LEDs lit, from none at all to all five. n Exercise 14.6 Add a digital input switch as in the previous example to reverse the operation of the analoginput. With thedigital switch in oneposition theLEDswill light fromright to left, but with the switch in the alternate position the DigOutData variable can be inverted to light LEDs in the opposite direction, from left to right. n 316 Chapter 14 Table 14.9: The AD0GDR register Bit Symbol Description Reset value 3:0 e Reserved, user softwareshould not writeones to reserved bits. The value read from a reserved bit is not defined NA 15:4 RESULT When DONE is 1, this field contains a binary fraction representingthevoltageon theAD0[n] pin selected bythe SEL field, asit fallswithin therangeof VREFP to VREFN. Zero in thefield indicates that thevoltageon theinput pin was less than, equal to, or closeto that on VREFN, while0x3FF indicatesthat thevoltageon theinput wascloseto, equal to, or greater than that on VREFP NA 23:16 e Reserved, user softwareshould not writeones to reserved bits. The value read from a reserved bit is not defined NA 26:24 CHN These bits contain the channel from which the RESULT bits were converted (e.g. 000 identifies channel 0, 001 channel 1 . ) NA 29:27 e Reserved, user softwareshould not writeones to reserved bits. The value read from a reserved bit is not defined NA 30 OVERRUN This bit is 1 in burst mode if the results of one or more conversions was (were) lost and overwritten before the conversion that produced the result in the RESULT bits. This bit is cleared by reading this register 0 31 DONE Thisbit isset to 1 when an A/D conversion completes. It is cleared when this register is read and when the ADCR is written. If theADCR iswritten whilea conversion isstill in progress, this bit is set and a new conversion is started 0 RedrawnfromNXP SemiconductorsUM10360 LPC17xxUser Manual, Table532: A/D Global DataRegister (AD0GDRe address0x4003 4004) bit description, with permission of NXP. n Exercise 14.7 Extend the bargraph so that it has eight or 10 LEDs. n 14.6.3 Changing ADC Conversion Speed One of the limitations of the mbed ADC library is the comparatively slow speed of conversion. Thiswas exploredinExercise5.6. Let’s try nowto vary this conversionspeedby adjusting the ADC clock speed. Letting Go of the mbed Libraries 317 Table 14.8 tells us that the ADC clock frequency should have a maximumvalue of 13 MHz, and that it takes 65 cycles of the ADC clock to complete a conversion. A quick calculation shows that the minimum conversion time possible is therefore 5 ms. It takes a very careful reading of the LPC1768 user manual (Reference 2.4) to gain a full picture of how the ADC clock frequency is controlled. The ADC clock is derived from the main microcontroller clock; there are several stages of division that the user can control in order to set up afrequency ascloseto13 MHz aspossible. ThefirstisthroughregisterPCLKSEL0, detailed in Tables 14.5 and 14.6. Bits 25 and 24 of PCLKSEL0 control the ADC clock division. We haveseenthat formost peripherals, includingtheADC, theclock canbedividedby 1, 2, 4or 8. On power-up the selection defaults to divide by 4. The clock may be further divided through bits 15e8 of the AD0CR register, seen in Table 14.8. Program Example 14.6 replicates Program Example 5.5, with some interesting results. It is also a useful example, as it combines ADC, DAC and digital I/O, therefore illustrating how these can be used together. It is made up of elements from programs earlier in this chapter, sometimes with adjustments; it should be possible to follow it through without too much difficulty. As sections of the programrepeat fromearlier examples, only the newer parts are reproduced here. The full program listing can be downloaded from the book website. /* Program Example 14.6: Explore ADC conversion times, programming control registers directly. ADC value is transferred to DAC, while an output pin is strobed to indicate conversion duration. Observe on oscilloscope */ . . . . int main() { FIO2DIR0=0xFF; // set lower bits port 2 to output PINSEL1=0x00210000; //set bits 21-20 to 10 for analog output (mbed p18) //and bits 17-16 to 01 to enable ADC channel 1 (AD0.1, mbed pin 16) //initialize the ADC. . . . . while(1){ // infinite loop // start A/D conversion by modifying bits in the AD0CR register AD0CR &= (AD0CR & 0xFFFFFF00); FIO2PIN0 |= 0x01; // OR bit 0 with 1 to set pin high AD0CR |= (1 << ADC_channel) | (1 << 24); // wait for it to finish by polling the ADC DONE bit while((AD0GDR & 0x80000000) == 0) { } FIO2PIN0 &= ~0x01; // AND bit 0 with 0 to set pin low ADCdata = AD0GDR; // get the data from AD0GDR AD0CR &= 0xF8FFFFFF; //stop ADC by setting START bits to zero // shift data 4 bits to right justify, and 2 more to give 10-bit ADC value ADCdata=(ADCdata>>6)&0x03FF; //and mask 318 Chapter 14 DACR=(ADCdata<<6); //delay(); } } . . //could be merged with previous line, // but separated for clarity //insert delay if wished Program Example 14.6 Applying ADC, DAC and digital output, to measure conversion duration You can use the same mbed configuration for this as you did for Program Example 14.5, although only the LED on pin 26 is necessary. Compile and run the program. First put an oscilloscope probe on pin 18, the DAC output. The voltage on this pin should change as the potentiometeris used. This confirms that theprogramis running. Nowmovetheprobeto pin 26; youwill see thepin pulsinghighfor the durationof theADC conversion. If youmeasure this, you should find it is 14 ms, or just under. To calculate the ADC clock frequency, and hence conversion time, remember that the mbed CCLK frequency is 96 MHz. We have not touched the PCLKSEL0 register, so the clock settingfortheADCwill be96 MHz dividedby theresetvalueof 4, or24 MHz. Thisisfurther divided by 5 in the ADC0CR setting seen in the programexample, leading to an ADC clock frequency of 4.8 MHz, or a period of 0.21 ms. Sixty-five cycles of 0.21 ms leads to the measurement duration mentioned in the previous paragraph. n Exercise 14.8 1. Adjust the setting of the CLKDIV bits in AD0CR in Program Example 14.7 to give the fastest permissible conversion time. Run the program, and check that your measured value agrees with the predicted value. 2. Can you now account for the value of ADC conversion time you measured in Exercise 5.6? n 14.7 A Conclusion on using the Control Registers Thischapterhasexploredtheuseof theLPC1768control registers,inconnectionwithuseof the digital I/O, ADC andDAC peripherals. This discussionhas demonstratedhowtheseregisters allowtheperipheralstobecontrolleddirectly, withoutusingthembedlibraries.Thishasallowed greaterflexibilityof useof theperipherals,atthecostof gettingintothetinydetail of theregisters andprogrammingat thelevel of thebitsthatmakethemup. Ordinarily, weprobably wouldnot want to programlikethis; it is timeconsuming, inconvenient anderrorprone. However, if we needaconfigurationorsettingnot offeredby thembedlibraries, this approachcanbeaway forward. Whilewehaveonly workedinthisway inconnectionwiththreeof theperipherals, itis Letting Go of the mbed Libraries 319 possibletodoitwithany of them. Itisworthmentioningthatthesethreeperipheralsaresomeof thesimplerones; someof theothers requireevenmoreattentionto detail. Chapter Review • This chapter introduced a different way of controlling the mbed peripherals. It demands a much deeper understanding of the mbed microcontroller, but allows for much greater flexibility. • Some registers relate to just one peripheral and others relate to microcontroller performance as a whole. • We have begun to implement features that are not currently available in the mbed library, for example in the change of the ADC conversion speed. • The chapter only introduces a small range of the control registers that are used by the LPC1768. However, it should have given you the confidence to look up and begin to apply any that you need. Quiz 1. The initialization section of a certain program reads: FIO0DIR0=0xF0; PINMODE0=0x0F; PINSEL1=0x00204000; Explain the settings that have been made. 2. An LPC1768 is connected with a 3.0 V reference voltage. Its DAC output reads 0.375 V. What is its input digital value? 3. On an LPC1768, the ADC clock is set at 4 MHz. How long does one conversion take? 4. A userwants to sampleanincomingsignal withanmbedADC at 44 kHz orgreater. What is the minimum ADC clock value? 5. Describe how the ADC clock frequency calculated in Question 4 can be set up. Reference 14.1. ARM Technical Support Knowledge Articles. Placing C variables at specific addresses to access memorymapped peripherals. http://infocenter.arm.com/help/index.jsp?topic¼/com.arm.doc.faqs/ka3750.html. Accessed January 2012. CHAPTER 15 Extension Projects Chapter Outline 15.1 Where do We Go from Here? 321 15.2 Pololu Robot for mbed 321 15.3 Advanced Audio Projects 323 15.4 The Internet of Things 323 15.5 Introducing the mbed LPC11U24 325 15.6 From mbed to Manufacture 326 15.7 Closing Thoughts 329 References 329 15.1 Where do We Go fromHere? A vast number of peripheral devices and applications can be used with mbed projects. In the scope of this book alone it is not possible to explore every technology or peripheral device, but the design and programming techniques covered will allow you to investigate wider concepts to develop advanced projects using the mbed. This chapter discusses a number of extension topics which suggest other areas for investigating and enjoying, as well as helping to bridge the gap between laboratory prototyping and the world of mass manufacturing. It is not possible to cover each of these aspects in detail, but an overview is provided to allow you to be creative in your approach to mbed projects and to give a springboard to more advanced and innovative systems. 15.2 Pololu Robot for mbed Pololu manufactures a number of robotics and electronics kits for developing embedded systems. Inparticular, thePololum3pi robot, whichfeaturesanmbedcontrol boardandahost of sensorsandactuators, isshowninFigure15.1. Therobothastwowheelsandisableto turn on its central point by rotating the wheels in opposite directions. For full details, see Reference 15.1. Fast and Effective Embedded Systems Design. DOI: 10.1016/B978-0-08-097768-3.00015-5 Copyright Ó 2012 Elsevier Ltd. All rights reserved. 321 322 Chapter 15 (a) (b) Figure 15.1: (a) Pololu m3pi robot with (b) mbed control board (Reference 15.1). (Image reproduced with permission of Pololu Corporation) The mp3i has an 8x2 character liquid crystal display (LCD) screen built in, as well as a number of buzzers and switches for input and output control. There are also several reflective sensors on the underside to allow development of line-tracking and maze-solving systems. Beyondthis, thereis auniversal serial bus (USB) port andanXBeesocket allowing wireless connectivity. Indeed, various projects have been prototyped by ARM to show the capabilities of the Pololu m3pi, in particular a system that allows control of the robot via a Nintendo Wii controller (see Reference 15.2). Extension Projects 323 15.3 Advanced Audio Projects So far, the audio projects we have discussed have used very simple implementations of the analog-to-digital converter (ADC), the digital-to-analog converter (DAC) or the pulse width modulation ports. In addition, some very simple analog circuitry has been used when implementingsimpledigital audiosamplingandanalogreconstructionsystems. However, the LPC1768 ADC is only 12-bit and the DAC is only 10-bit resolution, whereas high-quality audio generally requires 16-bit or even 24-bit resolution. Furthermore, having only asingleDAC meansthatthembedcannotdirectly outputstereo (two-channel) audio. If highquality stereo audio projects are to be developed it is possible to use a specialist ADC/DAC integrated circuit, such as the Texas Instruments TLV320AIC23b (Reference 15.3), which boasts stereo 24-bit resolution at sampling frequencies up to 96kHz. RS Components has announced the release of an mbed demo board (Reference 15.4) which includes a TLV320AIC23b ADC/DAC, and ARM has developed a number of libraries and support pages to interface the device (Reference 15.5). The mbed communicates with the TLV320 through an inter-integrated circuit sound (I2S) port. This is a serial interface specifically designedforconnectingdigital audio devicestogether. Wehavenotuseditinthis book, as it is not part of the ‘official’ mbed interconnection of Figure 2.1. However, it does appear in the LPC1768 block diagram of Figure 2.3, and there are means of routing it externally. 15.4 The Internet of Things TheInternetof Thingsisaphrasethathasevolvedto referto asystemof everyday objectsand sensors being connected to the Internet, allowing remote access to information that can be used to control and enhance everyday activities, while interacting with the mobile Internet devices that people are now carrying (for example smartphones). Initially, the Internet of Things referred to global logistical systems that allow advanced stock control and real-time tracking of delivery items. For example, when an itemis purchased froman online shop, the shop will have a detailed inventory of all the items held in stock. In general, when a shop receives items to its warehouse, the items are scanned in by an electronic system which evaluatessomebarcodedataandautomatically maintainsanaccuratestock register. Whenan itemisdispatchedto acustomer, theitemisscannedoutof thewarehouseandissubsequently scannedat various checkpoints along thedelivery route, allowingthecustomerto loginto an onlineportal andtrack thedelivery of theirpurchase. Ondelivery, thecustomerwill writean electronic signature into a portable device which will update the online delivery system to identify theitemasdelivered, andperhapsgenerateaninvoiceto besentto thecustomer. The whole process happens automatically, allowing the item to have an online status and the customeraccess to thestatus information. Thetechnology that allows this to happenis inthe 324 Chapter 15 barcodes, the barcode scanners, handheld scanning and signature systems, as well as the Internet server hardware and software that manage the tracking information. Technical advances in scanning and tracking processes are expected to continue, particularly with the development of cheaper and more advanced barcode scanners and the introduction of Quick Response (QR) codes which allow more data than a standard barcode to be encoded into an image. Figure 15.2 shows a QR code which, when scanned, will open the ARM mbed website. One advantage of using QR codes is that they effectively allow a one-way communication protocol with no wires and no electronic requirement in the slavesystem, which is very cost effective. They are also very tolerant to noise and image degradation. Using a QR code printed on an item, a QR scanner can find out a number of details about that item, essentially in a similar way to requesting a status messagevia any of the serial communication protocols previously discussed. People also have access to very accurate code scanners these days, as most smartphones are enabled with high-resolution cameras which, when equipped with barcode scanning software, such as that fromRedLaser (Reference 15.6), allow many people to scan items with little additional hardware cost. The QR code cannot be changed, of course, so there are limitations, but dynamic QR codes may be an innovation for the future! More recently, the Internet of Things concept has expanded to include everyday objects attachedto theInternet; forexample, allowingthedatafromatemperaturesensorononeside of the world to be used in a bespoke mobile phone application being accessed on the other side of theworld; or allowing people to control their household lighting and heating systems remotely over the Internet or via a smartphone, bringing potential fuel efficiency and home security improvements. In some cases the ideal application for this globally connected networkof dataandinformationhasyettoberealized, butitiswidely thoughtthatthistypeof Figure 15.2: QR code linking to www.mbed.org Extension Projects 325 data access and control will become commonplace, especially if systems are made open access (i.e. at no cost) to software developers and network users. ARM has recently developed a new concept for the mbed platform called ‘WebSockets’ (Reference15.7). WebSocketsallowmbeddevelopersto prototypesystemsthat adhereto the Internet of Things concept by giving webserver access to wireless- and Ethernet-equipped mbed systems. An mbed system can push sensor data to an ARM-managed WebSocket (a remote server) and the real-time data can be accessed globally by any Internet-equipped device. It is also possible to push data to the mbed through a WebSocket, hence allowing remote Internet control of the mbed system’s features. 15.5 Introducing the mbed LPC11U24 In early 2012 ARM released a second mbed platform, the mbed LPC11U24, based on the ARM Cortex-M0 microprocessor architecture. This device is aimed predominantly at prototyping low-power, portable applications and specifically those requiring USB functionality. The NXP LPC11U24 microcontroller is a 48MHz device with 8kB of RAM and 32kB of flashmemory. It also supports USB, two serial peripheral interface(SPI) buses, inter-integrated circuit (I2C) and universal asynchronous receiver/transmitter (UART) serial, and has six analog inputs and up to 30 digital input/output pins. The full pinout diagramfor the mbed LPC11U24 is shown in Figure 15.3. ThembedLPC11U24isdesignedto havethesameformfactorandpinlayoutastheoriginal mbed LPC1768, but with reduced functionality. So, in general, any programs compiled to run on the lower spec mbed LPC11U24 should execute with identical functionality on the mbed LPC1768. The mbed LPC11U24 is also specifically designed to have lower power consumption, so enabling prototyping of portable systems. Libraries for enabling sleep modeandinterrupt-drivenwakefunctionshavealso beenimplementedby ARM, andrecent tests showed the device drawing 16mA while awake and less than 2mA while asleep. However, it must be remembered that the device itself is for prototyping and any resultant production design based on the LPC11U24 could readily do away with a number of mbed hardware features and potentially reduce power consumption to lower levels still. A further application of the mbed LPC11U24 is as a key enabler for the Internet of Things and WebSockets concepts discussed earlier. The Internet of Things relies heavily on portable sensing devices and mass commercial take-up, so mobile communications, portability, low cost and low power prototyping are essential for these technologies to evolve. In addition to the mbed LPC11U24, ARM has developed a number of WebSockets libraries to allow mobile connectivity to the Internet, using the Roving Networks RN-131C WiFly module, which communicates with the mbed over standard UART serial (see Reference 15.8). 326 Chapter 15 Figure 15.3: mbed LPC11U24 pinout diagram. (Image reproduced with permission of ARM Holdings) 15.6 Frommbed to Manufacture The main thrust of this book has been focused towards rapid prototyping of embedded systems, using the ARM mbed. Rapid prototyping is an essential part of the design process, as it is the point where engineers need to seewhether a design concept will work and how it should be implemented in hardware and software. The speed of this process is important, because companies need to know where to invest their research and development resources and which products to develop into mass-market systems. The mbed is an excellent device for accelerating this process as its ease of use and high-level libraries allow continuous testing during the prototyping and proof-of-concept cycle. The easier it is to test a system, the easier it is to develop accurate solutions in a short space of time. There comes a time, however, when, if a prototype proves successful, a developer will wish to consider how the systemcould be engineered for mass manufacture and consumer use. At this stage a number of issues should be considered, in particular size, cost, power consumption, manufacturing methods, component availability and reliability, and quality control. So, the move froma working prototype to a commercially ready product is not an insignificant one, and thesoonertheseconsiderations can beincorporatedinto thedesignthe Extension Projects 327 lowertheriskof drasticfeaturechangesbeingrequiredatalaterstage. Figure15.4summarizes aproductdesigncycle, frominitial ideaandconceptdevelopment, throughprototypingtofinal commercialization. The role of the mbed in proof of concept can bevery clearly seen. Althoughthembedis designed as arapid prototypingdevice, it is intended to allow asimple development path from prototyping to commercialization. In large companies, research and development engineers will prototype and evaluate design concepts and a different set of engineers may be required to take successful prototypes to commercialization. However, in small industries it is not uncommon for a single engineer to see a product through the entire development cycle, so engineers must also have a working knowledge of the manufacturing constraints when working on prototyping and product development. Brainstorming Concept Development IDEAS PROOF OF CONCEPT Rapid Prototyping Market research Prototype Testing Design for Manufacture Schematic and printed circuit board design Component sourcing Negotiating costs and partnerships COMMERCIALIZATION Field Testing Product Launch Figure 15.4: A simplified product development cycle 328 Chapter 15 If only a few commercial units are to be built, then it is quite feasible to use the mbed as it stands as the core controller of the system. However, where thousands of units are to be developed and sold, cost and size become very important factors. It is therefore desirable to implement the mbed hardware components on a custom printed circuit board (PCB) design, inorderto minimizesizeandcost. Indeed, anumberof hardwarefeaturesonthembedcanbe removedforcertainhardwareimplementations, if developingabespokePCB, hencereducing cost and size further still. Guidanceontheprocess involvedintakinganmbedprototypeto themanufacturestagecan be found in Reference 15.9, while Reference 15.10 gives a good example. Essentially, the USB bootloader hardware features on the mbed (those which allow drag-and-drop downloading of the .bin file) are only required for prototyping. Furthermore, if the application does not use Ethernet, then the Ethernet features can be left off the PCB design too. In a production system, the program binary file needs downloading to the LPC1768 only once, although this is an important part of the manufacturing process. It would be inefficient to populate the bespoke PCB with all the USB capabilities of the mbed simply to program the device once, but thankfully it is possible to use an actual mbed as a gateway device to the LPC1768 on the PCB, allowing the chip to easily be programmed. Martin Smith’s description in Reference 15.10 of the development of a bespoke PCB containing all mbed features, except for Ethernet, JTAG and USB, is a useful guide for anyonelookingto developtheirownmbedPCBs. TheresultingPCB isshowninFigure15.5. The process of programming the LPC1768 on this PCB through a second mbed is also described. Figure 15.5: Bespoke PCB based on the mbed, showing the LPC1768 in place. (Image reproduced with permission of Martin Smith) Extension Projects 329 15.7 Closing Thoughts The mbed is shown to be a flexible and powerful device for the rapid prototyping of a number of electronic systems from electromechanical control to advanced Internet communications. The possibilities for projects involving the mbed are perhaps endless, and these latter chapters are intended to widen the developer’s creative perspective and give some examples of how the technology described can be applied to bigger and more advanced projects. The mbed itself is an innovative design, using a novel online compiler and a simple drag-and-drop USB interface. The aim is to make working with embedded systems simple, as often the learning curve is so steep that non-engineers rarely overcome the initial hurdles. The mbed is an excellent device to use for prototyping, education (both at early learning and higher education levels) and engagement between artistic and technological fields, where developers may not have aconventional engineering background. The idea is to make embedded systems design fun, accessible, yet productive, which the mbed does with ease. References 15.1. 15.2. 15.3. 15.4. 15.5. 15.6. 15.7. 15.8. 15.9. 15.10. Pololu m3pi robot with mbed socket. http://www.pololu.com/catalog/product/2151 mbed Robot Racing Wii. http://mbed.org/cookbook/mbed-Robot-Racing-Wii TLV320AIC23B low-power stereo CODEC with HP amplifier. http://www.ti.com/product/tlv320aic23b mbed now does audio. http://www.designspark.com/content/mbed-now-does-audio TLV320AIC23B. http://mbed.org/cookbook/TLV320AIC23B RedLaser is a scanning application for iPhone. http://redlaser.com/ The Internet of Things. http://mbed.org/cookbook/IOT Roving Networks RN-131 Wi-Fi module http://www.rovingnetworks.com/products/RN_131 Prototype to hardware. http://mbed.org/users/chris/notebook/prototype-to-hardware/ Turning an mbed into a custom PCB. http://mbed.org/users/ms523/notebook/turning-an-mbed-circuitinto-a-custom-pcb/ APPEN DIX A Some Number Systems A.1 Binary, Decimal and Hexadecimal Thenumbersystemwearemost familiarwith, decimal, makesuseof 10different symbolsto represent numbers, i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Each of these symbols represents anumber, andwemakelargernumbersby usinggroupsof symbols. Inthiscasethedigitmost to the right represents units, the next represents tens, the next hundreds, and so on. For example, the number 249, shown in Figure A.1, is evaluated by adding the values in each position: 2 hundredsþ 4 tensþ 9 units ¼249 or 2 102 þ 4 101 þ 9 100 ¼249 The base or radix of the decimal system, just described, is 10. We almost certainly count in the decimal system owing to the accident of having 10 fingers and thumbs on our hands. Thereis nothingintrinsically correct orsuperiorabout it. It is quitepossibleto count inother bases, and the world of digital computing almost forces us to do this. The binary counting system has a base or radix of 2. It therefore uses just two symbols, normally 0 and 1. These are called binary digits, or bits. Numbers are made up of groups of digits. The value each digit represents again depends upon its position in the number. Therefore, the 4-bit number 1101, shown in Figure A.2, is interpreted as: 1 8þ 1 4þ 0 2þ 1 1 ¼8þ 4þ 1 ¼13 Similarly, thevalue0110binary ¼6decimal. Notethatwereferto theunitsdigitas‘bit0’, or the least significant bit (LSB). The twos digit is called ‘bit 1’ and so on, up to the most significant bit (MSB). Figure A.1: The decimal number 249 331 332 Appendix A Figure A.2: The binary number 1101 We are obviously interested in binary representation of numbers, because that is how digital machines performmathematical operations. But sometimes therearejust too many 0s and1s to keep track of. We oftengroup bits in 4s, as we oftenlook at 4-bit numbers, 8-bit numbers, 12, 16, 20, 24, 28 and 32-bit numbers. A single byte is made up of 8 bits. With one byte we can count up to 255 in decimal; for example: 0000 0000 binary ¼0 decimal 1111 1111 binary ¼255 decimal 1001 1100 binary ¼128 +16 +8 +4 ¼156 The range of 0 to 255, offered by a single byte, is not very great, however. To perform mathematical calculations to ahigh accuracy we need to work with 16, 24 or32-bit systems. With 16 bits we can count or resolve up to 65535; for example: 1111 1111 1111 1111 binary ¼65535 decimal 0111 0111 0111 0110 binary ¼30582 decimal Working with large binary numbers is something that is just not easy for a human; we just cannot absorball those1s and0s. A very convenient alternativeis to usehexadecimal, which works to base 16. This means that we can now count up to 15 (decimal) before there is an overflow, and each new overflow column is an increased power of 16. Consider the hexadecimal number 371 as shown in Figure A.3. Here, we see that 371 in hexadecimal is (3 256) +(7 16) +1¼881 in decimal. Now we need to represent 16 numbers with just a single digit. We use the decimal digits for numbers 0 to 9, but to represent numbers 10 to 15 we use letters: ‘A’ or ‘a’ is adopted to represent decimal 10. Similarly, B or b¼11, C¼12, D ¼13, E¼14 and F¼15. As convention, we put ‘0x’ before a hexadecimal number; this means that all the bits before the Figure A.3: Hexadecimal number system Some Number Systems 333 Table A.1: 4-bit values in binary, hexadecimal and decimal 4-bit binary number Hexadecimal equivalent Decimal equivalent 0 0 0 0 0x0 0 0 0 0 1 0x1 1 0 0 1 0 0x2 2 0 0 1 1 0x3 3 0 1 0 0 0x4 4 0 1 0 1 0x5 5 0 1 1 0 0x6 6 0 1 1 1 0x7 7 1 0 0 0 0x8 8 1 0 0 1 0x9 9 1 0 1 0 0xA 10 1 0 1 1 0xB 11 1 1 0 0 0xC 12 1 1 0 1 0xD 13 1 1 1 0 0xE 14 1 1 1 1 0xF 15 number are zero or clear. For example, 0xE5¼14 16+5¼229. Table A.1 shows the equivalent 4-bit values in binary, hexadecimal and decimal. The great advantage of hexadecimal numbers is that we can represent 4-bit numbers with a single digit. An 8-bit number is represented with 2 hexadecimal digits, and 16-bit numbers with 4 digits. You can then see that by individually looking at groups of four bits, we can easily generate the hexadecimal equivalent, as with the following examples: 255 decimal ¼1111 1111 ¼0xFF 156 decimal ¼1001 1100 ¼0x9C 65535 decimal ¼1111 1111 1111 1111 ¼0xFFFF 30582 decimal ¼0111 0111 0111 0110 ¼0x7776 While we correctly use the two values of 0 and 1 in all binary numbers above, it is worth noting that different terminology is sometimes used when we apply electronic circuits to represent thesenumbers. Thisisdoneparticularly by thosewho arethinkingmoreintermsof the circuit than of the numbers. This terminology is shown in Table A.2. 334 Appendix A Table A.2: Some terminology for logic levels Logic 0 Logic 1 0 1 Off On Low High Clear Set Open Closed A.2 Representation of Negative Numbers: Two’s Complement Simple binary numbers allow only the representation of unsigned numbers, which under normal circumstances are considered to be positive. Yet we must have away of representing negative numbers as well. A simple way of doing this is by offsetting the available range of numbers. We do this by coding the largest anticipated negative number as zero and counting up from there. In the 8-bit range, with symmetrical offset, 128 can be represented as 00000000, 1000000 then represents zero, and 11111111 represents +127. This method of coding is called offset binary, and is illustrated in Table A.3. It is used on occasions (e.g. in Table A.3: Two’s complement and offset binary Two’s complement Decimal Offset binary 0111 1111 +127 1111 1111 0111 1110 +126 1111 1110 : : 0000 0001 +1 1000 0001 0000 0000 0 1000 0000 1111 1111 1 0111 1111 1111 1110 2 0111 1110 1000 0010 126 0000 0010 1000 0001 127 0000 0001 1000 0000 128 0000 0000 : : Some Number Systems 335 analog-to-digital converter outputs), but its usefulness is limited, as it is not easy to do arithmetic with. Let us consider an alternative approach. Suppose we took an 8-bit binary down counter, and clocked it from any value down to, and then below, zero. We would get this sequence of numbers: Binary Decimal 0000 0101 5 0000 0100 4 0000 0011 3 0000 0010 2 0000 0001 1 0000 0000 0 1111 1111 1? 1111 1110 2? 1111 1101 3? 1111 1100 4? 1111 1011 5? This gives a possible means of representing negative numbers: effectively, we subtract the magnitude of the negative number from zero, within the limits of the 8-bit number, or whatever other size is in use. This representation is called two’s complement. It can be shown that using two’s complement leads to correct results when simple binary addition and subtraction is applied. Two’s complement notation can be applied to binary words of any size. Thetwo’scomplementof ann-bitnumberisfoundby subtractingitfrom2n; thatiswherethe terminology comes from. Rather than doing this error-prone subtraction, an easier way of reaching the same result is to complement (i.e. change 1 to 0, and 0 to 1) all the bits of the positive number, and then add 1. Hence, to find 5 we follow the procedure: original number 0000 0101 (+5) complement all / 1111 1010 add one / 1111 1011 ( 5 in two’s complement) Toconvertback, simply subtract1andcomplementagain. Notethatthemostsignificantbitof atwo’scomplementnumberactsasa‘signbit’, 1fornegative, 0forpositive. The8-bitbinary range, shown for both two’s complement and offset binary, appears in Table A.3. 336 Appendix A A.2.1 Range of Two’s Complement Ingeneral, therangeof ann-bittwo’scomplementnumberisfrom 2(n 1) to+{2(n Table A.4 summarizes the ranges available for some commonly used values of n. 1) 1}. A.3 Floating Point Number Representation The numbers described so far all appear to be integers; we have not been able to represent any sort of fractional number, and their range is limited by the size of the binary word representing them. Suppose we need to represent really large or small numbers? Another way of expressing a number, which greatly widens the range, is called floating point representation. Ingeneral, anumbercanberepresentedasa re, whereaisthemantissa, r istheradix, ande is the exponent. This is sometimes called scientific notation. For example, the decimal number 12.3 can be represented as: 1.23 .123 12.3 123 1230 101 or 102 or 100 or 10 1 or 10 2 Floating point notation adapts and applies scientific notation to the computer world. The name is derived fromtheway the binary point can be allowed to float, by adjusting thevalue of theexponent, to makebest useof thebits availableinthemantissa. Standardformats exist for representing numbers by their sign, mantissa and exponent, and a host of hardware and software techniques exists to process numbers represented in this way. Their disadvantage lies in their greater complexity, and hence usually slower processing speed and higher cost. For flexible use of numbers in the computing world they are, however, essential. The most widely recognized and used format is the IEEE Standard for Floating-Point Arithmetic (known as IEEE 754). In single precision form this makes use of 32-bit Table A.4: Number ranges for differing word sizes Number of bits Unsigned binary Two’s complement 8 0 to 255 128 to +127 12 0 to 4095 2048 to +2047 16 0 to 65535 32768 to +32 767 24 0 to 16777 215 8388 608 to +8388 607 32 0 to 4 294967 295 2147 483648 to +2147483 647 Some Number Systems 337 Figure A.4: IEEE 754 32-bit floating point format representation for a number, with 23 bits for the mantissa, 8 bits for the exponent and a sign bit, as seeninFigureA.4. Thebinary point is assumedto bejust to theleft of theMSB of the mantissa. A further bit, always 1 for a non-zero number, is added to the mantissa, making it effectively a24-bitnumber. Zeroisrepresentedby 4zerobytes. Thenumber127issubtracted fromthe exponent, leading to an effective range of exponents from 126 to +127. Exponent 255 (leading to 128, when 127 is subtracted) is reserved to represent infinity. The value of a number represented in this format is then: ð 1Þsign 2ðexponent 127Þ 1:mantissa This allows number representation in the range: 1:175494 10 38 to 3:402823 10þ 38 APPEN DIX B Some C Essentials B.1 A Word about C This appendix aims to summarize all features of the C language used in this book, though not of the language as a whole. It is intended to be just adequate for the purpose of supporting the book, and should not be viewed as complete. With care and experimentation it can be used as an adequate introduction to the main features of the language. If you are a C novice, however, it is well worth having another reference source available, particularly as you consider the more advanced features. References B.1 and B.2 are both good. As youprogress throughthebook, youwill findyourself jumpingaround withinthematerial of this appendix. Do not feel you need to read it sequentially. Instead, read the different sections as they are referenced from the book. B.2 Elements of a C Program B.2.1 Keywords C has a number of keywords whose use is defined. A programmer cannot use a keyword for any otherpurpose, forexampleasadataname. KeywordsaresummarizedinTablesB.1e B.3. B.2.2 ProgramFeatures and Layout Simply speaking, a C program is made up of: Declarations All variables in C must be declared before they can be applied, giving as a minimum the variable name and its data type. A declaration is terminated with a semicolon. In simple programs, declarations appear as one of the first things in the program. They can also occur within the program, with significance attached to the location of the declaration. For example: float exchange_rate; int new_value; 339 340 Appendix B Table B.1: C keywords associated with data type and structure definition Word Summary meaning Word Summary meaning char A single character, usually 8-bit signed A qualifier applied to char or int (default for char and int is signed) const Data that will not be modified sizeof Returns the size in bytes of a specified item, which may be variable, expression or array double A ‘double precision’ floatingpoint number struct Allows definition of a data structure enum Defines variables that can only take certain integer values typedef Creates new name for existing data type float A ‘single precision’ floatingpoint number union A memory block shared by two or more variables, of any data type int An integer value unsigned A qualifier applied to char or int (default for char and int is signed) long An extended integer value; if used alone, integer is implied void No value or type short A short integer value; if used alone, integer is implied volatile A variable which can be changed by factors other than the program code Table B.2: C keywords associated with program flow Word Summary meaning Word Summary meaning break Causes exit from a loop for Defines a repeated loop e loop is executed as long as condition associated with for remains true case Identifies options for selection within a switch expression goto Program execution moves to labeled statement continue Allows a programto skip to theend of a for, while or do statement if Starts conditional statement; if condition is true, associated statement or code block is executed default Identifies default option in a switch expression, if no matches found return Returns program execution to calling routine, causingalso return of anydata value specified by function do Used with while to create loop, in which statement or code block following do is repeated as long as while condition is true switch Used with case to allow selection of anumber of alternatives; switch hasan associated expression which is tested against a number of case options else Used with if, and precedes alternative statement or codeblockto beexecuted if if condition is not true while Defines a repeated loop e loop is executed as long as condition associated with while remains true Some C Essentials 341 Table B.3: C keywords associated with data storage class Word Summary meaning Word Summary meaning auto Variable exists only within block within which it isdefined. Thisis the default class register Variable to be stored in a CPU register; thus, address operator (&) has no effect extern Declares data defined elsewhere static Declares variable which exists throughout program execution; the location of its declaration affects in what part of the program it can be referenced declare a variable called exchange_rate as a floating point number, and another variable called new_value as an integer. The data types are keywords seen in Tables B.1e B.3. Statements Statements are where the action of the program takes place. They perform mathematical or logical operations, and establish program flow. Every statement that is not a block (seebelow) endswithasemicolon. Statementsareexecutedinthesequencethey appearinthe program, except where program branches take place. For example, this line is a statement: counter = counter + 1; Space and Layout There is no strict layout format to which C programs must adhere. The way the program is laidoutandtheuseof spacearebothusedto enhanceclarity. Blank linesandindentsinlines, for example, are ignored by the compiler, but used by the programmer to optimize the program layout. Asanexample, theprogramthat thembedcompileralwaysstartsupwith, shownasProgram Example 2.1, could bewritten as shown here. It would not be easy to read, however. It is the semi-colonsattheendof eachstatement, andthebrackets, whichinreality definemuchof the program structure. #include "mbed.h" DigitalOut myled(LED1); int main() {while(1) {myled = 1; wait(0.2); myled = 0; wait(0.2);}} Comments Two ways of commentingareused. Oneis to placethecomment betweenthemarkers /* and */. This is useful for a block of text information running over several lines. Alternatively, when two forward slash symbols (//) are used, the compiler ignores any text that follows on that line only, which can then be used for comment. 342 Appendix B For example: /*A program which flashes mbed LED1 on and off, Demonstrating use of digital output and wait functions. */ #include "mbed.h" //include the med header file as part of this program Code Blocks Declarations andstatements canbegroupedtogetherinto blocks. A block is containedwithin braces, i.e. { and }. Blocks can and are written within other blocks, each within its own pair of braces. Keepingtrackof thesepairsof bracesisanimportantpastimeinCprogramming, as in a complex piece of software there can be numerous ones nested within each other. B.2.3 Compiler Directives Compiler directives are messages to the compiler, and do not directly lead to programcode. Compiler directives all start with a hash, #. Two examples follow. #include The#includedirectivedirectly insertsanotherfileinto thefilethatinvokesthedirective. This provides a feature for combining a number of files as if they were one large file. Angled brackets(< > ) areusedto enclosefiles heldinadirectory different fromthecurrent working directory, hence often for library files not written by the current author. Quotation marks are used to contain a file located within the current working directory, hence often user defined. For example: #include "mbed.h" #define The #define directive allows use of names for specific constants. For example, to use the numberp ¼3.141592intheprogram, wecouldcreatea#defineforthename‘PI’ andassign that number to it, as shown: #define PI 3.141592 Thename‘PI’ is thenusedinthecodewheneverthenumberis needed. Whencompiling, the compiler replaces the name in the #define with the value that has been specified. B.3 Variables and Data B.3.1 Declaring, Naming and Initializing Variables must be named, and their data type defined, before they can be used in a program. Keywords from Table B.1 are used for this. For example, Some C Essentials 343 int MyVariable; defines ‘MyVariable’ as a data type int (integer). It is possible to initialize the variable at the same time as declaration; for example, int MyVariable = 25; initializes MyVariable, and sets it to an initial value of 25. It is possible to give variables meaningful names, while still avoiding excessive length, for example ‘Height’, ‘InputFile’, ‘Area’. Variable names must start with a letter or an underscore; no other punctuation marks are allowed. Variable names are case sensitive. B.3.2 Data Types Whenadatadeclarationismade, thecompilerreservesforitasectionof memory, whosesize depends onthe typeinvoked. Examples of thelink betweendatatype, numberrange and memory size are shown in Table B.4. It is interestingto comparethesewithinformationon numbertypesgiveninAppendix A. Notethattheactual memory sizeappliedtodatatypescan vary between compilers. A full listing forthe mbed compilercan befound inReference B.3. B.3.3 Working with Data In C we can work with numbers in binary, fixed or floating point decimal, or hexadecimal format, depending on what is most convenient, and what number type and Table B.4: Example C data types, as implemented by the mbed compiler Data type Description Length (bytes) Range char Character 1 0 to 255 signed char Character 1 unsigned char Character 1 short Integer 2 unsigned short Integer 2 int Integer 4 2147483648 to +2147483647 long Integer 4 2147483648 to +2147483647 unsigned long Integer 4 float Floating point 1.17549435 3.40282347 double Floating point, double precision 2.22507385850720138 1.79769313486231571 128 to +127 0 to 255 32768 to +32767 0 to 65 535 0 to 4294967295 10 38 to 10+38 10 308 to 10+308 344 Appendix B range is required. For time-critical applications it is important to remember that floating point calculations can take much longer than fixed point. In general, it is easiest for us to work in decimal, but if a variable represents a register bit field or a port address, then it is usually more appropriate to manipulate the data in hexadecimal. When writing numbers in a program, the default radix for integers is decimal, with no leading 0 (zero). Octal numbers are identified with a leading 0. Hexadecimal numbers are prefixed with 0x. For example, if a variable MyVariable is of type char we can perform the following examples to assign a number to that variable: MyVariable = 15; //a decimal example MyVariable = 0x0E; //a hexadecimal example The value for both is the same. B.4 Functions A function is a section of code that can be called from another part of the program. So, if a particular piece of code is to be used or duplicated many times, we can write it once as a function, and then call that function whenever the specific operation is required. Using functions saves coding time and improves readability by making the code neater. Data can be passed to functions, and returned from them. Such data elements, called arguments, must beof atypethat is declaredinadvance. Only onereturnvariableis allowed, whose type must also be declared. The data passed to the variable is a copy of the original. Therefore, the function does not itself modify the value of the variable named. The impact of the function should thus be predictable and controlled. return type function name argument(s) type(s) and names(s) Close of function Figure B.1: Function example opening of function Some C Essentials 345 A functionisdefinedinaprogramby ablockof codehavingparticularcharacteristics. Itsfirst line forms the function header, with the format: Output_type function_name (variable_type_1 variable_name_1, variable_type_2 variable_name_2,. ) An example is shown in Figure B.1. The return type is given first. In this example, the keyword float is used. After the function name, in brackets, one or more data types may be listed, which identify the arguments which must be passed to the function. In this case two arguments are sent, one of type char and one of type float. Following the function header, apairof braces encloses thecodewhichmakes upthefunctionitself. This couldbeanything fromasinglelineto many pages. Thefinal statement of thefunctionmay beareturn, which will specify thevaluereturnedtothecallingprogram. Thisisnotessential if no returnvalueis required. B.4.1 The main Function Thecorecodeof any C programis containedwithinits‘main’ function. Otherfunctionsmay be written outside main( ), and called from within it. Program execution starts at the beginning of main( ). It must follow the structure just described. However, as main( ) containsthecentral program, onedoesnotexpect to sendanythingto it orto receiveanything from it. Therefore, usual patterns for main( ) are: void main (void){ void main (){ int main (){ The keyword void indicates that no data is specified. The mbed main( ) function applies the third option, as in C++int is the return type for main( ) normally used. B.4.2 Function Prototypes Just like variables, functions must be declared at the start of a program, before the main function. The declaration statements for functions are called prototypes. Each function in the code must have an associated prototype for it to run. The format is the same as for the function header. For example, the following function prototype applies to the function header seen above: float conversion(char currency, float number_of_pounds) This describes a function that takes inputs of a character value for the selected currency and a floating point (decimal) value for the number of pounds to be converted. The function returns the decimal monetary value in the specified currency. 346 Appendix B B.4.3 Function Definitions The actual function code is called the function definition. For example: float conversion(char currency, float number_of_pounds) { float exchange_rate; switch(currency) { case 'U': exchange_rate = 1.50; // US dollars break; case 'E': exchange_rate = 1.12 ); // Euros break; case 'Y': exchange_rate = 135.4); // Japan yen break; default: exchange_rate = 1); } exchange_value=number_of_pounds*exchange_rate; return(exchange_value); } This function can be called any number of times from within the main C program, or from another function, for example in this statement: ten_pounds_in_yen=conversion(‘ Y’ ,10.00); B.4.4 Using the static Storage Class with Functions The static data type is useful for defining variables within functions, where the data inside the function must be remembered between function calls. For example, if a function within a real-time system is used to calculate a digital filter output, the function should always remember its previous data values. In this case, data values inside the function should be defined as static; for example: float movingaveragefilter(float data_in) { static float data_array[10]; // define static float data array for (int i=8;i>=0;i--) { data_array[i+1]=data_array[i]; // shift each data value along } // (the oldest data value is discarded) data_array[0]=data_in; // place new data at index 0 float sum=0; for (int i=0;i<=9;i++) { sum=sum+data_array[i]; // calculate sum of data array } return sum/10; // return average value of array } B.5 Operators C has a wide set of operators, shown in Table B.5. The symbols used are familiar, but their application is not always the same as in conventional algebra. For example, a single ‘equals’ symbol, ¼, is used to assign a value to a variable. A double equals sign, ¼¼, is used to represent the conventional ‘equal to’. Some C Essentials 347 Table B.5: C operators Precedence and order Operation Symbol Precedence and order Operation Symbol Parentheses and array access operators 1, L to R Function calls () 1, L to R Point at member X-> Y 1, L to R Subscript [] 1, L to R Select member X.Y Arithmetic operators 4, L to R Add X+Y 3, L to R Multiply X*Y 4, L to R Subtract X Y 3, L to R Divide X/Y 2, R to L Unary plus +X 3, L to R Modulus % 2, R to L Unary minus 6, L to R Less than or equal to X< ¼Y X Relational operators 6, L to R Greater than X> Y 6, L to R Greater than or equal to X> ¼Y 7, L to R Equal to X¼¼Y 6, L to R Less than 7, L to R Not equal to X!¼Y 2, R to L NOT (1 if X¼0) !X X< Y Logical operators 11, L to R AND (1 if both X and Y X&&Y are not 0) 12, L to R OR (1 if either Xor Yare XjjY not 0) Bitwise operators 8, L to R Bitwise AND X&Y 2, L to R Ones complement (bitwise NOT) zX 10, L to R Bitwise OR XjY 5, L to R Right shift. X is shifted right Y times X[ Y 9, L to R Bitwise XOR XˆY 5, L to R Left shift. Xisshifted left X[ Y Y times Assignment operators 14, R to L Assignment X¼Y 14, R to L Bitwise AND assign X&¼Y 14, R to L Add assign X+¼Y 14, R to L Bitwise inclusive OR assign Xj¼Y 14, R to L Subtract assign X ¼Y 14, R to L Bitwise exclusive OR assign Xˆ¼Y 14, R to L Multiply assign X * ¼Y 14, R to L Right shift assign X [ ¼Y Continued 348 Appendix B Table B.5: C operatorsd cont’d Precedence and order Operation 14, R to L Divide assign 14, R to L Remainder assign Increment and decrement operators 2, R to L Preincrement 2, R to L Predecrement Conditional operators 13, R to L Evaluate either X (if Zs 0) or Y (if Z¼0) “Data interpretation” operators 2, R to L The object or function pointed to by X 2, R to L Cast e the value of X, with (scalar) type specified Precedence and order Operation Symbol X/¼Y X%¼Y 14, R to L Left shift assign X ++X X 2, R to L 2, R to L Postincrement Postdecrement X++ X Z?X:Y 15, L to R Evaluate X first, followed by Y X,Y *X 2, R to L The address of X &X (type) X 2, R to L The size of X, in bytes Sizeof X Symbol ¼Y Operators have a certain order of precedence, shown in Table B.5. The compiler applies this orderwhenitevaluatesastatement. If morethanoneoperatoratthesamelevel of precedence occurs in a statement, then those operators are evaluated in turn, either left to right or right to left, as shown in the table. For example, the line counter = counter + 1; contains two operators. Table B.5 shows that the addition operator has precedence level 4, while all assign operators have precedence 14. The addition is therefore evaluated first, followed by the assign. The outcome is that the variable counter is incremented by 1. B.6 Flow Control: Conditional Branching Flowcontrol coversthedifferentformsof branchingandloopingavailableinC. Asbranching and looping can lead to programming errors, C provides clear structures to improve programming reliability. B.6.1 If and else If statements always start with use of the if keyword, followed by a logical condition. If the condition is satisfied, then the code block that follows is executed. If the condition is not satisfied, thenthecodeisnotexecuted. Theremay ormay not also befollowingelseorelseif statements. Some C Essentials 349 Syntax: if (Condition1){ . C statements here }else if (Condition2){ . C statements here }else if (Condition3){ . C statements here }else{ . C statements here } The if and else statements are evaluated in sequence, i.e.: • else if statements are only evaluated if previous if or else if conditions have failed • else statements are only executed if all previous conditions have failed. For example, in the above example, the else if (Condition2) will only be executed if Condition1 has failed. Example: if (data > 10){ data += 5; }else if(data > 5){ data -= 3; }else{ nVal = 0; } //If we reach this point, data must be > 10 //If we reach this point, data must be <= 10 //If we reach this point, data must be <= 5 B.6.2 Switch Statements, and using break Theswitch statementallowsaselectionto bemadeof oneoutof several actions, basedonthe value of a variable or an expression given in the statement. An example of this structure has already appeared, in the example function in Section B.4.3. The structure uses no fewer than four C keywords. Selection is made from a list of case statements, each with an associated label e note that a colon following a text word defines it as a label. If the label equals the switch expression then the action associated with that case is executed. The default action (which is optional) occurs if none of the case statements is satisfied. The break keyword, which terminates each case condition, can be used to exit from any loop. It causes program execution to continue after the switch code block. B.7 Flow Control: ProgramLoops B.7.1 while Loops A whileloopisasimplemechanismforrepeatingasectionof code, until acertainconditionis satisfied. The condition is stated in brackets after the word while, with the conditional code block following. For example: 350 Appendix B i=1 while (i<10) { . C statements here i++ //increment i } Here, thevalueof i isdefinedoutsidetheloop; itisthenupdatedwithintheloop. Eventually i increments to 10, at which point the loop will terminate. The condition associated with the while statement is evaluated at the start of each loop iteration; the loop then only runs if the condition is found to be true. B.7.2 for Loops The for loop allows a different form of looping, in that the dependent variable is updated automatically every timetheloopisrepeated. Itdefinesaninitializedvariable, aconditionfor looping and an update statement. Note that the update takes place at the end of each loop iteration. If the updated variable is no longer true for the loop condition, the loop stops and program flow continues. For example: for(j=0; j<10; j++) { . C statements here } Here, theinitial conditionis j=0 andtheupdatevalueis j++, i.e. j is incremented. This means that j increments with each loop. When j becomes 10 (i.e. after10 loops), the condition j<10 is no longer satisfied, so the loop does not continue any further. B.7.3 Infinite Loops Weoftenrequireaprogramtoloopforever, particularly inasuper-loopprogramstructure. An infinite loop can be implemented by either of the following loops: while(1) { . continuously called C statements here } or for(;;) { . continuously called C statements here } B.7.4 Exiting Loops with break The break keyword can also be used to exit froma for or while loop, at any timewithin the loop. For example: while(i>5) { . C statements here if (fred = = 1) break; Some C Essentials 351 . C statements here } //end of while //execution continues here loop completion, or on break B.8 Derived Data Types Inadditiontothefundamental datatypes, therearefurtherdatatypesthatcanbederivedfrom them. Example types that we use are described in this section. B.8.1 Arrays and Strings An array is a set of data elements, each of which has the same type. Any data type can be used. Array elements are stored in consecutive memory locations. An array is declared with its name and the data type of its elements; it is recognized by the use of the square brackets following the name. The number of elements and their value can also be specified. For example, the declaration unsigned char message1[8]; defines an array called message1, containing eight characters. Alternatively, it can be left to the compiler to deduce the array length, as seen in the two examples here: char item1[] = "Apple"; int nTemp[] = {5,15,20,25}; In each of these the array is initialized as it is declared. Elements withinanarray canbeaccessedwithanindex, starting withvalue0. Therefore, for the first example above, message1[0] selects the first element and message1[7] the last. An access to message [8] would be outside the boundary of the array, and would give invalid data. The index can be replaced by any variable that represents the required value. Importantly, thenameof anarray is set equal to theaddress of theinitial element. Therefore, when an array name is passed in a function, what is passed is this address. A string is a special array of type char that is ended by the NULL (\0) character. The null character allows code to search for the end of a string. The size of the string array mustthereforebeonebytegreaterthanthestringitself, tocontainthischaracter. Forexample, a 20-character string could be declared: char MyString[21]; // 20 characters plus null B.8.2 Pointers Insteadof specifyingavariableby name, wecanspecify itsaddress. InCterminology suchan addressiscalledapointer. A pointercanbeloadedwiththeaddressof avariableby usingthe unary operator ‘&’, like this: my_pointer = &fred; 352 Appendix B Thisloadsthevariablemy_pointer withtheaddressof thevariablefred; my_pointer isthen said to point to fred. Doing things the other way round, the value of the variable pointed to by a pointer can be specified by prefixing the pointer with the ‘*’ operator. For example, *my_pointer can be read as ‘the value pointed to by my_pointer’. The * operator, used in this way, is sometimes called the dereferencing or indirection operator. The indirect value of a pointer, for example *my_pointer, can be used in an expression just like any other variable. A pointer is declared by the data type it points to. Thus, int *my_pointer; indicates that my_pointer points to a variable of type int. We can also use pointers with arrays, because an array is really just a number of data values stored at consecutive memory locations. So, if the following is defined: int dataarray[]={3,4,6,2,8,9,1,4,6}; int *ptr; ptr = &dataarray[0]; // define an array of arbitrary values // define a pointer // assign pointer to the address of // the first element of the data array given the previous declarations, the following statements will therefore be true: *ptr = = 3; *(ptr+1) = = 4; *(ptr+2) = = 6; // the first element of the array pointed to // the second element of the array pointed to // the third element of the array pointed to Thus, array searching can be done by moving the pointer value to the correct array offset. Pointersarerequiredforanumberof reasons, butonesimplereasonisbecausetheC standard doesnotallowusto passarraysof datato andfromfunctions, sowemustusepointersinstead to get around this. B.8.3 Structures and Unions Structures and unions are both sets of related variables, defined through the C keywords struct andunion. Inaway they arelikearrays, but inbothcasesthey canbeof dataelements of different types. Structure elements, called members, are arranged sequentially, with the members occupying successive locations in memory. A structure is declared by invoking the struct keyword, followed by an optional name (called the structure tag), followed by a list of the structure members, each of these itself forming a declaration. For example: struct resistor {int val; char pow; char tol;}; Some C Essentials 353 declares a structure with tag resistor, which holds the value (val), power rating (pow) and tolerance (tol) of a resistor. The tag may come before or after the braces holding the list of structure members. Structure elements are identified by specifying the name of the variable and the name of the member, separated by a full stop (period). Therefore, resistor.val identifies the first member of the example structure above. Likeastructure, aunioncanholddifferenttypesof data. Unlikethestructure, unionelements all beginatthesameaddress.Hence,theunioncanrepresentonlyoneof itsmembersatanyone time, andthesizeof theunionis thesizeof thelargest element. It is upto theprogrammerto trackwhichtypeiscurrentlystored.Unionsaredeclaredinaformatsimilartothatof structures. Unions, structures and arrays can occur within each other. B.9 C Libraries and Standard Functions B.9.1 Header Files All but the simplest of C programs are made up of more than one file. In general, many files are combined together in the process of compiling, for example original source files combining with standard library files. To aid this process, a key section of any library file is detached and created as a separate header file. Header filenames end in.h; thefile typically includes declarations of constants and function prototypes, and links on to other library files. The function definitions themselves stay in the associated .c or.cpp files. In order to use the features of the header file and the file(s) it invokes, itmustbeincludedwithinany programaccessingit, using#include. Weseembed.h being included in every program in the book. Note also that the .c file where the function declarations appear must also include the header file. B.9.2 Libraries, and the C Standard Library BecauseC isasimplelanguage, muchof itsfunctionality derivesfromstandardfunctionsand macros that are available in the libraries accompanying any compiler. A C library is a set of precompiled functions that can be linked in to the application. These may be supplied withacompiler, availablein-company, ormay bepublicdomain. Notably, thereisaStandard Library, definedintheC ANSI standard. Thereareanumberof standardheaderfiles, usedfor different groups of functions within the standard library. For example, the < math.h> header file is used for a range of mathematical functions (including all trigonometric functions), while < stdio.h> contains the standard input and output functions, including the printf function. 354 Appendix B B.9.3 Using printf This versatile function provides formatted output, typically for sending display data to a PC screen. Text, data, formatting and control formatting can be specified. Only summary informationisprovidedhere; afull statementcanbefoundinReferenceB.1. Examplesbelow are taken from book chapters. In each case the function appears in the form pc.printf( ), indicating that printf( ) is being used as a member function of a C++class pc created in the example program. This does not affect the format applied. Simple Text Messages pc.printf("ADC Data Values. \n\r"); \\send an opening text message Thisprintsthetextstring‘ADCDataValues. ’ toscreen, andusescontrol characters\nand\r to force a new line and carriage return, respectively. Data Messages pc.printf("%1.3f",ADCdata); Thisprintsthevalueof thefloat variableADCdata. A conversionspecifier, initiatedby the% character, defines the format. Within this, the ‘f’ specifies floating point, and the .3 causes output to three decimal places. pc.printf("%1.3f \n\r",ADCdata); \\send the data to the terminal As above, but includes \n and \r to force a new line and carriage return. Combination of Text and Data pc.printf("random number is %i\n\r", r_delay); Thisprintsatextmessage, followedby thevalueof int variable(indicatedby the‘i’ specifier) r_delay. pc.printf("Time taken was %f seconds\n", t.read()); //print timed value to pc This prints a text message, followed by the return value of function t.read( ), which is of type float. B.10 File Access Operations B.10.1 Overview In C we can open files, read and write data and also scan through files to specific locations, even searching for particular types of data. The commands for input and output operations are all defined by the C stdio library, already mentioned in connection with printf( ). Some C Essentials 355 The stdio library uses the concept of streams to manage the data flow. All streams have similar properties, even though the actual application of the data flow may be very varied. Streams are represented in the stdio library as pointers to FILE objects, which uniquely identify the stream. We can store data in files (as chars) or we can store words and strings (as character arrays). A summary of useful stdio file access library functions is given in Table B.6. B.10.2 Opening and Closing Files A file can be opened with the following command: FILE* pFile = fopen("datafile.txt","w"); This assigns a pointer with name pFile to the file at the specific location given in the fopen statement. In this example the access mode is specified with a ‘w’, and a number of other file open access modes, and their specific meanings, are shown in Table B.7. When ‘w’ is the access mode (meaning write access), if the file does not already exist then the fopen command will automatically create it in the specified location. When you have finished using a file for reading or writing it is good practice to close it, for example with fclose(pFile); Table B.6: Useful stdio library functions Function Format Summary action fclose int fclose ( FILE * stream ); Closes a file fgetc int fgetc ( FILE * stream ); Gets a character from a stream fgets char * fgets ( char * str, int num, FILE * stream ); Gets a string from a stream fopen FILE * fopen ( const char * filename, const char * mode); Opens the file of type file and name filename fprintf int fprintf ( FILE * stream, const char * format, . ); Writes formatted data to a file fputc int fputc ( int character, FILE * stream ); Writes a character to a stream fputs int fputs ( const char * str, FILE * stream ); Writes a string to a stream fseek int fseek ( FILE * stream, long int offset, int origin ); Moves the file pointer to the specified location str: an arraycontainingthenull-terminated sequenceof charactersto bewritten; stream: pointer to aFILE object that identifies the stream where the string is to be written. 356 Appendix B Table B.7: Access modes for fopen Access mode Action ‘r’ Open an existing file for reading ‘w’ Create a new empty file for writing. If a file of the same name already exists it will be deleted and replaced with a blank file ‘a’ Append to a file. Writeoperationsresult in data beingappended to theend of thefile. If the file does not exist a new blank file will be created ‘r+’ Open an existing file for both reading and writing ‘w+’ Createa new emptyfilefor both reading and writing. If a fileof thesamenamealready exists it will be deleted and replaced with a blank file ‘a+’ Open a filefor appendingor reading. Writeoperationsresult in data beingappended to the end of the file. If the file does not exist a new blank file will be created B.10.3 Writing and Reading File Data If the intention is to store numerical data, this can be done in a simple way by storing individual 8-bit data values. The fputc command allows this, as follows: char write_var=0x0F; fputc(write_var, pFile); Thisstoresthe8-bitvariablewrite_var tothedatafile. Thedatacanalso bereadfromafileto a variable as follows: read_var = fgetc(pFile); Using the stdio.h commands, it is also possible to read and write words and strings with fgets( ) and fputs( ), and to write formatted data with fprintf( ). It is also possible to search or move through files looking for particular data elements. When reading data from a file, the file pointer can be moved with the fseek command. For example, the following command will reposition the file pointer to the 8th byte in the text file: fseek (pFile , 8 , SEEK_SET ); // move file pointer to 8 bytes from the start Thefirst termof thefseek( ) functionis thestream(thefilepointername), thesecondtermis thepointeroffset valueandthethirdtermis theoriginforwheretheoffset shouldbeapplied. There are three possible values for the origin as shown in Table B.8. The originvalues have predefined names as shown. Further details on the stdio commands and syntax can also be found in References B.1 and B.2. Some C Essentials 357 Table B.8: fseek origin values Origin value Description SEEK_SET Beginning of file SEEK_CUR Current position of the file pointer SEEK_END End of file B.11 Towards Professional Practice Thereadability of aC programis muchenhancedby goodlayout onthepageorscreen. This helps to produce good and error-free code, and enhances the ability to understand, maintain and upgrade it. Many companies impose a ‘house style’ on C code written for them; such guides can be found online. Thevery simplestyleguideadoptedinthisbookshouldbeexemplifiedinany of theprograms reproduced. It includes: • • • • • • Courier New font applied opening header text block, giving overview of program action blank lines used to separate major code sections extensive commenting opening brace of any code block placed on the line which initiates it code within any code block indented 2 spaces compared with code immediately outside the block • closing brace stands alone, indented to align with line initiating code block. Versioncontrol is essential practiceinany professional environment. Forclarity, wehavenot displayed version control information within the programs as reproduced in the book, althoughthiswasdoneinthedevelopmentprocess. Minimal versioncontrol withinthesource code (spaced within the header text block) would include the date of origin, name of the original author, name of the person making the most recent revision, and date. References B.1. Prinz, P. and Kirch-Prinz, U. (2003). C Pocket Reference. O’Reilly. B.2. The C++Resources Network. www.cplusplus.com B.3. ARM. RealViewÒ CompilationTools. Version4.0. CompilerReferenceGuide. December2010. DUI 0348C (ID101213). APPEN DIX C mbed Technical Data C.1 Summarizing Technical Details of the mbed The mbed is built around an LPC1768 microcontroller, made by NXP Semiconductors. The LPC1768 is, in turn, designed around an ARM Cortex-M3 core, with 512kB flash memory, 64kB RAM, and a wide range of interfaces, including Ethernet, universal serial bus (USB) device, Controller Area Network (CAN), serial peripheral interface (SPI), inter-integrated circuit (I2C) and other input/output (I/O). It runs at 96MHz. Full technical details of the mbed and LPC1768 can be found in References 2.1 to 2.4. Summary mbed operating conditions are given directly below. Package: • 40-pinDIPpackage,with0.1inchspacingbetweenpins,and0.9inchesbetweenthetworows. • Overall size: 2inches 1inch, 53mm 26mm. Power: • Powered through the USB connection, or 4.5e9.0V applied to VIN (see Figure 2.1). • Power consumption < 200mA (100mA approx. with Ethernet disabled). • Real-time clock battery backup input VB; 1.8e3.3V at this input keeps the Real Time Clock running. This requires 27m A, which can be supplied by a coin cell. • 3.3V regulated output on VOUT available to power peripherals. • 5.0V from USB available on VU, available only when USB is connected. • Total supply is current limited to 500mA. • Digital I/O pins are 3.3V, 40mA each, 400mA maximum total. Reset: • nR e Active-low reset pin with identical action to the reset button. Pull-up resistor is on the board. C.2 LPC1768 Electrical Characteristics To interface successfully to any microcontroller, certain electrical conditions must be satisfied. Many digital componentsaredesignedto becompatiblewitheachother, so inmany situations we do not need to worry about this. Once it comes to applying non-standard 359 360 Appendix C devices, however, it is very important to gain an understanding of interfacing requirements. Input signals haveto liewithincertain thresholds in order to be correctly interpreted as logic levels. We need also to understand the ability of an output to drive external loads that may be connected to it. These operating conditions for the mbed are referred to in Chapter 3 and from time to time onwards. They are specified precisely, and in very great detail, by the manufacturer of any electronic component or integrated circuit, in the relevant datasheet. It is part of the skill of aprofessional designengineertoknowwhereto accessthesedetails, to knowhowto interpret them and to be able to design to meet the criteria specified. The hobbyist can engage creatively orintuitively insometrial anderror, andhopefor thebest. The professional needs to be able to predict analytically the performance of a design. Inside the mbed is the LPC1768 microcontroller; when interfacing with the mbed we are actually directly interfacing with an LPC1768. We therefore turn to the LPC1768 datasheet (Reference 2.3). For a novice reader this is a very complex document. We have therefore extracted a very limited amount of data which contains some of the main details required. Some of these lead to the mbed figures quoted above; others indicate operating conditions within which the mbed figures apply. C.2.1 Port Pin Interface Characteristics Table C.1 is drawn mainly from Table 7 of Reference 2.3, and defines port pin operating characteristics. The format of Reference 2.3 is retained as far as possible, but for simplicity afewof thefinerdetailsof operationareremoved. Eachparameterthat appearsinthetableis described here. • Supply voltage (3.3 V), VDD(3V3) e This is the power supply voltage connected to the VDD(3V3) pin of the microcontroller. Although nominally 3.3V, the minimum acceptable supply voltage for this pin is seen to be 2.4V, and the maximum 3.6V. This pin is one of several supply inputs, and supplies the port pins. • LOW-level input current, IIL e This is the current flowing into a port pin, with pull-up resistor disabled, when the input voltage is at 0V. This very low current implies a very high input impedance. • HIGH-level input current, IIH e This is the current flowing into a port pin, with pull-down resistor disabled, when the input voltage is equal to VDD(3V3). This very low current implies a very high input impedance. • Input voltage, VI e This indicates the legal range of input voltages to any port pin. Unsurprisingly, the minimum is 0V. Interestingly, the maximumis 5V, showing that the pin input can actually exceed the supply voltage. This is a very useful feature, and allows interfacing to a system supplied from 5V. mbed Technical Data 361 Table C.1: Selected port pin characteristics Symbol Parameter Conditions Minimum Typical Maximum Unit VDD(3V3) Supply voltage (3.3 V) External rail 2.4 3.3 3.6 V IIL LOW-level input current VI ¼ 0 V; on-chip pull-up resistor disabled e 0.5 10 nA IIH HIGH-level input current VI ¼ VDD(3V3); on-chip pull-down resistor disabled e 0.5 10 nA VI Input voltage pin configured to provide a digital function 0 e 5 V VO Output voltage output active 0 e VDD(3V3) V VIH HIGH-level input voltage 0.7VDD(3V3) e e V VIL LOW-level input voltage e e 0.3VDD(3V3) V VOH HIGH-level output voltage IOH ¼ e V VOL LOW-level output voltage IOL ¼ 4mA e 0.4 V IOH HIGH-level output current VOH ¼ VDD(3V3) e e mA IOL LOW-level output current VOL ¼ 0.4V 4 e e mA IOHS HIGH-level shortcircuit output current VOH ¼ 0V e e IOLS LOW-level shortcircuit output current VOL ¼ VDD(3V3) e e 50 mA Ipd Pull-down current VI ¼ 5 V 10 50 150 m A Ipu Pull-up current VI ¼ 0 V 85 m A 4mA VDD(3V3) e 0.4V 4 15 0.4 e 45 50 mA • Output voltage, VO e This indicates the range of output voltages that a port pin can source. The limits are 0V and the supply voltage. • HIGH-level input voltage, VIH e This parameter defines the range of voltages for an input to be recognized as a Logic 1. Any input voltage exceeding (VDD(3V3) 0.4) V is interpreted as Logic 1. In this context there is no need for a typical or maximum value, although the maximum is contained within the definition for VI. VIH is illustrated in Figure 3.1. 362 Appendix C • LOW-level input voltage, VIL e This parameter defines the range of voltages for an input to be recognized as a Logic 0. Any input voltage less than 0.4V is interpreted as Logic 0. In this context there is no need for a typical or minimum value, although the minimum is contained within the definition for VI. VIL is illustrated in Figure 3.1. • HIGH-level output voltage, VOH e This indicates the output voltage, for a Logic 1 output. Thevalue is defined for a load current of 0.4mA, where the convention is applied thatacurrentflowingoutof alogicgateterminal isnegative. Considerthatacircuitsuchas Figure 3.3b applies. For this output current the minimum output voltage is (VDD(3V3) 0.4) V. With no output current the output voltage will be equal to VDD(3V3). The values quotedimply anapproximateoutput resistanceof 100U undertheseoperatingconditions. • LOW-level output voltage, VOL e Thisindicatestheoutput voltage, foraLogic 0output. The value is defined for a load current of 0.4mA, where the convention is applied that a current flowing out of a logic gate terminal is positive. Consider that a circuit such as Figure 3.3c applies. For this output current the maximumoutput voltage is 0.4V. With no output current the output voltage will be equal to 0V. The values quoted imply an approximate output resistance of 100U under these operating conditions. • HIGH-level output current, IOH e This gives the same information as the HIGH-level output voltage, VOH. • LOW-level output current, IOL e This gives the same information as the LOW-level output voltage, VOL. • HIGH-level short-circuit output current, IOHS e This gives the maximum output current if the output is at Logic 1, but is short-circuited to ground. • LOW-level short-circuit output current, IOLS e This gives the maximum output current if the output is a Logic 0, but is connected to the supply, VDD(3V3). • Pull-down current, Ipd e This is the current which flows due to the internal pull-down resistor, when enabled, when VI ¼ 5V. • Pull-up current, Ipu e This is the current whichflows due to theinternal pull-upresistor, when enabled, when VI ¼ 0V. Table C.2: Selected limiting values Symbol Parameter Conditions Minimum Maximum Unit VDD(3V3) Supply voltage (3.3 V) External rail 2.4 3.6 V VI Input voltage 5 V tolerant I/O pins; only valid when the VDD(3V3) supplyvoltage is present +5.5 V IDD Supply current Per supply pin e 100 mA ISS Ground current Per ground pin e 100 mA 0.5 mbed Technical Data 363 C.2.2 Limiting Values The values in the previous section showed the limits to which operating conditions could be taken, while maintaining normal operation. Limiting values (Table C.2), also called absolute maximumvalues, definethelimitsthatmustbemaintained, otherwisedevicedamageoccurs. These must, of course, always be observed. For example, although a single port pin can supply up to 45mA when short-circuited, one must also take note of the limiting value for supply and ground currents. APPEN DIX D Parts List To getstartedwiththepractical exercisesinthisbookyouwill of courseneedanmbed. There is some flexibility in almost any other component or subsystem after that. The items listed below are the ones we used, sourced from the supplier shown; in most cases it is easy to substitute others. As is the way with electronics, some of these parts are likely to become obsolete and you will have to seek an alternative. Although we identify certain suppliers, there are many alternatives. Table D.1: Components and devices used in the book Description Supplier Supplier code NXP mbed prototyping board LPC1768 www.rs-online.com 703-9238 Prototyping breadboard www.rapidonline.com 34-0664 OR 34-0550 Jumper wire kit www.rapidonline.com 34-0495 OR 34-0555 Chapter 2 Chapter 3 LED, 5 V, red www.rapidonline.com 56-1500 LED, 5 V, green www.rapidonline.com 56-1505 Switch PCB mount SPDT www.rapidonline.com 76-0200 Photointerrupter/Slotted Optoswitch www.rapidonline.com 58-0944 OR 58-0303 Kingbright 7-segment display www.rapidonline.com 57-0115 Switching transistor, ZVN4206 www.rapidonline.com 47-0162 Motor, 6 V, DC www.rapidonline.com 37-0161 Battery box, 4 AA www.rapidonline.com 18-2913 OR 18-2909 Diode, IN4001 www.rapidonline.com 47-3420 Chapter 4 Servo Hitec HS-422 www.active-robots.com HS-422 Piezo transducer (‘buzzer’) www.rapidonline.com 35-0200 Chapter 5 10k linear potentiometer www.rapidonline.com 65-0715 Continued 365 366 Appendix D Table D.1: Components and devices used in the bookd cont’d Description Supplier Supplier code NORPS12 light-dependent resistor www.rapidonline.com 58-0132 10k resistor www.rapidonline.com 62-2146 LM35 temperature sensor www.rapidonline.com 82-0240 Chapter 6 (No new items) Chapter 7 (two mbeds and breadboards required for some builds) Triple-axis accelerometer breakout, ADXL345 www.sparkfun.com SEN-09836 4k7 resistor www.rapidonline.com 62-2130 Push-button switch, red www.rapidonline.com 78-0160 Push-button switch, green www.rapidonline.com 78-0155 Digital temperature sensor breakout, TMP102 www.sparkfun.com SEN-09418 Ultrasonic range finder, SRF08 www.rapidonline.com 78-1086 Chapter 8 PC1602 alphanumeric LCD display www.rapidonline.com 57-0913 Nokia 6610 display www.coolcomponents. co.uk 000147 Chapter 9 ICL7611 op amp www.rapidonline.com 82-0782 Chapter 10 Breakout board for MicroSD transflash www.sparkfun.com BOB-00544 Transcend MicroSD card www.rapidonline.com 19-9123 Chapter 11 1.5k resistor www.rapidonline.com 62-2106 47k resistor www.rapidonline.com 62-2178 4.7nF capacitor www.rapidonline.com 08-0995 10 mF capacitor www.rapidonline.com 11-0840 0.1mF capacitor www.rapidonline.com 08-1020 Parts List 367 Chapter 12 RN-41 Bluetooth module (2 required) www.sparkfun.com WRL-10559 Ethernet RJ45 8-pin connector www.sparkfun.com PRT-00643 Ethernet RJ45 breakout board www.sparkfun.com BOB-00716 Chapter 13 HMC6352 digital compass module www.sparkfun.com SEN-07915 Servo e continuous rotation www.oomlout.co.uk NA MCP2551 CAN transceiver (2 required) www.farnell.com 9758569 Chapter 14 (No new items) Chapter 15 Pololu m3pi robot with mbed socket www.pololu.com 2151 WiFly GSX breakout RN-131C www.sparkfun.com WRL-10050 NXP mbed prototyping board LPC11U24 www.rs-online.com 751-0725 Note: Order codes and suppliers change very rapidly. Check that each code is correct for the part you wish to order, before placing the order. APPEN DIX E The Tera TermTerminal Emulator E.1 Introducing Terminal Applications A terminal emulator allows a host computer to send or receive data from another computer, through a variety of links. Terminal emulators simply take the form of a software package runningonthehost computerwhichcreates animageonthecomputerscreen, throughwhich settings can be selected. It then provides a context for data transfer, using the host computer keyboard for data input. Such a terminal is particularly useful for displaying messages from the mbed to a computer screen. It can become a very useful tool for user interfacing and software debugging. For example, status or error messages can be embedded into a program running on the mbed, and transferred to the terminal emulator when certain points in the program are reached. Whileanumberof terminal emulatorsareavailable, TeraTermis recommendedby thembed team. This is afreeandopensourceterminal emulatorwhichallows host PC communication withthembed. Inorderto useTeraTermwithaWindowsPC, youwill firsthaveto install the WindowsSerial Driver; thiscanbeinstalledfromtheHandbook sectionof thembedwebsite, at time of writing http://mbed.org/handbook/Windows-serial-configuration. Note that you needtoruntheinstallerforevery mbed, asWindowsloadsthedriverbasedonthembedserial number. The Tera Term support page can be viewed at http://logmett.com/ E.2 Setting up and Testing Tera Term Open the Tera Term application. You will need to perform the following configuration: • Select File / New Connection (or just press Alt+N). • Select the Serial radio buttonand select thembed Serial Port fromthe drop-down menu, as seen in FigureE.1. • Click OK. If mbed Serial Port is not in the drop-down menu, the Windows Serial Driver may not be installed. Set up New-line format (to print out new line characters correctly) by following: • Setup / Terminal . • Under ‘New-line’, set Receive to ‘LF’. 369 370 Appendix E Figure E.1: Setting up the Tera Term connection To test Tera Term running with an mbed, create a new project of suitable name in the compiler, andenterthecodeof ProgramExampleE.1. Thiscodesimply greetstheworld, and then reads your keyboard input and displays it to Tera Term. To show that the character value is being seen by the mbed, the program adds one to the ASCII code, meaning that every letterisechoedbacktotheterminal astheletterfollowingitinthealphabet: binsteadof a, c instead of b, and so on. // Print to the PC, then pass back characters (slightly modified!) */ #include "mbed.h" Serial pc(USBTX, USBRX); // define transmitter and receiver int main() { pc.printf("Hello World!"); while(1) { pc.putc(pc.getc() + 1); //adds 1 to the ASCII code, and returns it } } Program Example E.1 Transferring keyboard characters to the screen A more advanced program using terminal access is given in Program Example E.2. This is taken from the mbed site, and uses a pulse width modulated signal to increase and decrease the brightness of a light-emitting diode (LED). The pulse width modulation (PWM) is controlled from the keyboard and displayed on the Tera Term screen. To test the program, connect an LED between pin 21 and ground, and enable Tera Term. /*Connects to the mbed with a Terminal program and uses the 'u' and 'd' keys to make LED1 brighter or dimmer */ #include "mbed.h" Serial pc(USBTX, USBRX); // define transmitter and receiver The Tera TermTerminal Emulator 371 PwmOut led(p21); float brightness=0.0; int main() { pc.printf("Press 'u' to turn LED1 brightness up, 'd' for down\n\r"); while(1) { char c = pc.getc(); wait(0.001); if((c == 'u') && (brightness < 0.1)) { brightness += 0.001; led = brightness; } if((c == 'd') && (brightness > 0.0)) { brightness -= 0.001; led = brightness; } pc.printf("%c %1.3f \n \r",c,brightness); } } Program Example E.2 Controlling PWM setting from the keyboard Index Note: Page numbers with “f” denote figures; “t” tables A Accelerometer data logging, on exceeding threshold, 214e215 threshold interrupt, 198e199, see also Interrupts Acorn computer, 12 Address bus, 8 Advanced RISC Machines Ltd, 11e15 ADXL345 accelerometer, 125, 126f pin connections to mbed, 121f program, developing, 125e128 registers, 126t Aliasing, 81e82, 81f American Standard Code for Information Interchange (ASCII), 104, 155, 156t Analog input, 77e93 combined with analog output LED brightness by PWM, controlling, 84 LED brightness by variable voltage, controlling, 82e83, 83f PWM frequency, controlling, 84e85 data conversiontime, estimating, 90e92 data on LCD, displaying, 162e163 interrupts from, 180e181, 180f with mbed, 82 mini project, 92 processing data from, 86e88 ADC outputs to recognized units, scaling, 87 averaging to reduce noise, applying, 87e88 displaying values on computer screen, 86 Analog output, 57e75 combined with analog input LED brightness by PWM, controlling, 84 LED brightness by variable voltage, controlling, 82e83, 83f PWM frequency, controlling, 84e85 on mbed, 59e65 API summary for, 59, 59t, 67t constant output voltages, creating, 60 DAC resolution, testing, 63e64 sawtooth waveforms, 60e62 sine wave, generating, 64e65 Analog sensors, 88e90 integrated circuit temperature sensor, 89e90, 90f light-dependent resistor, 88e89, 89f Analog-to-digital conversion, 77e82 quantization error, 79e80 range of, 79e80 resolution of, 79e81 sampling frequency, 81e82 Analog-to-digital converter (ADC), 77e79 control registers, 312e318 applications of, 314e316 conversion speed, changing, 316e318 mbed, 82, 305e308, 312, 313t LPC1768, 323 373 Apple, 12 Application programming interface (API), 25e26, 32e33 Arithmetic logic unit (ALU), 7e8 ARM ARM Holding, 12e13 Cortex core, 12e15, 14f, 178 history of, 12e13 mbed, see mbed RVDS (RealView Development Suite) compiler, 25 Arrays, 351 Assembler, 10 Asynchronous serial data communication, 140e144, 141f on mbed, 141e144, 142t, see also Serial data communication Audio projects, advanced, 323 Averaging to reduce noise, applying, 87e88 B Binary number system, 331, 332f Bistable circuit, 201e202 Bluetooth serial communication, 244e251 communication between two mbeds, 248e251 data from host terminal application, receiving, 247 defined, 244 RN-41 module, 244e245, 245f RN-42 module, 244e245 sending mbed data over, 245e247, see also Serial communication 374 Index Break statement, 349e351 Byte, 332 C C language, 9e10, 339e357 code blocks, 342 comments, 341e342 compiler directives, 342 #define, 342 #include, 342 data types, 343, 343t file access operations, 352e353 closing, 355 opening, 355, 356t reading file data, 356 standard library functions, 355t writing file data, 356 flow control, conditional branching, 348e349 break statement, 349 if and else, 348e349 switch statement, 349 flow control, program loops, 349e351 arrays, 351 derived data types, 351e353 exiting loops with break, 350e351 for loops, 350 infinite loops, 350 pointers, 351e352 strings, 351 structures, 352e353 unions, 352e353 while loops, 349e350 functions, 344e346, 344f definitions, 346 main function, 345 prototypes, 345 static storage class with, 346 #ifndef directive, 108 header files, 353 keywords, 339, 340t layout, 341 library functions, 205, 205t mbed development environment using, 26 mbed objects, global use of, 109 operators, 346e348 preprocessor, 107e108, 107f preprocessordirectives, 107e108 printf command, 354 program compilation, 106e107, 106f space, 341 standard libraries, 353 statements, 341 using multiple files in, 105e109 variables declaration, 339e343 initializing, 342e343 naming, 342e343 working with data, 343e344 C++language, 9e10 #ifndef directive, 108 library functions, 205, 205t mbed development environment using, 26 mbed objects, global use of, 109 preprocessor, 107e108, 107f preprocessor directives, 107e108 program compilation, 106e107, 106f using multiple files in, 105e109 Central processing unit (CPU), 7 Circular buffer, 236, 237f CISC, 13 Clear display command, 155, 155f Clock select registers, 308e309, 309t, 310t Closed loop control system, 274 cruise, 275e276, 277f digital compass, 280e287, 281f HMC6352 digital compass, 281e283, 281f, 282t implementation algorithm, 285e287 360 degree rotation servo, 283e285 See also Control systems Cloud computing, 262 Code blocks, 342 Color LCDs, 163, 164t, see also Liquid crystal displays Comments, 341e342 Compiler directives, 342 #define, 342 #include, 342 mbed, 25e26 Complex instruction set computer (CISC), 13 Constant output voltages, creating, 60 Context, 172e173 Controller area network (CAN), 288e289, 289f data read, 293 on mbed, 289e294 mbed-to-mbed communication hardware build for, 291f pin connections for, 292t Microchip transceiver IC, 290f Control register(s), 298e299, 299f analog-to-digital converter, 312e318 applications of, 314e316 conversion speed, changing, 316e318 mbed, 305e308, 312, 313t clock select registers, 308e309, 309t, 310t digital input, 303e305 digital output applications of, 301e302 second digital output, adding, 302e303 digital-to-analog converter, 308e309 mbed, 310 mbed digital input/output, 299e301, 300t pin mode registers, 307e308, 307t pin select registers, 305e307, 306t power control registers, 308e309, 308t Control systems, 273e295 advantages of, 274e275 closed loop, 274 cruise, 275e276, 277f Index 375 controller area network, 288e294, 289f, 290f, 291f, 292t electromechanical, 273 open loop, 274 proportional, 276e278, 278f, 279f proportional integral derivative, 278e280, 279f, 280f Cortex microprocessor core, 12e15, 14f, 178 Counter digital counter, 181e182, 182f as timer, 182e183 Cruise control system, 275e276, 277f, see also Control systems D Data acquisition system, 78f bus, 8 conversion, 57e58 derived data types, 351e353 memory, 7e8, 7f, 201, see also Memory types, 343, 343t working with, 343e344 Debounce, 196e198, 196f Decimal number system, 331e332, 331f Decoupling capacitor, 224 Delay/echo effect, 230f, 232f Derived data types, 351e353 Development cycle, of embedded systems, 10e11, 11f Digital compass closed loop control system, 280e287, 281f HMC6352 digital compass, 281e283, 281f, 282t implementation algorithm of, 285e287 360 degree rotation servo, 283e285, see also Control system; Closed loop control system Digital counter, 181e182, 182f, see also Counter Digital filtering, 220e222 Digital input, 29e55, 36f control registers, 303e305, see also Control register(s) DigitalIn API, 40, 40t switches to logic inputs, connecting, 39, 39f using if to respond to a switch input, 40e41 Digital output, 29e55, 36f control registers, see also Control register(s) applications of, 301e302 second digital output, adding, 302e303 using external pins, 37e39, 38f using LEDs, 36e37, 37f Digital signal processing (DSP), 219e242 defined, 219e220 delay/echo effect, 229e232 digital data, input/output of, 222e224, 226f high-pass filter, adding, 220e221, 229 low-pass filter, adding, 224e228 push-button activation, adding, 228e229 signal reconstruction, 224 stereo wave player, 240e241 basic, 240 with PC interface, 240 portable, with mobile phone display interface, 241 wave audio file, 232e239 information header, 233e234 with mbed, reading, 235e236 mono wave data, reading and outputting, 236e239 Digital spirit level, in LCDs, 166 Digital-to-analog converter (DAC), 58, 58f, 59f control registers, 308e309 applications of, 59e65, 311e312 mbed, 59e65, 310 resolution, testing, 63e64 TLV320AIC23b, 323 Disabling interrupts, 179e180, see also Interrupts Displaying values on computer screen, 86 Display mode control register, 154e155, 155f Duty cycle, 65 Dynamic random access memory (DRAM), 203, see also Random access memory E Electrically erasable programmable read only memory (EEPROM), 204, see also Read-only memory (ROM) Electrically programmable read only memory (EPROM), 204, see also Read-only memory (ROM) Electromechanical control systems, 273, see also Control systems Electronic memory, 202e204, see also Memory Embedded system, 4f defined, 3e5 development processes in, 9e11 development cycle, 10e11, 11f programming languages, 9e10 example, 5e6, 6f, see also mbed Ethernet, 255e261 communicationsbetweenmbeds, 257e261 data, Manchester encoding for, 256, 257f overview of, 255e256 Event-triggered tasks, 171, 171t responding to, 171e173 polling, 171e172, 172f See also Task Extension projects, 321e329 advanced audio projects, 323 Pololu robot, for mbed, 321e322, 322f External pins, digital output using, 37e39, 38f 376 Index F Field effect transistor (FET), 204 Field programmable gate array (FPGA), 15 File(s) access, 207e208, 352e353 closing, 355 opening, 355, 356t reading file data, 356 standard library functions, 355t string, 208e209 writing file data, 356 closing, 206 data formatted data, using, 209e210 reading, 206e207 writing, 206e207 opening, 206 Filter(s) cut-off frequency, 220e221 finite impulse response, 221e222, 221f high-pass, 220e221 infinite impulse response, 225, 226f low-pass, 220e221, 224e228 order of, 220e221 pass-band, 220e221 roll-off rate, 220e221 stop-band, 220e221 taps, 221 Finite impulse response (FIR) filter, 221e222, 221f, see also Filter(s) Flash memory, 204, see also Memory Floating point, 59 number representation, 9f, 336e337 Flowcharts, 97, 97f, 98f Flow control conditional branching, 348e349 break statement, 349 if and else, 348e349 switch statement, 349 program loops, 349e351 exiting loops with break, 350e351 infinite loops, 350 for loops, 350 while loops, 349e350 For loops, 350 Formatted data, 209e210 Framecheck sequence(FCS), 256 Frames, 256 Full duplex, 118 Functions(s), 96e97, 344e346, 344f call, 96f definitions, 346 liquid crystal displays, 157e158 main function, 345 on mbed, working with, 100e105 mode control register, 154, 154f prototypes, 345 reuse, 102e103 static storage class with functions, 346 H Half duplex, 129e130 Hardware, 4e5 #define directive, 342 #ifndef directive, 108 #include directive, 342 HD44780, 149 data transfer, 150f 4-bit interface, timing for, 150f instruction transfer, 150f user interface lines, 150f Header files, 353 Hexadecimal number system, 332e333, 332f High-level language (HLL), 10 High-pass filter (HPF), 220e221, 229, see also Filter(s) Hitachi HD44780, 149, 150f HMC6352 digital compass control system, 281e283, 281f pin connections for, 282t setup and read, 282e283 Hot electron injection (HEI), 204 HTTP client, mbed as, 262e264 HTTP file server, mbed as, 264e266 I IBM, 12 If and else, 348e349 Infinite impulse response (FIR) filter, 225, 226f, see also Filter(s) Infinite loops, 350 Instruction set, 8 Integrated circuit (IC), 3 Integrated circuit temperature sensor, 89e90, 90f Intelligent instrumentation, 125 Inter-integrated circuit (I2C) bus, 129e134, 129f data link, setting up, 131e134 data transfer, 130e131, 131f evaluation of, 140 on mbed, 131, 132t multi-node, 144 temperature sensor, communicating with, 135e138 Inter-integrated circuit sound (I2S) port, 323 Internet of Things, 323e325 Interrupts, 170e173, 175e181 accelerometer threshold, 198e199 from analog inputs, 180e181, 180f disabling, 179e180 latency, 176e179 on LPC1768 microcontroller, 178 masked, 176 on mbed, 173e175 nested, 176 pending, 176e177 prioritized, 176 timer, repetitive, 183 vector, 172e173 Interrupt service routine (ISR), 172e173 K Keywords, 339, 340t L Latency, 176e177 testing, 178e179 Index 377 Layout, 341 Library wait functions, 31t Light emitting diode (LED), 147e148 brightness by pulse width modulation, controlling, 84 brightness by variable voltage, controlling, 82e83, 83f digital output using, 36e37, 37f Light-dependent resistor (LDR), 88e89, 89f Lighttracking,two-dimensional,92 Linear pulse code modulation, 233 Liquid crystal displays (LCDs), 147e167 adding data to specified location, 158e159, 159f analog input data on, displaying, 162e163 character displays, 149 color, 163, 164t definition of, 156e157 display data to, sending, 155e156 functions, utilizing, 157e158 HD44780, 149, 150f initializing, 154e155 clear display, 155, 155f display mode, 154e155, 155f function mode, 154, 154f mbed TextLCD library, using, 160e161 modular coding to interface, 153e154 PC1602F LCD, 150e159, 151t, 152t SPI LCD mobile phone display, controlling, 163e166 Local area network (LAN), 256 Local file system, defining, 205e206 Low-pass filter (LPF), 220e221, 224e228, see also Filter(s) LPC11U24 mbed, 325, 326f LPC1768 microcontroller, 17e19, 18f, 21e22, 21f, 173e176, 298e299, 323 electrical characteristics of, 359e362 limiting values, 362t port pin interface characteristics, 354e356, 355t interrupts on, 178, see also Microcontroller(s) M Machine code, 8 Manchester encoding method, 256, 257f Masked interrupts, 176, see also Interrupts mbed, 17e27, 18f architecture of, 19e20, 20f as HTTP client, 262e264 as HTTP file server, 264e266 two mbeds on Bluetooth, communicating between, 248e251 Media access control (MAC) address, 244 Memory, 201e204 access with mbed, 205e207 external, 210e212 data, 7e8, 7f, 201 electronic, 202e204 flash, 204 function types of, 201e202 non-volatile, 7e8, 201e202 program, 7, 201e202 dynamic, 203 static, 203 read-only, 201e202 electrically erasable programmable, 204 electrically programmable, 204 programmable, 204 volatile, 7e8, 201e202 Microchips, 3 Microcontroller(s), 4, 8e9 features of, 9f LPC1768, 17e19, 18f, 21e22, 21f, 173e176, 298 electrical characteristics of, 359e362, 361t interrupts on, 178 Microelectromechanical system (MEMS), 125 Microprocessor(s), 3, 6e9 interrupt response, 172e173, 173f, 177e178, 177f Microwire, 117e118 Mono wave data, reading and outputting, 236e239 Motorola, 117e118 Motor with mbed, switching, 50e51 Multi-node I2C bus, 144, see also Inter-integratedcircuitbus Multi-tasking, 170 in metronome program, 194e195, see also Task N National Semiconductors, 117e118 Negative feedback, 276 Negative numbers, representation of, 334e336 Nested interrupts, 176, see also Interrupts Nested Vectored Interrupt Controller (NVIC), 178 Non-volatile memory, 7e8, 201e202, see also Memory Nordheim Fowler Tunneling, 204 Nyquist sampling criterion, 81e82, 90 O Offset binary, 334e335, 334t Open loop control system, 274, see also Control systems Operators, 346e347 Opto-sensors, 42e48 to mbed, connecting, 43e44, 44f reflective, 42e43, 43f transmissive, 42e43, 43f P PC1602F LCD, 150e159 to mbed, connecting, 152e153 378 Index PC1602F LCD (Continued) physical pin layout, 153f pin descriptions, 151t, 152t Philips I2C bus, 129e134 Piconet system, 244 Piezo transducer, outputting to, 72e74 Pin mode registers, 307e308, 307t Pin select registers, 305e307, 306t Plant, 278 Pointers, 212e214, 351e352 Polling, 171e172, 172f Pololurobot, for mbed, 321e322, 322f Powercontrol registers, 308e309, 308t Printf command, 354 Prioritized interrupts, 176, see also Interrupts Product development cycle, 327f Program design benefits of, 95 defining code structure, using flowcharts, 97, 97f, 98f modular program example, 109e112 pseudocode, 99 using multiple files in C/C++, 105e109 Program memory, 7, 201e202, see also Memory Program structure, benefits of, 95 Programmable read only memory (PROM), 204, see also Read-only memory Programming languages, 9e10, see C language, see also C++language Proportional control system, 276e278, 278f stepresponse of, 276e278, 279f, see also Control systems Proportional integral derivative (PID) control system, 278e280, 279f, 280f, see also Control systems Pseudocode, 99, 99f Pulse width modulation (PWM), 65e66 averaging circuits, 66f controlling LED brightness by, 84 frequency, controlling, 84e85 on mbed, 66e74 outputting to piezo transducer, 72e74 servo control, 71e72 small motor, speed control of, 68 in software, generating, 70e71 sources, 66e67 trial outputs, 67e68 waveform, 65f Push-button activation, adding, 228e229 Q Quantization error, 79e80 Quick response (QR) codes, 324, 324f R Random access memory (RAM), 7e8, 201e202 dynamic, 203 static, 203, see also Memory Rapid prototyping, 326e327 Read-only memory (ROM), 7e8, 201e202 electrically erasable programmable, 204 electrically programmable, 204 programmable, 204, see also Memory Real Time Clock (RTC), 195 RedLaser, 324 Reduced instruction set computer (RISC), 13e14 Remote JavaScript interface, controlling mbed using, 267e270 Remote procedure calls (RPCs) to modify mbed outputs, 266e267 Repetitive interrupt timer, 183, see also Timer(s) RISC, 13e14 RN-41 module, 244e246, 245f, 246f, 248 RN-42 module, 244e245 S Sampling frequency, 81e82 Sawtooth waveforms, 60e62 Segway personal transporter, 275f Self-contained metronome, 198 Serial communication, 115e145, 243e271 asynchronous, 140e144, 141f on mbed, 141e144, 142t Bluetooth, 244e251 data from host terminal application, receiving, 247 defined, 244 RN-41 module, 244e245, 245f RN-42 module, 244e245 sending mbed data over, 245e247 two mbeds, communicating between, 248e251 Ethernet, 255e261 communications between mbeds, 257e261 data, Manchesterencodingfor, 256, 257f overview of, 255e256 protocols, advanced, 243e244 synchronous, 115e117 with host computer, 144 universal serial bus, 251e254 MIDI data from mbed, 253e254 mouse, mbed usage for emulating, 252 Serial peripheral interface (SPI), 117e124, 210e211 ADXL345 accelerometer, 125, 126f pin connections to mbed, 121f program, developing, 125e128 registers, 126t data link, creating, 121e124