123 pic microcontroller experiments for the evil genius

348

Upload: reivach

Post on 23-Nov-2015

1.483 views

Category:

Documents


426 download

TRANSCRIPT

  • ISBN D 0? 1q51,'ra-0

    llilXIJltlllllllllllilll ttnnnli

  • E3 PIf@M itrrtrcontrollerExperiments fsrthe Evi | Eenius

  • Evil 6eniu5 series

    123 Robotics Experiments for the Evil Genius

    Electrcnic Gad|ets fot the Evit Genius:28 Build'it'yourself Prciec!

    Electonic Ci/cuits for the Eril GeniL.s:57 Lesso^, with Prciects

    123 PI(P Microcotltollel Eryeriments fol the Eril Geniut

    Mechatonics fol the Et il Genius: 25 Build-it'youtself Prcject'

    50 Awesome Automoli'e Prcjects for the EviI Genius

    Sotat Energ! Proiects for the Evil Genius: 16 Buikl'it'yoarselfThemoelectic andMechdnical Prcjects

    Bionics fol the Evit GeniLLs: 25 Build'it'Yourself Prcjec1

    MORE Etectronic Gadgets for the Evil Genius:28 MORE Build'it'yourself Proiects

  • the Evi | 6eniusMYKE PREDKO

    Experiments for

    1A3 PIE@Mitrrotrontroller

    McCraly-HillNew York Chicago San Francisco Lisbon

    London Madid Mexico Cily Milan New DcthiSan Juan Seoul Singapore SydDey Toronlo

  • Catiloging-in-Publicttion Data is oD lilc with the Library of Congfcs!

    copyright O 2005 by The McC raw-H ill Commpinicq Inc. All rights fcscrved Prinled in thcUnired Stoles orAnerica. Excepl as permitted undcr the Uniled Stalcs CoPvright Act of 1976'topnn of this publication may be reproduced or dislributed in nny forn or by any mcan$,ot sloredin a dala base or rotricval syftD.vilhout the prif writLen pcrnhskn ol rhe publishcr'

    3 4 5 6 7 8 9 0 Q P D / Q P D 0 I 0 9 l J 7

    ISBN 0-07145142-0

    The sponhtug edint lot thi\ hook tras Jkd!) Bisr Ml the ?roduction tttll!tui$reas PMtle A. Pelton. ft wat Net ibTinw Tat by l kAllistet Pttblishi S Service!, LLC Thc Irt dituctor Jolth! &v0 ,,a! Ahthory kndi.Ptink anl hantl bt Qu.h.cot/Dubuque.

    {}Jlllbk::\,ti,''*t"nrocvored'ocid'riccraPcrconl0ini'saminiDUDor50PcrccntrccvcredMccraw-Hill kloks arc dvailable at special quanlily discounts to use as prmirims and sales ptomo-tions, or tor use in corponlc Lr.ining pro$ am$ For Inore information, please wrile to tho DirectofofSpccialSales"McGraw-H I'|ofessional,Two Pcm PlaTa.New York,NY l0l2l-2298. O' contacr

    lnformatio! conlained in this woik has beetr obtained by The Mccraw-Hill Conpa_nicr lno. ("Mccraw-nill") lron sources bclieled to be reliablo However, neithcrMocraw-Hill nor ih authore Suarantee rhc accuracy or comPlebness of any informd-tion published hcrcir. and neither Mccraw-Hill nor its authos shall be responsible lbrdnr eros, onn$iorn or danages arising oul oi use of this infomation. Tbis work hDublished with thc underst.nding ural Mccraw Hill and its authos are suPplvinginformation but are not attempnng b render profe$ional senices Ii such serrices arerequired. tho alsislane of an aPProPnate prolesional shoLrld be soughl.

  • ft

    ff{b.{.q.f,

    LOnIenrSwn w)E w" w w. wt gF t F&as i['tq ffii ffi asSt J6r!6 iqost

    Introduction

    Section One

    EXPERIMBNT 1

    EXPERIMENT 2

    EXPERTMENT 3

    Acknowledgments

    About the Author

    EX?ERMENT 14

    EXPERTMENT 15

    EXPERIMENT 16

    Section Three

    EXPERTMENT 17

    EXPERTMENT 1 8

    EXPERIMENT 19

    The Switch DecisionStatement 43

    Conditional Looping 45

    The For Statement 46

    Simple PIC@ MCUApplications 51

    Basic Delays 53

    Sequencing PTCkit 1Starter Kit LEDS 55

    Binary Number OutputUsing PICkit 1 StarterKit LEDS 56

    Basic Button Inputs 58

    Debouncing Button Inputs 59

    MCLR Operatiorl 6I

    Ending Applications 63

    C Language Features 67Functions and Subroutines 69Global and Local Variables 70

    Defi[es and Macros 7IVadableAuays 73

    Structures and Unions 75

    Pointers and Lists '76

    Character Strings 79

    Library Functions 81

    ix

    x

    t

    t3L 4

    EXPERIMENT 4

    Section Tko

    EXPERIMENT 5

    EX?ERIMENT 6

    EXPERTMENT 7

    EXPERIMENT 8

    EXPERIMENT 9

    EXIERTMENT 10

    EXPERTMENT 11

    EX?ERTMENT 12

    EX?ERTMENT 13

    Under the Covers ofthe PIC16F684I/O PinsConfiguration word

    PIC MCU VariableMemory, Registers, andProgram Memory

    Simulating cFlash.c inMPLAB IDE

    Introductory CProgrammingVariable DeclaralionStatements

    C DataTypes

    Constant Formatting

    Assignment Statements

    Expressions

    lJrtwrse uperators

    Logical Expressions

    Conditional ExecutionUsing the If Statement

    Nested ConditionalStatements

    EXPERIMENT 20

    EXPBRTMEN'r 21

    EXPBRIMENT 22

    EXPBRIMENT 23

    Section FourEXPERIMENT 24

    EXPERTMENT 25

    EXPERIMENT 26

    EXPERIMENT 27

    EXPERIMENT 28

    EXPERTMEN.T 29

    EXPERTMENT 30

    EXPERIMENT 31

    18

    20

    27

    28

    29

    31

    33

    35

    39

    4I

  • Section Flve PIC16F684 Microcontroller Section SevenBuilt-in Functions 89

    ExPERrrtNT32 Brownout Reset 91

    EXTERIMENT'33 ADC Opcratiotl 93

    EXpERINIENT 34 Comparatol Operation 96

    UsingTMRo 101

    Usiig theTMRo Prescaler 102

    EXPERTMENT 50

    EXPERTMENT 51

    ExPERltvtENT 52

    EXPERIMENT 53

    EXPDRIMENT 54

    EXlrinrMENT 55

    Sample CMicrocontrollerApplications

    Pumpkin LED Display

    Rcaction-Time Tester

    Rokenbok@ Monorail/Tiaffic Lights

    Seven-Segment LEDThelmometer

    PIC MCU "Piano"

    Model Railway SwitchColltrol

    Exr,r ,RrNrENr' 37

    Exl, t r t IMENr'38

    ExPERTMEN f 39

    LlxPEnt\ ' l r - tN r '40

    137

    138

    140

    143EXPER|"I|NT35 Watchdog'l'imer

    ExpERlNlFrNr 36 Short Timer Delays

    99

    t 1 4

    t46

    151

    LongTlnler DelaysUsing l 'MRt

    Comparing ClockOscillators

    Pin RcsislarceMcasulcmcnts

    104

    106

    l f J

    ExPERIMENT 56 PC Operating StatusDisplay 156

    t09

    l t lF\11 RrN,rE\ | 41 Cunerirung PwM Signir lJ

    Exl,r-rRrN4BN I 42 Stol ing and RctrievingData

    Section Six Interl'acing Projects for thePIC@Microcontroller ll'7

    ExpLRIMEN] 43 Driving a Scvcn_SegmcntI-ED DisPlaY DirectlYhom thc PICl6F6U4

    L \ " r R r \ I N " 4 | M u l t i l ' l c S c v q n - S c g m c t r tLED Displays

    ExPERTMENT 45 LED Matrix DisPlaYS

    EXPERTMENT ,16 LCD Display

    ExpFtRrNrENl ,lT ProduciDg RandomNumbers

    ExpERrvrENr ,l8 Two-Bit LCD Display

    EXPERI4nNT 49 Switch MatrixKeYPad MaPPing

    l l 9

    121

    124

    126

    128

    129

    t 3 1

    .

    Section Eisht Introduction to PIC@

    ExIERIMENT 57

    ExPERIMENT 58

    EXPERTMENT 59

    ExPERtMENT' 60

    EXI,ERIMENT 6l

    EXPLRTMENT 62

    EXPERIMENT 63

    EXPERIMEh*T 64

    EXPERTMENT 65

    EXPERTMENT'66

    MCU AssemblyLanguageProgramming 159

    Thc asmTemplate.asmFilc ard Basic Directivcs 160

    Specifying ProgramMemory Addresses 161

    Loading the WREG andSaving Its Coitents 164

    Detining Variables 165

    B i t w i s e l n s t r u c t i o n s ' i 6 ' 7

    Additionlnstruclions 168

    AddLibs: StrangeSimulator Results 170

    Sublractionlnstructions ']71

    Bank Addressing 173

    Bit lnstructions 1'75

    C o n t e n t s

  • EXPERTMENT 67

    EXPERIMEh-r 68

    EXfERTMENT 69

    EXPERTMENT 70

    EXPERTMENT 7l

    Section Nine

    Bit Skip Instructions

    Conditional Execution

    declsz Looping

    Subroutines

    Defining andImplementingArrays I82

    PIC@ MicrocontrollerAssembly LanguageResource Routines '187

    Logic Simulation Using188

    Statcmont 191,

    Dcfines 194

    ConditionalAssembly 197

    Macros 199

    l6-BitValues/Variables 201

    Universal Delay Macro 203

    High-lavcl Pro$amming 205lmplementing Read-OnlyAIrays

    Data Stacks

    Circular Buffers

    Reading andw ting theEEPROM Data Memory

    EXPERTMENT86 PIC MCU InstrumentInterface

    EXPERTMENT8T SoundDetection

    EXPERTMENT 88 Multiple MiqoswitchDebouncing

    Light Sensors

    r7'7

    178

    180

    181

    231

    235

    23'7

    238

    f"\{",t,:ii',1'*J?:!:"{a'iil

    EXPERTMENT 89

    EXPERIMENT 90

    EXPERIMENT 72

    EXPER]MENT 73

    ExPEnIMENT 74

    ExPEnTNIENT 75

    ExPERti \4ENr 76

    EXPERIMEN].77

    ExPEnTMENT 78

    EXPERIMENT 79

    EXPERIMENT 80

    EXPERIMENT 8l

    EXPERTMENT 82

    EXPERTMENT 83

    EXPERTMENT 85 PIC MCU BS2 KeypadInterface 230

    Infiared (IR) SurfaceSensor 239

    ExpERlMENr9l Intcrfacing 10 SharycP2D120 RangirgObject Sensors 242

    ExPERTMENT 92 Do-lt-Yourself IRObject Sensor 243

    ExPERTMENT' 93 lR Object-RangingSensor 24'7

    ExpERTMENT 94 Ultrasonic Distanco-Range Sensor 249

    ExPERrMENr95 Robor IRTag 251

    Section Dleven Motor Control 255EXPERIMENT 96 DCMotor Driven Usi g

    the CCP PWM and Usinga Potentiometer Control 257

    ExPfRrvF \ r 1 ,7 DC Moto r Con t ro l x i l tSimple TMR0 PWM 261

    ExpERIMENT98 ControllingMultipleMotors with PWM aDdBs2lntcdace 264

    EXPERIMENT 99 Bipolar Stepper MotorControl 265

    EXpERIMENT 100 Unipolar Stepper MotorControl 269

    EXPERIMENT 101 Radio-Control Model ScrvoControl 272

    EXPERTMENT 102 Multiple Servo ControlSoftware Structure 2'74

    the PlC16F684

    The C "Switch"

    208

    210

    212

    SectionTen Sensors

    ExPERrMENr34 PIC MCU BS2 Userlnterfacc

    214

    227

    224

    C o n t e n t s

  • EXPERTMENT 103 Two-Servo Robot Basewith Bs2lnterface 27'7

    Section Twelve Solving ProgrammingProblems in PIC@MicrocontrollerAssembly Language 279

    E\p r R rMr \ r 104 L igh l -B i t Mu l t i p l i ca t i t r nwith a 16-Bit Product 280

    ExpERrMENl 105 Division of a 16-Bitvalueby an Eight-Bil Valuc 282

    Exr,r 'RrMr'\ | lu6 Squrring a Number UsingFinite Difference Theory 284

    EXPERTMENT 107 Find lhe Square Rool of a16-Bit Number 28(t

    EXPERIMENT 108 Converling a Byte intoThree Decimal,T\'r'o Hex,or Eight Binary ASCIIBytes 289

    EXPERTMBNT 109 Producc the Even ParityValues for a Byte 291

    EXPERTMENT 1 I0 Sort a List of 10 Eight-BitValues Using the Bubble-SortAlgo tllrn 292

    EXpERIMENT 111 Encrypt and Decryptul l ASCIIZ Slr ing Usinga Simple SubstitutionAlgolithm 294

    ExpERr \4 r \ r l l 2 Ccnera te c F ihonacc i

    Number Sequence 29'7

    EXPERTMENT 113 Find the Largest CommonFactor ofTwo Eight-BitNumbers 298

    Section Thirteen

    EXPERIMEN T 114

    EXPERTMENT'115

    EXPERTMENT 116

    EXPERIMF,NT I 17

    EXPERIMENT I18

    EXPERTMENT 119

    EXl ERTMENT 120

    ExPERTMENT 121

    EXPERTMENT' 122

    ExPERTMENT 123

    Index

    ZipZaps@ Robot 301

    Characte zing theZipzaps

    PIC MCU Power Supply

    PIC MCU ElectronicsPCB

    IRTV Remote Control

    Molor and SteeringControl

    Basic Thsk-ControlSoftware

    lR Remote Contlol

    Lighl Sensors andFollowirlg

    303

    305

    307

    310

    3 1 1

    316

    IR ObjectDetectionSensors 318

    IR Linc-FollowirlgSensors 320

    327

    ii$i--;!'1#4_.1*

    i)t-:

    v t i . r C o n t e n t s

  • FcknouJledgments! t j . . : . i ' t ! . ; : t l t ! ! ) . : t t ; . : : ! : ! r i r : i , : : ? r r a , - \ r i

    F"{'}'trl'tijql.-ir(*Nl"{trs{n;:.!f*{,n

    This book would not have been possible without t1lehelp, suggestions, and time from the fbllowing individuals:

    . CarolPopovich, Greg ADderson, JocDrzewiecki,Andre Nemat, and Fanic Duven-hage ol I \4i(rochrn $ho ha\e helped nreunderstand which products would be beslsuited for this book,and have been williDg to.pcnd r ime with me lo undersrand my rcquirc-m9nts, answer my legions of questions, andsuggest avenues to follow that hadn't occurred

    HT-Soft and lhcir technical support stall fbranswering D'ry qucstions quickly and holpingto cxplail the iDner workings ofthe PICCLirc comti ler.The PICC .l inc of compilers isa lrcmcndous tool for the bcginnct and pro-lc:) iunrl r l ikc, and one T ncvcr hcsitatc lo re.-onmlcDCl.Brad North, Richard Bonafede, and lhe s!u-dents ot Rick Hansen Sccondary School ilrMissassauga, Onf.lrio,lbr helping me to learnmore about how studenls (and teachers) learnabout pr ogramming, electronics, and thc PICMCUBlair Clarkson aDd Dnvc Pilole at the OltarioSciencc Centre inToronlo,I'or pushing me toexplair basic microcontroller concepts to peo-ple that luve built the TAB Electronics Sumo"Bot at a workshop and want to do norc withir. lhe BS2 i rt ' r facc and Robot IR Tig cxpcr-iments are a direcl result ofthis work.

    My edilor at Mccraw-Hill, Judy Bass,whoconsistently responds to my questions andsuggestions, regardless of how dunb they are,with good humor and thougltfulness.

    lhc PIC MCU cont inucs lo bc one ol lhd be(l.uppo cd dc! ice. on l i r )e.3nd I ! \ould l ike lothalk the many individuals who have takenthe time lo put information and projects onrhe lnlefncl a\ \ rc l l as supporl and hclp ntheNtrying to better undclstand the PIC MCU orget their applicalions up and ruDning.

    . Celeslica and its employccs fbr ideas, answcrsto straDge questions, and opPortunities toexpand my lcchnical horizons,

    . My daughter Marya,who has grown up with afather lhat is always trying out ncw projeclson hcr. Shc trics them out wilh cnlhusiasmdespite thc lhcl they genorolly need a bit oftuning belorc they work perlcctly.

    . My wilc Patience, for kecping everythingtogethcr, cvcn when our youngcst daughlerTalitha was sick, and for having dinner on theslove, evcn wilh me asking hc! 10 do a"quickread" of a section or two.I couldn't do any ofit withoul you.

    To all ofyou, thank you for all you unselfishhelPand willingness 1() shareyour ideas, expcdences, andenlhusiasm for lhis book.

    mgkehttp J/rilirur. mske. Eom

    A c k n o u l e d g m e n t s i x

  • ,')'$.iifi : ::i,ilfi !i!i:.1.-iti::i1i ii'ii#iirt ill,i:i$[ii] {g{S"*;Fbout the Futhor

    i{w w ffi M ffi EGH @ W{ $SSg Sr$ss ffi ffi KS&&{ ffi

    Myke hedko is Test Architect at Celestica, in Torontq Canada, a suppliel of printed circuit boards to the com-puter industry. Aln expedenced author, Myke wrote Mccraw'Hill's best-selling 123 Robotitr Prcjects for the EvilGenius; PICmicrc Mictocontoller Pocket Refercnce; Progamming and Customizing PICMirrc Microconlrolkrs,Second Edition;P/oSramming Robot Contollers; and other books, and is the principal designer of both TABEElecironics BuiM your Ov,n Ro b ot kits,

    h

    .tJ5

    {)

    +-,

    ,.t

    A b o u t t h e A u t h o r

  • Introduction

    When I wrote my first book on the Microchip PICPmicrocontroller (commonly abbreviated to "MCU")almost 10 years ago, the most common criticism Ireceived about the book was that it took too long toget to the projects. This is quite foreign to me because Itend to leam a new device, like a microconftoller, byfirst reviewing the datasheets for the part's electricalinformation, working at understanding the architec-ture and how it is programmed, and ending withunderstanding what kind of development tools areavailable for the part. Looking over this list of tasks, itis quite obvious that they came about with my back-ground and training. Being a teenager in the 1970s andgoing to university in the early 1980q there wasn't thevariety of easy-to-work-with devices that are availabletoday, and the sophisticated personal computer-baseddevelopment tools that we take for granted were noteven being considered, let alone being developed orsold. My method for learning about a new part is effec-tive for me and a result of the situation I found rnyselfin when I first started working with electronics Todayyou can set up a development "lab" and create a basicapplication from scratch for the PIC MCU in less than20 minutes using Microchip's MPLAB@ integrateddevelopment mvironmmt (IDE) andPlckitrM 1starter kit with HT:.soft's PICC LiterM c compiler.

    The purpose of this book is to introduce you to theMicrochip PIC MCU and help you understand howto create your own applications. In this introduction,using the PICkit 1 sl2irter kit printed circuit board.(PCB) and free development tools from Microchipand HT-Soft,I will show you how easy it is to create asimple PIC MCU program that will flash one of thelight-emitting diodas (LEDs) on the PICkit 1 starterkit. As you work through the book, your understand-ing of the PIC device will increase to the point whereyou should be comfortable creating your own com-plex applications in both the C programming lan-guage as well as assembly language.

    The PICkit 1 starter kit (see Figure i-1) containseverything you will need to leam how to create andtest your own PIC MCU applications. This includes aprogrammer PCB (see Figure i-2), a universal serialbas (USB) cable to connect the PICkit 1 starter kit toyour PC, a CD-ROM containing the source code forthe applications presented in this book, two PICMCUs, an eight-pin PIC12F675, and a 14-pinPIC16F684. In this book,I will be focusing on thePIC16F684 because its 14 pins allow a greater varietyof different applications to be built from it, but you willalso gain experience with the eight-pin PIC12F675.

    On the back cover of the book is a web link that youcan use to order a PICkit 1 starter kit for use with thisbook. If you do not buy a PICkit 1 starter kit, thesource code can be dolrinloaded from my web site(www.myke.com).

    In this book, I will be working exclusively withMicrosoft Windows. I recorrmend that you use the lat-est version available (at this witing it is Windows,XPSP2) when working with the PICC Lite compiler andMPLAB IDE tools used in the book. Developmenttools are available for Linux, although not for AppleMacintosh OS/X (but you should be able to get theWindows software to work from an emulator). Youwill find that the software works well underWindows.

    If you look at the CD-ROMS that come with thePICkit 1 starter kit, you will find they have theMicrochip MPLAB IDE and HT:Soft PICC Lite com-piler development tools that are used in the book.Although you could load these programs onto yourPC,I recommend that you download the latest ver-sions from the Microchip and HT-Soft web sites.Thesetools are continuously updated (during the period thatthis book was written, MPLAB IDE had five upgrades,two of them major and changed how some of the oper-ations are performed) to include new features and PICMCU part numbers, and to fix any outstanding prob-lems. In this book. I used MPLAB IDE version 7.01

    Figure il The Microchip PICkit I stsrter kitenables you to create your own PIC MCUapplications and to test them out easily qndinexp ensively.

  • o . , o . i . n , ; : " 3 o . . & q < r . r . , . . . d G 9

    EmbeddedSv$emst 0nlelence san Franc "o.,"-..,,P, I:S:,"f,'i.'::.i'i.Yrf"!.'*...,"-..,

    Figure i-? The PICkit I starter kit's PCB consisx ofprogrammer circuits along with eight LEDI, a switch,and a potentiometer that enable you to easily learnhow to program and access the peripheral feqtures ofthe PIC MCU.

    and PICC Lite compiler version 8.05. With the versionsthat you use, you may see some differences in look oroperation, but the features presented in this book willall be present. If you are confused as to how to per-form some operation, you can consult the T[torialsection of MPLAB IDE, which can be found under theHelp pull-down.

    To start setting up the software needed to startdeveloping your own PIC MCU applications, go towww.htsoft.com, as shown in Figure i-3. PICC Lite is afree, full-featured C compiler that supports quite a fewof the different PIC MCU part numbers (including thePIC12F675 and PIC16F684 included in the PICkit 1starter kit package). Next click "Downloads" and thenselect "PICC Lite (Windows)" (see Figure i-4). Todownload PICC Lite compiler, you will have to regis-ter with HT-Soft at no charge (see Figure i-5).To dothis, follow the instructions on the page shown inFigure i-4. It should go without saying that the pagewill probably not look exactly like the figures here, dueto the delay between when I have written this andwhen you actually access the web site.

    The retail PICC compiler is capable of buildingcode for literally all the PIC MCU part numbers anddoes not have any of the restrictions of the PICC Litecompiler.

    After registering, the PICC Lite compiler installa-tion software should start downloading automatically.Depending on your secudty settings (especially if youuse Microsoft Windows/XP Service Pack 2 or later),the download may be blocked (as in Figure i-6). If thisis the case, you may have to tum off the security toallow the download to take place. Once the programhas downloaded, I recommend selecting "Run" insteadof"Save" (see Figure i-7).This will install the PICC

    Figure i-3 Step I - Go to www.htsoft.com

    I l ; , - . I d " e : . ; , . d & a t ' r !

    Figure Step 2 - PICC Lire Compiler downloa,li -q

    94- .J ! l I i ; i / , i4 . . - " r r . , a . t j .o I

    ltfi il,f; :i#;il ;i':ii:f .ri::,:.i l":ll

    Fiqure i-5 Step 3 - Registering a an HT-Softcustomer

    q. . ^ : i , i ; l :

    d!!:@

    1 , 2 3 P I C @ l ' l C [ J E x o e r i m e n t s f o r t h e E v i l 6 e n i u s

  • lib Edt r/i4 FMt6 Iode rgp

    Oo* - .,.y' sl td $ j)s..,a $r"-* 3- + n :, ffl im I

    I oownuas > oomos r,G@Download P.oducl Demos and Fra SoftwareRegistratron is requrred to dowrload.lf)u ha\ notalready registered you willbe redlrected t0 a page attowingyou to register,free 0f charge, or tog n Ityou have prevjou9ty registefed.

    @l;;--__lI H r r E r H P ' ( ( 1 8 || @f rp r r ru .d i It " " " " " " . , - lr@n,i, ";,"";,";".,""

    @f - - - , 1I sere.1 w it . 1

    . l

    D6mos

    The demo progms below a inbndd l0r prosperllvecustome6 ofNI.TECH Sotware lo evaluate our produltbefore naking a prxchase decision.Tlte demostpicallyhaw 53me deliberale limilalions com!rJed t0lhe full,purchased prcdurt, and also ha! an xpiry, usualt2l

    These d.mos are provrded enlirely dlhoul any wamnly.and arelorevalualion pueosss onv, and are notlicensed

    8051

    HitachiHS/300 f68HC05l68H411H- I0E fo i P CC 18MEP43|]

    z 8 0 l

    Faee Software

    H|T:CH Sdlwar maks cenarn lelsions of ils sonwaEpfoducls avadable asrree sonwdre Thseproducls areireef0rr.ykind oluse, inrludinq educalrol]al rnd commercirl!se, bulremain lhe propeE of!1lIc!1 sonwa 313l timesAllcopy qhl and olhernghls are resered and nowa*artot

    Thenee sottvi?fe downloads do no! ha! a built,tn xpiry

    Prcc,L|TE (Lrnua

    I C0nlactsilee t0 orqanize a lime llmiled eyalualion ollhis

    Figure i-6 Step 4 - Allowing PICC Lite Compiler file download inWindows/XP SP2

    Lite compiler without leaving you with an .exe or .zipfile to delete later.

    When the PICC Lite compiler installation screenappears (see Figure i-8), click "Next" and follow thedefaults. If you are prompted to load the software/drivers for MPLAB IDE, do so, as they will berequired to use PICC Lite compiler with theMicrochip tools and provide you with a truly inte-grated development environment, or IDE. TheMPLAB IDE is a single program containing an editor,assembler, linker, simulator, and PICkit 1 starter kit'sprogrammer interface, and it will be the only programyou have to run to create PIC MCU applications.PICC Lite compiler will integrate with MPLAB IDEwhen the latter is installed so you will have a singleWindows program for developing C and assembly lan-guage programs for the PIC MCU.

    After PICC Lite compiler is installed, you will beasked if you want to restart your computer. Click"No," then power down your computer, and powerback up. I find that soft resets (ones in which power is

    I . a O ) , * i r * o i . i ; ! r . { .G : . .

    Figure i-7 Step 5 - PICC Lite downloading

    not removed) may not reset all the PC's parameters,and the software installed on boot may not work prop-erly. Powering down and then back up eliminates thesepotential problems.

    @t;,;i l

    e-d

    ql " ; "

    lntroduction

  • . d . . 1 1 G . .

    Figure i-8 Step 6 - PICC Lite Installer

    With the PC back up, go to Microchip's web site(www.microchip.com shown in Figure i-9) andclick "MPLAB IDE" or "Development Tools," fol-lowed by "Full Install" (see Figure i-10).The MPLABIDE software is quite large (30 MB) and will takesome time to download if you use a dial-up connec-tion. This time click "Save" instead of "Run" and storethe .zip file into a temporary folder on your PC(see Figure i-11). You should be able to unzip thefile by double-clicking on it, and the file managementsoftware on your PC will expand the file into the direc-tory of your choosing (ideally the same one youstarted with).

    After the MPLAB IDE install files are unzipped,double-click on "Setup" and follow the instructions toinsrall the MPLAB IDE (see Figure i-12). If asked,make sure the programming interface for the PICkit 1starter kit is included and you will not have to look at

    , , . ! r . / , G n , . a ' , . d a i : l

    Fiqure ilO Step 8 - MPLAB IDE Download Pageon www,microchip.com

    Figure i-ll Step 9 - MPLAB IDE Install files storedin a temporary folder

    any readme files (unless you want to). If you areprompted to reboot your computer, click "No" andthen power down and power back up, as you did afterinstalling the PICC Lite compiler software. Do notconnect the PICkit 1 starter kit to your PC using theUSB cable until you are told.

    That's it;you've just installed a set of integrateddevelopment tools that are just as powerful as somesoftware development products that cost many thou-sands of dollars.With the tools installed, you can copythe source code files for the application code used inthis book from the PICkit 1 starter kit's CD-ROMcode folder into a similar "code" or "Evil Genius"folder under the C drive of your PC.Another sourcefor these files can be found on my web site atwww.myke.com.

    {rnc*rr

    EE-

    WWffir E - E :

    " ' Elir

    Figure i-9 Step 7 - Set yotry browser towww.microchip.com to download the MPLAB IDEas well as PIC MCU Datasheets

    d- ..) . ' ,a i . * :t '6G I t-t- i

    r t ; ^ . t

    ; . J t / * . . * , E l l - - 4 - j 9 -

    8.. . SiAl'l.,....'

    l , P 3 P I C @ l ' l C U E x o e r i m e n t s f o r t h e E v i l 6 e n i u s

  • r{qf*i:i.{

    $-i*

    kr.r'1.-i

    Figure i-12 Step 10 - MPLAB IDE Installerwindow

    Now let's try to create a simple program that flashesan LED on the PICkit 1 starter kit. To do this, double-click on the MPLAB IDE icon that has been placed onyour PC's desktop.When it first boots up, the MPLABIDE desktop looks like Figure i-13, and is ready foryou to start entering your own application. Click"New" and enter the following code into the windowthat comes up:

    #incluale -CONEIG(FCITDIS & IESODIS & BORDIS & IINPROIECT

    !4CIJRDIS & P!\IRTEN & WMDIS & INTIO) 'in t i tnain( )t

    PORTA = 0;CUCONo = ?tANSE J = 0iTRISA{ = 0iTRISAs = 0twhi le (1 == 1){

    25000 r i ++ ) i

    Different parts of this program will be displayedusing different colors; don't worry if it looks a bitstrange.The program should be saved as "c:\EvilGenius\Flash\Flash.c" (see Figure i-14). Once the pro-gram is saved, close the window that contains it.

    All programs should be run as part of an MPLABIDE project that saves options and features selectionsspecific to the application without requiring you toreload them each time you start up MPLAB IDE.Thefirst step is to specify the project name and where it isgoing to be stored (see Figure i-15).

    Fisure i-13 Step 11 - MPLAB IDE Start Updesktop

    Figure iJq Step 12 - First Applicqtion entered intoMPLAB IDE Editor wind.ow and savetl

    Figure i-I5prolect

    f o r ( i = 0 r i ,

    RA{ = 0t

    t o r ( i = O tO t

    RAA = li // D0 LED On AEain

    for ( if o r ( j

    TRISA4

    = 0i i < 255, i11) / / s inDle Delay r .oop= o i i < L 2 9 , i t L ) ,= 7i // EltlE RA4 irto rnput !{oale

    // LED lrrrned Offout

    f o r ( i = 0 r i ;

    .x!"j*:r1 .

    Xi . ' i

    In the introduction,I outlined sorne of the differencesbetween a microcontroller (such as the PIC rnicrocon-troller) and a PC, and I noted that one of the big dif-ferences in the application code was the need forproviding code to initialize variables. Another differ-ence is how the application code loaded into a PC or aPIC microcontroller and how it is organized.In thisexperiment,I will explain these differences (and theneed for them) and help you understand how informa-tion is organized in the PIC MCU and some of theissues that you must be aware of when you are pro-gramming the PIC16F684.

    When computer architectures are presented for thefimt time, something like Figure 1-4 is shown, which isthe standard Prlnceton or von Neumann architecture,The important feature of this architecture is that thememory space is a single address area for the programmemory, variable memory, and stqck memortes;theaddresses for these application features are presentedas being arbitrary and could be placed annvhere inthis address space. An interesting side effect of thiscomputer architecture is that an errant program couldescape from the program memory area, start executrngthrough the variable memory stack RAM, registerareas, and treat the data as program statements.

    When a program is built for loading into a targetPrinceton computer system, the file that is loaded intothe computer is organized to reflect the memoryorganization of the memory space. As shown in Table1-2, the program file is broken up into segments,eachat a different location, with a different size, and withdifferent information. This is a simple example;largePC applications can have literally dozens of different,code, variable, data, and stack segments whereas a

    MemorySDace

    Figure f-t l Princetonarchitecture

    microcontroller application often only requires onlyfour (reset, code, data, and stack). The compiler andother application build tools are responsible for speci-fying and allocating memory in the application.

    Table 1-2Princeton Computer Frchitecture Flpplication File5egmenl and Function

    ExFeriment 3-PlE MEU Variable Memorg, Flegisters,and Program Memorg

    Reset

    CodeData

    Stack

    Function

    Address application starts executing at. Usually agolo at the start ofthe application code.Application code. Starting address and size specified.Variable space for application. Starting address andsize specified. Initial values for variables.Program counter and data stack.

    The PIC MCU is designed to use the Ilarvard com-puter architecture (see Figure 1-5) in which the pro-gram memory and variable memory/register spaces arekept separate from each other. Along with this, theprogram counter's stack is also kept in a separatememory space. The advantage of this method dudngprogram execution is the ability of the processor tofetch new instructions to execute while accessing theprogram memory/registers. Bad programs can still exe-cute, but at least they won't try to execute data asinstructions. The disadvantage of this method is a lossof flexibility in application organization (i.e., changingdata or stack segment sizes to accommodate differentapplications).

    Figure f-5 Harvard architecture

    Data Processorand Register

    lnterface

    r.8 l , a 3 P I C @ I I C U E x p e n i m e n t s f o n t h e E v i l G e n i u s

  • The program files loaded for PIC MCU and otherHarvard computer systems are much simpler than thefiles loaded into the Pdnceton computer systems.These are produced by the MPLAB IDE, end in theextension .hex, and are usually referred to as ,,hexfiles."A typical PIC MCU hex file consists of two orthree segments, one for application code (starting atthe reset address), one for the configuration fuses, andan optional one for electrically erasable programmableread-only memory (EEPROM) data. For the applica-tions presented in this book, the hex files will consistonly of the code and configuration fuse segments.There is no need for defining different areas in thememory space.

    This last point is subtle, but extremely important.Whenyots declare a variable in a Princeton computersystem, you are speciflng the label to be used with thevariable as well as reserving a space in memory for thevariable. When you are declare a variable in a Harvardcomputer system (like the PIC MCU), you are simplyspecifying the label to be used with the variable; thereis no need (or any mechanism) to reserve space for thevariable. This means that the location for variables in aHaryard computer system can be chosen with muchless rigor than in a Princeton computer system, and theHarvard application can still be expected to run.

    The separate memory areas also mean that initialvariable values cannot be loaded into the data segmenLin the Harvard computer system variables are initial-ized from program memory. In terms of hex file space,you save on the need for a data segment, but you dorequire more for the initialization space. For microcon-trollers, this is not an important point because in eithercomputer architecture, variables will have to be initial-zed by code, because the applications are not loaded[]to memory as they are wirh a PC.

    Although I've probably given you the perceptionthat variables can be placed any.where willy-nilly in thePIC MCU, the truth is a bit more complex. As I workthrough the book,I will explain the variable memoryand register space in more detail, but for now I justwant to note that they share the same space andexplain a bit about the function of the registers.

    What I am casually calling the registers in thisexperiment are refefied lo as the special function regis-ters by Microchip (and, similarly, what I am callingvariable memory is more properly called the file regis-ters), the special function registers (SFRs) listed inTable 1-3 are used to monitor the status of programexecution as well as provide an interface to the hard-ware peripheral functions of the PIC MCU. As youread through the book, the function and addressing ofthese registers will be explained to you.

    Table 1-3PlEl6FEBq Microcontroller 5DeEial FunctionFleg istersName Flddress FunctionINDF 0x00 & 0x80 Index Data RegisterTMRO 0x01 TMRoValuePCL 0x02 & 0x82STATUS 0x03 & 0x83

    FSR 0x04 & 0x84PORTA 0x05PORTC 0x07PCLATH 0x0A & 0x8A

    INTCON 0x0B & 0x8BPIR1 0x0C

    TMR1L 0x0ETMR1H 0x0FT1CON 0x10TMR2 0x11TMR2CON 0x12CCPR1L 0x13CCPR1H 0x14PWM1CON 0x15ECCPAS 0x16

    WDTCON 0x17CMCON0 0x18CMCON1 0x19ADRESH 0x1EADCONo 0x1FOPTION 0x81TRISA 0x85TRISC 0x87PIE1 0x8C

    PCON 0x8EOSSCON 0x8FOSCTUNE 0x90ANSEL 0x91PR2 0x92WPUA 0x95IOCA 0x96

    VRCON 0x99EEDAT 0x9AEEADR 0x9BEECON1 0x9CEECON2 0x9DADRESL 0x9EADCON1 0x9F

    Low 8 Bits of the Program CounterPIC MCU Processor StatusRegisterPIC MCU Index RegisterPORTA I/O Pin ValuePORTC I/O Pin ValueUpper 5 Bits ofthe ProgramCounterlnterrupt Control RegisterPeripheral Interrupt RequestRegisterLow Byte of TMR1 ValueHigh Byte of TMR1 ValueTMR1 Control RegisterTMR2ValueTMR2 Control RegisterLow Byte of CCP RegisterHigh Byte of CCP RegisterCCP PWM Control RegisterCCP Auto-Shutdown ControlRegistetWatchdog Timer Control RegisterComparator Control RegisterComparator Control RegisterHigh Bits of ADC ResultADC Control RegisterPIC Operation Control RegisterPORTA Data Direction PinsPORTC Data Direction PinsPe pheral Interupt EnableRegisterPower Control RegisterOscillator Control RegisterOsciilator TLning RegisterADC Pin Enable RegisterTMR2 Period RegisterWeak Pull-Up Enable RegisterInterrupt on Port Change SelectRegisterComparator Vref Control RegisterEEPROM Data RegisterEEPROM Address RegisterEEPROM Control RegisterEEPROM Write Enable RegisrerLow Bits ofADC ResultADC Control Register

    ! & !

    &,!,ta

    ft\$-*L, i ,

    1t'9.ii . i

    I

    E*tl

    ".,.t-

    va:*gn:xiLJ

    i1rF.t

    tf':

    ti iit;*.d

    yt"itfil

    {r?

    Section One U n d e r t h e C o v e r s o f t h e P f C l t F b g q 1 9

  • Experiment U-Simulat ing cFlaEh.c in MPLHB IDE

    The simulator built into the MPLAB IDE is probablythe least used and understood tool available to you,which is unfortunate because it is the most effectivetool that you have to find and debug problems.Thereasons why applications are nol simulated is due tothe perceived notions that it is too much work and thatthe program is either very simple or based on simplechanges to a working program. Old hands will cringeat these excuses and remember how they learned thehard way. PersonalIy,I never attempl to burn a pro-gram into a PIC MCU without first simulating it andmaking sure that it works properly. I always do thisbefore seeing if it will work in the application circuit;by simulating it first you have confidence that the pro-gram should run.

    In this experiment, I will work through the basics ofsetting up the simulator for an MPLAB IDE project. Ihave a few comments regarding how it should be usedbut, for the most part, I recommend that you use it forall the experiments in this book. Some of the initialprogramming (C and assembler) experiments aredesigned to work only in the simulator, but once again,you should simulate the experiments that access hard-ware before burning them so you can understand howthey work and what they are expected to do. As yougain experience with the simulator, you should alsodevelop personal standards for displaying data andunderstanding what the simulator is telling you inorder to find problems and gain confidence in yourprogram.

    After you have created a project and have built thesourcecode to ensure there aren't any syntax elrors(language formatting errors), you should enable thedebugger by clicking on "Debugger," then "SelectTool," and "MPLAB Sim" as shown in Figure 1-6.After enabling the simulator, the simulator toolbar(see Figure 1-7) will appear. The toolbar will allow youto do the following:

    . Run the simulated program at full speed. On a2.4 GHz Pentium running Windows XP, I findthat 1 simulated second executes in about 3seconds,

    Stop execution at any tirne. A breakpoint,whichforces the application to stop at a specific loca-tion, can also be put in the application code as Iwill show presently.Clicking 'Animate" causes the program to runrelatively slowly, so you can watch the flow ofthe program. I find that this feature is best usedto illustrate the operation of basic operatingconcepts.The program (subroutine or function) can beexecuted one step at a time by clickin g |he StepIn icon.If the operation of a subroutine or function iswell understood and felt to be correct or if ittakes a long time to execute, clicking the S/epOver icon will cause the simulator to executethe code in the subroutine or function at fullspeed and stop at the statement following thecall to the subroutine or functionIf you find yourself in a subroutine or functionthat is going to execute for a while, you canStep Out of it. After clicking this icon, executionwill run at full speed, stopping at the instructionafter the subroutine or function call statement.

    . To restart the simulation from power up, clickon the Reset icon. This icon will cause the simu-lated PIC MCU to return to power up condi-tions and reset the Stopwatch and Stimulusfunctions as well.

    'fo set abreakpoifi (which causes execution to stopwhen it is encountered) in your program, double-clickon the statement at which you wish the breakpoint tobe placed. Execution will stop when the simulator isrunning or animating an application, when a break-point is encountered. The breakpoint's statement is notexecuted but will execute if the Run. Animate, or oneof the Step icons is clicked. Figure 1-8 shows cFlash.cwith three breakpoints set and the execvtron run arrowpointing to the first statement in the program.

    At this time, you may want to start up your cFlashproject, enable the simulator, and put breakpoints atthe three locations I have in Figure 1-8. Once you havedone this, click on the Reset icon and you'll see thatthere is no run arrow. If you click on one of theStep icons repeatedly, the alrow won't appear and youmay think that you have not enabled the simulatorproperly.

    If you click on the Run icon, the program will stopand the run arrow will appear at the first breakpoint(at "PORTA : 0"). Before the C program startE there

    l , e l P I C @ l ' l C U E x p e r i m e n t s f o r t h e E v i I 6 e n i u s

  • D d k . , . i

    'CIPlCCLrTE\Bll.{flCl a4' C E cfl.sh @, cF ash.c'-O'cF dsh lbf,Zg9 .O .O MA_AA ,t EFOB4

    'CleLCO-rT\all.dPlCt E'-E cFllsh.lde,'C\vvitig\8to Eli Gei],s\Gd;\cl ash\cFt&h ob , O"cFtash cot -0..F 4i hef -O -MPI-IA -l6FdB1

    ( { ) b v ! s0070 s0031 ( 1 ) b t res

    s000s I 5) byls !o!ar Bnd 0 RAlt

    Figure l-6 Enabling MPLAB simulator

    is some code that sets up the execution environmentand calls the C program. Placing a breakpoint at thefirst statement in the program and then clicking on theRun icon after resetting the simulator, will provide youwith an application that is ready to go from the firststatement.

    Now would be a good time to start single-steppingthrough the program.

    When you get to the for statements,you'll see thatthe alrow doesn't move for each click of the Step iconsor even seemingly for the Animate icons.These state-ments provide a half-second delay for the program-you can execute through them quickly and stop at thestatements after them by clicking the Run icon.

    To understand better how long an application istaking to execute, click "Debugger" and then,,Stop-watch" to display the Stopwatch window shown in Fig-ure 1-9.This window will show you how manyinstruction cycles have executed and how long it would

    have taken if you were working with a PIC microcon-troller running at 4 MHz (which is the default execu-tion speed of the PIC16F684).The simulated executionspeed can be changed by clicking on "Debugger" andthen on "Settings;" this pop-up also allows you tochange other operating parameters of the simulator.

    You can also monitor the values of resisten andvariables in your program by adding a Wuch winclow(see Figure 1-10).To add a register, select it in the pull-down to the dght of 'Add SFR" and click on ,AddSFR;" to add a variable, select the one you want fromthe pull-down to the right of 'Add Symbol" and clickon 'Add Symbol." For your initial programs, I recorn-mend that you always put in the I/O (TRIS andPORT) registers as well as all the variables in yourprogram. When you are putting registers and variablesinto the Watch window, you may feel that the methodin which they are displayed is suboptimal.You canchange how they are displayed by right-clicking on the

    5ection One U n d e r t h e C o v e r s o f t h e P I C l h F h A q 2 L

  • l-,;;;;

    l* ,,Run,, "Animate": z1. ' ' ;iir:

    ,*.*

    91ri

    i-1..*

    ::d

    'irj

    :

    t:'.r-i? .; : 1 :

    :;;.ti.i

    "Pause/Stop" "SteP ln'

    Figure l-7 Simulator active

    Executionat Breakpoint(Arrow Over'8")

    BreakpointsSet

    Figure l-B Setting breakpoints

    2 2 l , a 3 P I C o I I C I J E x p e r i m e n t s f o r t h e E v i l G e n i u s

  • 14H

    t UL*

    3*t

    {u

    tt

    ?"t*,

    l 1

    ."{?";"{

    C J

    nr

    1 d

    SlopwatchWindowActive(46 Cycles)

    Figure l-9 Adding Stopwatch

    "Watch" Window

    s u r * * eL!4t 'd6 qdt . | 4

    'r rd6r | l.@f---Effi

    Figure 'f -10 Addine aWatchWindoh,

    S e c t i o n O n e U n d e r t h e C o v e r s o f t h e P I C l , t F h A r + 2 3

  • D d l l r * C a l . t

    SelectRegisterNariDisplay TypeSize andOtherParameters

    vdPs1tAetodt!d@---- l

    kl!b---l'*li;----:j

    rro&l:-.+ l

    l F l r , i i I b * l 4 1 4

    h t r f ' G q J f @ l @ - t r _ - f f i

    t r o @; ; : i* ,- . ; ; ; '

    L"t

    '"t.S'r

    HU'*n{

    IJJ

    Fi qure I -'f 'f Changing Watch data types

    variable, selecting "Properties," and then changing thedata format as shown in Figure 1--11.

    With the information I have presented here, youcan simulate most of the functions of the code writtenfor the experiments in this book. Right now, you canjust monitor the operation of the code, but in a laterexperirnent,I will show you how to set specific inputand register stimulus, which will help you see how yourapplication runs under different conditions.For now, you can change register values by double-clicking on their value in the Watch window and put-ting in new values manually.Adding stimulus to asimulated program takes a bit more work than theexecution, breakpoint, stopwatch, and variable displaysteps I've shown here, but it provides you with a way totest your application under constant conditions, ratherthan depending on remembering to set certain valuesmanually.

    One of the nice features of the MPLAB IDE simu-lator intedace is that it is the same as the ICD 2debugger and ICE 2000 emulator interfaces Thismeans that when you start working with these tools,there should be only a minimal learning curve goingfrom the simulator. The simulator features I've pre-sented here are also present in the debugger and emu-

    lator. Debuggers and emulators provide hardwareinterfaces to the application circuit (actually replacingthe PIC MCU in the circuit) that you can monitor, setbreakpoints for, and repeat over different sections ofcode,just as you would in the simulator.

    At the start of this experiment, I suggested thatyou use the MPLAB IDE simulator to test all theapplication code in this book (and any that youencounter) before burning it into a PIC MCU. Bydoing so you will gain experience with the simulatorand learn to come up with strategies that work best foryou. Additionally, you can experiment with placingyour editing, watch, and stopwatch windows on theMPLAB IDE desktop in positions that make the mostsense to you and that allow you to debug your applica-tions efficiently.

    For ConsiderationWhen people start investigating Microchip PIC micro-controllers for the first time, they are generally over-whelmed by the number of different part numbers(microcontrollers with different lealures) that are

    2 4 l , e 3 P I C @ l ' l C l J E x o e r i m e n t s f o r t h e E v i I 6 e n i u s

  • available. As I write thiE there are over 250 active PICMCU part numbers to choose from, not includingpackaging options. Most PIC MCUs are available withat least three different packages; each part number isavailable with two operating temperature mnges, andthe older parts are available in different voltageranges This means, when all is told, there are about2,000 different PIC MCUs and options to choose from.Over the next two pages,I would like to make yourchoice a bit simpler.

    There are six rnajor PIC MCU families to choosefrom as I have outlined in Table 1-4. The PIC16F684that is featured in this book may seem like one of thelower-end PIC MCUs, but it is actually a quite flexiblemember of the mid-range.

    The low-end PIC MCU processor architecture isavailable on many of the entry-level parts. The proces-sor is very similar to the mid-range architecture (whichis used in the PIC16F684) but does not have someimmediate instructions, does not support interruptrequestq cannot support large amounts of variablememory and does not have any advanced peripherals.The mid-range PIC MCU architecture is the most pop-ular architecture (and used in the PIC16F684), as itsupports moderate amounts of variable memoryadvanced peripherals, and interrupts. The PIC17 high-

    end architecture is somewhat unique to this familv ofmicrocontrollers although it does iave some simjLri-ties to the low-end and mid-range. The PIC18 architec-ture is really a superset of the mid-range architectureand it offers a number of features that allow it toaccess more program memory variable memory, andperipheral registers as well as instructions that willsimplify and speed up traditional applications. Onceyou are comfortable with programming the mid-rangechips and have worked through the experiments in thisbook, you shouldn't have any problems learning howto program and working with the other PIC MCUarchitectures

    Most new users and hobbyists limit themselves tothe parts listed in Thble 1-5.These devices are all easilyprogrammed either by the PICkit 1 starter kir, PIC-START@ Plus,ICD 2, or a homegrown programmer(of which there are many different designs availablefor dornload from the Internet). The Microchip ICD 2is a debugger interface that gives you many of thecapabilities of an ln-circuit emulator (ICE) without theextreme cost of an ICE.

    I want to make a few comments on each of thedevices listed in Table 1-5. The PICSTART Plus is adevelopment programmer produced by Microchip,which can be used for all PIC microcontroller Dart

    qt\Jnn

    $l!-.p-or-t8'alF.ot

    Table 1-4

    Il::::!il llc yi::?:::,T1P,'-. l"'"iIi*PIC MCU PmcessorFamilg FlrchleEture

    Programmlng PtugEmPlgqrithms and ICD Memory Tgpe Memory Slze Begt4er Size lO Plns Featues

    PIC10 Low-End (12 Bit) ICSP and ICD

    PIC12 Low-End (12 Bit) ICSP

    256 to 512 16 to 24 bytesinstuctions512to\,0u 25 to 41 bytesinstructions512to2,048 25 to 128 bytesmstructrons

    4096 instructions 192 bytes

    512 to 2,04a 25 ro 73 bytesinstructions512to8,192 72 to 368 bytesinstructions

    4 Comparator

    6

    6 Compamtorand ADC,AdvancedTimers

    20 ComparatorandADC,AdvancedTimefi

    121o20

    12 to 33136 ADC,Se alto 52 for I/O, AdvancedLCD Timerg

    LCD, USB33 to 66 Extemal

    Bus, SerialI/O, AdvancedTimers

    16 to72 ADC,SerialI/qAdvancedTime$

    Flash

    EPROM (OTP)

    PlC12 Mid-Range (14 Bit) ICSP and ICD EPROM (OTp)and Flash

    PIC14 Mid-Range (14Bit) ICSP EPROM (OTP)

    PIC16 Low-End (12 Bit) Parallel,ICSP EPROM (OTp)on Flash Parts and Flash

    PIC16 Mid-Range (14Bit) ICSP and some ICD EPROM (OTp)and Flash

    PIC17 "High-End" (16 Bit) Parallel EPROM (OTP) 2k to 16k 272to902bytesrnsrucnons

    PIC18 "PIC18" (16 bit) ICSP and ICD EPROM (OTp) 8k to 64k 6,10 to 4,096 bytesand Flash instructions

    Section Bne U n d e r t h e C o v e r s o f t h e P I C I E F h A t + 25

  • numbers-in some cases adapters are required to pro-gram the parts. In some cases, another PIC MCU partnumber has to be used to implement the ICD 2 func-tion for a specific PIC MCU. Although the PICC Litecompiler is either restricted or not available on someof the PIC MCUs listed in Table 1-5, the full productsupports each of these PIC MCUs and does not limitthe program size or number of variables required forthe application. Each of the listed PIC MCUs has flashprogram memory! which means that they can be erasedby the programmer before burning a new applicationinto them. All of the PIC MCUs except the PIC16F54have the mid-range processor architecture. I includedthe PIC16F54 because many early introductory booksand web sites reference the PIC16C54. and thePIC16F54 can be used in its place for these applica-tions. Another traditional beginner's part is thePIC16F84A, but I would recommend that you considermore advanced and feature-rich chios such as the

    PIC16F627A instead.These more advanced chips haveadditional peripheral features as well as built-in oscil-lators, eliminating the need for you to add oscillatorcircuitry to your application.

    I chose the PIC16F684 for this book because it is amid-range architecture part (14 bit), can be pro-grammed by the PICkit 1 starter kit, and has ICD 2and PICC Lite compiler support. This chip also has abuilt-in precision oscillator and is tolerant of a widerange of operating voltages. It also has a wide range ofperipherals that make it appropriate for use with appli-cations like robotics.To summarize,I feel thePIC16F684 gives the best cost-to-performance ratio(when the PICkit 1 starter kit and PICC Lite compileris included in the decision) for a mid-range part thatcould be used in a wide variety of different applica-tions and would be easy for somebody learning towork with the PIC microcontroller.

    Table 1-5Flecommended First PIE MEIJsPan Numbs PtugEm Va ableNumber Df Plns Memog Mem1rg

    PIC16F675 6 1,024 inslructions 64 bytes

    PIC16F630 12 1,024 instructions 64 bytes

    PICI6F6U4 12 2,048 instructions l2tl byles

    PIC16F54 13 512 instructions 25 bytesPIC16F84A 13 1,024 instrlctions 68 bytesPICI6F627A 16 1,024 instructions 224 bytes

    PICl6F87x 22 to 33 4,096 to 192 to8,192 instructions 368 bytes

    PeipheBls

    ADC,Timers

    Comparator

    ADC, Comparator,TimersNoneNoneComparator,Timers,Serial I/OADC,Timers,Serial l/O

    and Debugqel

    PICkit 1 starter kit,PICSTART PIUS,ICD 2Plckit 1 starter kir,PICSTART Plus,ICD 2PICkit 1 starter kit, PICSTARTPlus,ICD 2 Using PICI6F688PICSTART PlusPICSTART PlusPICSTART Plus,ICD 2

    PICSTART Plus,ICD 2

    PICC Lite su1pott

    Yes

    No

    Yes (Limited Size)

    NoYesYes (Limited)

    Just PICl6F87?Aand Limited

    2 6 l , P 3 P I C @ f l C U E x o e r i m e n t s f o r t h e E v i l G e n i u s

  • Introductoru f Programming

    1 P r c 1 6 F 5 8 4

    I often see the C programming language described asthe Universal Assembly Language by people trying toput it down.This isn't a very fair characterizationbecause C is an extremely flexible programming lan-guage that was the development tool of choice for vir-tually every operating system in use today, as well asfor a long list of successful business applications andgames. Along with common computer science applica-tions, C is used to program more artificial intelligence,computer-aided design systems, aerospace control sys-tems, and supercomputer applications than any otherprogramming language. Despite acknowledging C'swidespread use and popularity, detractors tend tofocus on a few points.

    C is an incredibly rich language that makes it suit-able for a wide variety of different applications. Thisrichness can be a two-edged sword; instead of forcingevery developer into following a common programlayout, C allows a wide of programming styles. As Iwill discuss at the end of this section, multiple C state-ments can be combined, which can make code unread-able to even the most expert programmer.Anacknowledgment of C's capability to be written intoincomprehensible code is the single point of theyearly "International Obfuscated C Code Contest"(www.us.ioccc.org/) in which the most confusing codepossible is created for prizes.

    The richness of the code is often given as a reasonfor why C is hard to learn. I regularly contest this withproponents of BASIC, JAVA, and other programminglanguages. All these programming languages have asimilar number of statement types, and I do not believethat any one has advanlages over another to make

    S e c t i o n T w o

    programming with it more efficient. In terms of read-ability, poor code can be written in any language. Goodprograms are not the result of the language designer;they are the result of the programmer thinking abouthow to approach a problem and clearly expressing intheir code what the programs are doing.

    Additionally, C is heavily dependent on pointerE aprogramming concept that many people find difficultto work with, debug, and understand, especially whenreading other people's code. I admit that I like workingwith pointers, but this is due to spending many yearsunderstanding what pointers can do when pro-grammed in C and how they can be used most effi-ciently for most applications. In this book, I willintroduce you to the basics of C pointers and try toemphasize only the things you have to know to workwith the language. For most C applications, pointersare minimally required and are often quite transparentto the operation of the program.

    My major complaint about the C programminglanguage is one that few people comment on;in itsANSI standard form, C cannot access data smallerthan bytes. The version of C used in this book can readfrom and wdte to bits, but you will still require somevery convoluted code to carry out some hardwareinterfacing.

    Despite these concerns, C has a number of charac-teristics that make it well suited for use in this bookand for individuals learning about programming.Firstly, because the language is over thirty years old, aplethora of books has been written about learning andcoding it. Secondly, it is actually quite easy to wdteefficient and readable code in C, and a good portion of

    27

  • the text in this book is devoted to teaching you to dojust that. Lastly, I believe HT:Soft's PICC LiterM com-piler is the best highJevel development tool availablefor the PIC16F684 microcontroller, and I'm pleasedthat it can be used in this book to teach you about thePIC@ microcontroller.

    PICC Lite compiler has three things going for itthat I feel are critical to its use in the book and for useby new users. First, it integrates extremely well withMPLAB@ IDE. As shown previously, PICC Lite com-piler works not only with MPLAB IDE's basic opera-tions, but it produces the necessary informationneeded by the MPLAB IDE simulator, MPLAB IDEdebuggers, and ln-cCircuit emulators (ICEs) to allowsource-code-level debugging. I feel this is critical forproducing, testing and analyzing applications.

    Second, PICC Lite compiler produces very efficientcode.In Section 12,I demonstrate how I would solve anumber of math problems using assembly languageprogramming. At the start of each program, I havewritten out the operation of the program in C;you may

    want to cut and paste this example code into separateC source-code files and see how efficient my assembleris to the code produced by PCC Lite. I would be sur-prised if my code had more than 10 percent fewerinstructions than any application, and I wouldn't besurprised if there are cases where PICC Lite versioncreated code with fewer instructions than I did.

    Finally, the price of PICC Lite compiler cannot bebeat. PICC Lite compiler is not a crippled version ofthe full productiit includes a1l the capabilities, includ-ing code optimization and simulator/debugger/emula-tor support, of the full product.This is an importantpoint because with PICC Lite compiler integrated intoMPLAB IDE, you have a development environmentwith capabilities that would normally cost well over$1,000 dollars. Thken together, the C programming lan-guage, with applications written with an eye towardreadability and efficiency and implemented in thePICC Lite compiler, is the best method of learningabout the PIC microcontroller, microcontroller pro-gramming, and application debugging.

    Experiment 5-Variable Declaration StatementsDeclaring variables in PICC Lite compiler is generallyas simple as:

    int variableNamet

    before the main statement of the application. This willcreate a 16-bit variable with the label VariableName(or whatever variable name you want) that can be usedanywhere in your program. In this experiment, I wouldlike to discuss a few issues regarding variable and hard-ware register declarations to help you make sure thatyou can successfully create applications even thoughyou have worked through only a few experirnents inthe book.

    VariableName is a label and can start with anyupper- or lowercase letter or the underscore character.After the starting character, the rest of the label can beany letter, number, or underscore character. Blankcharacters cannot be used in a label;if blanks areencountered, the compiler will try to divide the charac-ter strings to determine which of them are program-ming statements, directiveg or defines.These characterrestrictions are also used for subroutine and functionnames,

    For standard variables, two options exist that youshould be aware ol The first is the ability to initializethe variable when it is declared. By adding an equalssign and a constant value, you can set your variable to

    a specific value for the program without having to addanother line later in the code. To initialize the variabler to 47, you would simply key in:

    Another option that is available to the declarationstatement is the const ke1'word, which converts thedeclared value from a variable to a constant:

    conat in! xconstant = 47t

    In the declaration of xconstant, anytime the labelxConstant is encountered, the compiler replaces it withthe value 47. By declaring xconstant as a constant, youcan no longer write to it. For example the statement:

    xconstant = 48t

    will return an error.If you were to look at the pic16f684.h file that was

    put on your hard file when PICC Lite compiler wasinstalled in the \PICCLITE\nclude folder, you will seea number of statements that look like:

    static volalile unsigneal char tMRlIJ e 0x08,

    These are hardware register declarations andinvolve additional options that you do not need to be

    2 8 l , a l P I C @ l ' l C U E x o e r i m e n t s f o n t h e E v i l G e n i u s

  • concerned with, because HT-Soft has taken care ofdeclaring all the hardware registers in the PIC16F684microcontroller for you.

    I want to say a few words about variable names.Please try to make an effort to make them representa-tive of what they are being used for. I see many stu-dents create programs with variable names like Reg3when the name Remainder or PWMValue is muchmore representative of what the variable is used for inthe application. Although I recognize that the variablememory is limited in the PIC MCU, please do not feelyou have to use one variable for multiple functions; tryto use each variable for one purpose. Using the samevariable for multiple purposes can make writing yourprogram more difficult and cause problems when dif-ferent functions change a variable in ways that screwup the operation of other areas.

    One area that always gets new programmers con-fused is in the area of counters. I recommend that youuse the conventional variable names of i, j, k, and n.These values came into use with Fortran, the first high-level programming language, and by using them forthis function consistently, they are immediately under-stood when reading the code. By naming variablesapprop ately, you will find the tasks of tracking howdata is being processed by the application and ofdebugging the code much easier.

    As I explain more about the C programming lan-guage to you, I will expand the variable definition toinclude arrays, pointers, and local and global variables.For the time being, if you keep with the simple formatof the variable declaration that I have qiven you here.vou will not have anv Droblems.

    ExFeriment 6-C Data TgpesThe bit value is not supported by the C language stan-dard, and I would recommend that you do not use itfor variables. I realize that a single bit is useful forlagvariables rn aprogram, but because the bit is not avail-able in other C implementations, you will not be able

    Table 2-1PICE Lite ComEiler Data Tgpes

    Depending on your programming experience, the needto specify variable data types might seem new andsomewhat ominous to you. The restricted variablememory available to you in the PIC microcontrollerunder the PICC Lite compiler can make the decisionon what values to specify seemingly more ominous.There really is no need for this apprehension;mostvariables can be declared using the lnt data type wilh-out problem.

    The data types available to you are listed in Thble2-1. For the most part, the data types follow AmericonNational Starul.ards lnslinrle (ANSI) standards, or whatI call Standard C values, and are available in C compil-en for other processors.This allows you to import pro-grams or parts of programs (usually referred to assnippets) that have been created for other applications,but you would like to use on the PIC microcontroller.Similarly, if you were to come up with some good pro-grams or algorithms, this could be exported to othersystems quite easily.

    Three deviations exist in the PICC Lite compilerdata types to ANSI C that I have marked in Table 2-1.

    Tqpe Bit Sizebi l I

    Comment5

    Boolean value-Note: Not a StandardC data typeASCII character/signed integer (-128 to127)Unsigned inleger (0 1() 255)Signed integer (-32,7681o 32,767)Unsigned inleger (0 to 65,536)Signed integer (-32,768 to 32,767).same as shofiUnsigned iDteger (0 to 65,535);same asunsigned shortSigned integer (-2,147.483,648 to2.14'7 ,483,64'7)Unsigned integer (0 to 4,294.961.295)Reat (0 to 1/-6.81(10r3);Assume 3 dig,its of accuracy/default floating pointmodc;Note:Not a Stanldard C data typeReal (0 to 1/ 6.81(10r3)r Assume 6 dig-its of accuracy/specified using PICL -D32 compilation option Note: lnStandard C, this is float, not double

    unsigned char 8short 16unsigned short 16int 16

    unsigned int 16

    long 32

    unsigned long 32float 21

    5ection Tu-ro I n t n o d u c t o r y C P n o g r a m m i n g 2 9

  • to import the code directly to other implementationsof the C programming language, and you may end upgetting in a bad habit of working with bit variables.Note that I do not make the same comment for indi-vidual bits in a special purpose register.The registerbits are unique to the PIC MCU and, as such, wouldnot be involved in a code export to another device.

    me float and doubk (floating point) variable typesare substantially smaller in their PICC Lite compilerforms than in their high-end processor forms. For themost practical applications, you will not see a differ-ence between how they execute, but you may haveissues with very large numbers or numbers havingmany digits of precision.

    As I have indicated, the C data types are stronglytyped, and when you are equating values betweentypeE you may get a waming or an error from thecompiler indicating that a type conversion is required.If the data is stored in a format compatible with thedestination, the simplest way of resolving this is to usethe type cast, which consists of placing the desired datatype in parenthesis before the source variable. Forexample, if the variables i and j were different tlpesbut data could be passed between them, a simple typecast. as shown here. could be used:

    i = ( iTr 'ee) j ,

    The experiment for this application is quite simple;just a few lines of code demonstrate what happenswith type conversion:

    *incluale /* cTlDe.c - rave6tigate Dala Type operation inPICC lJite cdE)iler

    Tbie Program shosra the Deal for TtrD Casling ofvariab].es

    wheu dlata iE tsransfrretl.

    ThiB plograln is tlesigrned tso run unaler the MPr.alIDE Siltrrlator

    on1y.

    nlrhe prealko0 { . 0 9 . 1 5

    whi le (1 == l l r / / Loop Forever) // Enal cTtrp

    When you compile this application, you are going toget the message:

    warningt000l C:\ Evil Genius \c!P!.De\cTtDe. c 27 :iq)licit converEioa of float to inlege!

    This message is telling you that the statement "i = j;"involves a data conversion. When this message comesup, you have to decide whether or not to resolve it byusing a type cast or by leaving the warning as isRemember that the two data types store data in differ-ent ways (which can be inferred from Table 2-1); cast-ing the float type to a char is a bad idea because withthe type cast, the fkst byte of the float type could bepassed to the char without being modified. In this case,you would leave it as is.

    For virtually all the applications in this book and forvirtually all the PIC MCU applications that you will doon your own, you will only require the int data type.This 16-bit bit-variable data type will handle a reason-ably large range of values as well as work with ASCIIcharacters. This data type is handled well natively inthe PICC Lite compiler, but for long and floating-pointdata types, additional libraries will have to be added tothe final application. These libraries take up quite a bitof space and can slow down the execution of the appli-cation significantly. To avoid this space issue andreduced execution performance, I recommend thatthese data types not be used unless absolutely neces-sary and the impact of their operation is well under-stood. Later in the book, I will give you a couple ofthoughts on how to simulate the operation of thesedata t)?es using 8- and 16-bit vadables.

    char itf loat j t

    main ( )t

    i = 47 t

    j = i; // can voui = i , / / can you

    Plac char into f,loat?

    Place float inEo char?

    u t

    { ! I

    H-l

    ff4

    t,,lt t !

    '&&*

    3C

    30 l , a 3 P I C @ l l C U E x o e r i m e n t s f o n t h e E v i I 6 e n i u s

  • Experiment 7-Constant Formattingl-+1

    . aJ

    iU

    i-

    't rt

    l ' a -

    !i,

    i:?

    1=i:-;;

    When I introduced declaring variables, I suggestedstrongly that variable names should be representativeof what the data is used for, and if the variables areused for common functions (such as counters), theyshould be given conventional names.This plea iscommon to many programming books, but what isn'tall that comrnon is a pointer to speciq/ing constantsin the most appropriate data type for the situation.The readability of a program can be enhanced or dam-aged by program formatting, by variable names, or bycomments.

    Table 2-2Eonstant Formatting OFtions and 5uggested BestUseE

    -CONFIG(INTIO & !{DTDIS & PWRTTN & IICIJRDIS &T'NPROTECT \ & I'NPRC},IECT & BORDIS & IESODIS &FC!'DIS) t

    main( ){PORTA = 0tCMCONo = 7i // Turn off Corq)aratorsANSEIJ = 0r // Turn off JU,CTRISA - 0*49t // E':able PORTA IJED Oull>uts

    whi le( l == 1) / / I joop Forever{i f ( 0 = = ( P O R T A & ( 1 < < 3 ) ) )

    PORTA = '3'- // Tuln on Fou! LED8eLse

    PORTA = 4r // Turn on Remaining Four IJEDS

    ) / / er ihw) // Enal cconfu8e

    Chances are, you could not understand whatcConfuse does by just looking at it.You will probablyhave to look at a schematic for the PICkit 1 starter kitLEDs and application input hardware. By making fourchanges to this prograrn (and turning it into cClear.c), Ithink you'll agree that the function and what is hap-pening is a lot easier to understand.

    * incluale /* ccLear.c - *cconfuse.cz af ter pasaing througha Deobfuscator

    T]hia is lh same program as $cconfuse. c-, but withrrore appropriately chosen constant tlata values.

    nyk predlko0 { . 1 1 . 1 s

    CONI,IC ( IIITIO & WDTDIS & PWRTEN & I{CLRDIS &IJNPROTECT \ & I'IIPROTECT & BORDIS & IESODIS &FCI'IDIS ) i

    nain( ){PORTA = O'Cl.fCONo = 7; // \tr'r ofg CornpalatorsANSEIJ = 0t // I'urn off ADCTRISA = 0b001001i // EnabLe PORTA LED Outsputss

    wr! i re(1 == 1) / / looD Foreverti t (0 == 8A3 )

    PORTA = 0b010010t / / But ton Presseal , D0, D2,D4, D7 On

    PORIA = 0b000100r // BI'rt.Eo'r Releaaeal, D1, D3,D5, D5 On

    , // eli'nwl // Enal cclear

    Constant Definition FomatDecimal ##HexadecimalBinaryASCII

    Best UseDefault Value

    0x## Register CounterValues0bf#ff i fr fr f Noncounrer RegislerValues'#' Human Interface Values

    There are four ways to specify comments, as is listedin Thble 2-2 along with the situations where they arebest used. In cconfuse.c, I have created a simple appli-cation that uses data in different formats; before burn-ing it into a PIC16F684 and running it in a PICkitrM 1starter kit, try to figure out what it does.

    * incluale /r ccoffus.c - wri! to plcki! InterfaceIlaralware in a Confuaing Way

    This program Derforms a simple task. but ilsfunction ia obfuscated b!' poorly chosen dtatat]lDes.

    fiE'ke prealko0 4 . 1 1 . 1 5

    5ection Tulo I n t r o d u c t o r y C P r o g n a m m i n g 3 1

  • Three of the changes were to convert the TRISAand PORTA register assignment values to binary fromdecimal, hex, and ASCII. I think you will agree thatthey were effective and helped you see what was hap-pening in the application and the output values. Thefourth change was to eliminate the complex test of theRA3 (button input pin) and simply do a bit compare.With the bit compare, you could easily look at thePICkit 1 starter kit schematic and see that RA3 is con-nected to a pulled-up push button.

    When deciding which constant format to use inyour program, you might want to follow these rules:

    . Use decimal by default. For basic variable andvariable functions, decimal is probably mostappropriate and easy to read.

    . Use binary when you are working with a regis-ter that does not contain counter data. An

    example of this is loading the OPTION registerwith the value 0b10011111.

    . Use hexadecimal for register counting or resultdata, Comparing a counter's current value witha hexadecimal constant would be most appro-pnate.

    . Use ASCII data when human interfaces areinvolved.This includes text messaging as well asuser input.

    . Data sizes should be appropriate. Use six bitsfor the two sets of six-bit PORT and TRIS reg-isters. For other registers, use eight bits.

    I think what I am trying to say in this experiment isbest summed up by the maxim: "There are 10 types ofpeople in this world: those that understand binary andthose that don'1."

    Experiment 8- Rssignment Statements

    .:t,13

    $.i.i l

    -i-,

    i t t

    a::-i

    .rjr",il i:

    t_'j'

    1l'-.

    .'].{

    ,t:;

    I

    c;

    .:;".1

    ....

    ill1.:

    1::

    If you are familiar with other highJevel programminglanguages, you are aware of the statement type calledthe assignment statemezl, which is used to store data ofa variable of a specified type. In the previous experi-mentE I have detailed different data types as well ashow variables are declared. In this experiment I willpresent how assignment statements are written in C.

    The basic form for a C assignment statement is:

    ValldbleNam = E

  • nJake prealko0 4 . 0 9 . 2 4

    ) // End cAsaigTl

    The filst assignment statement is the initializationof the variable j. There is no difference between initial-izing a variable at its declaration and assigning a valueto it in the ffust line of a program. You may find thatinitializing a variable at declaration is easier to read,making its function easier to understand in the pro-gram.The next two statements are basic assignmentsof a constant value and a variable value, respectively.These statements are common to other programminglanguages and their operation should be obvious.

    The last assignment statement is probably some-thing that you have never seen before in BASIC orother beginner programming languages; the value of iis given the value ofj, which itself is being loaded witha new value.This is one of the many capabilities builtinto C that can be used to both simplify applicationprogramming and obfuscate the function of the appli-cation code. This ,lultiple assignment statemen1whichhas multiple deslinalions [or the expression. is reason-ably clear, but as I will show in the next experiment,multiple assignment statements can become quite

    complex, with their function being confused with thebuilt-in assignment statements.

    Access (read and write) of PIC16F684's registersand I/O Pins is accomplished using standard assign-ment statements such as the ones demonstrated incAssign.c.The registerg bits, and pins are all declaredin pic16f684.inc, which is loaded in by pic.h. cl-ight.c isa simple application that simply turns on D0 on thePICkit 1 starter kit and illustrates how registers can bewritten to 8 bits at a time, just as 8-bit variables (oftype char).Indivrdual bits are read from and written toin exactly the same way.

    #incLude /r clisht.c - Sinple c Program lo Turn on an LEDon a PIC16F584 in the PICki t 1

    aA4 - LED Poaitive Connectiona-45 - r,ED Negative Connection

    myke predlko0 { . 1 1 . 1 0

    i r t j = 23,/ / udi t iaLized var iabl Dclarat ion// valiabl DecLareil with Initial/ / value assisnment ( In i t ia l izat ion)

    The variable \ri', aBsigned (or loaalealwith) the conalanl value 47rhe variable "i,, aaEigneal contents

    // "i" axud "j" aasigneal the Ean6 va1ue.

    nain( )t

    CONFIG(II\TIO & WUTDISUNPROTECT \ & UNPROTECTFCTiIDIS ) ,

    nain( )(CMCoN0 = 7; // Tlrr|ANSEIT = 0r // A\rrLTRISA{ = 0r // rtakeTRISAs = Oi

    aA4 = 1r // '\ErLn-4,5 = 0t

    vr{h i le( l == ! ) , / / hoop

    l // End cliqht

    &PWRTEN & IICI,RDISBORDIS & IESODIS

    off conpalatorsoff ADCRA4/RA5 Oueputs

    on LED

    Experiment 9 - Expressi ong

    In the previous experiment, I really skipped over whatan exnression is. This is unfortunate because a lot of

    potential exists in the capabilities of the C expressionstatemenl thal can make your programming easier andmore efficient. Unfortunately, this potential comes at acost: it's easy to create expressions that do not executeas you would expect, and are very hard to debug. Inthis experiment, along with looking at different typesof expressions that can be used in your applications, Iwill present some of the potential pitfalls you may haveto navigate around.

    To demonstrate the operation of C expressions, Icame up with cExpression.c, which examines different

    Section Turo I n t r o d u c t o r y C P r o g n a m m i n g 33

  • naitt( ){i = 3 tj = i ;

    i = j * 1 1 ,

    i = j * 0 x 0 B t

    formats for expressions and data. As you read throughthe description of this program, I suggest that you loadand single step through cExpression.c so you can bet-ter see the points that I am making.

    *incluale /* cE.Dression.c - Look at E {pressions

    Thia Program tlenronstrates a variety ofDif,f,ernt E apraaions that can be createal ilr C.

    nyk Drealko0 4 . 0 9 . 2 3

    Haralware Notea:ThiB Program has ben wlit.ten to run inthe MPtAa IDE Simu!.ato! ONLY,

    contents of i are the expression and they are saved in j.These are assignment statements,just like the ones inthe previous experiment.

    The next three statements have the same expres-sions ( x 11).The difference between them is the num-bering system (radix) used to express the constant 4.This is a review of the C DataTypes experiment inwhich I discussed how using bases other than 10 makesit harder to immediately see what is happening withthe code.

    In the assignment statements following the threej x 11 statementq I am applying the basic arithmeticoperations (addition [+], subtraction [- ], multiplica-tion [*], and division Ul, along with the modulus oper-ator [%]. The modulus of two numbers is theremainder of the division operation. In the next exper-iments, I will look at some of the other operators avail-able in expressions The next statement has anexpression that you have probably never seen before; Iam adding the contents of the variable j to the ASCIIcharacter zero (which is specified in single quotes as'0').The value of this expression (and the value storedin i) is 51 decimal, or if you change the Watch windowdisplay format for i to ASCII, you will discover that itis'3'.This may be a surprising result, but if you were toreview a table of the ASCII codes, you will see that thenumeric and alphabetic characters are definedtogether; so if you have one character's value, you canjump to another character simply by adding or sub-tracting the difference between them. This property ofASCII codes is used in a number of places in the bookto algorithmically change values instead of relying ondecision structures to change lhem.

    the "i : C - 5) % 7;" statement has what is knownas a compkx. expressioz: that is, multiple operations areperformed within the statement. Looking at the firststatement, it should seem obvious that five is added tothe value ofj and the sum is found using rnodulus 7.Right after this statement, I have repeated it withparenthesis around the "j - 5" expression removed.When the full expression is evaluated, you will see theresult (stored in i) is different than in the previousexpression.

    The reason for this difference is due to the order ofoperations of the operators used in these statements.The multiplication and division operators have ahigher order of operations, or what you could refer toas execution priority, than addition and subtractioninstructions have. Even though the addition operator isencountered before the modulus operator, the modu-lus operator executes first because it has a higherorder of operations. To avoid these problems, youshould enclose higher priority operations in parenthe-sis (indicating that their contents must be evaluatedbefore they are used for other operations) to ensure

    // n3" iB the E qr!aEion/ / \i" fa the ErqrleEEion

    // Siq)le AriEbmetsic E

  • they execute before other operators execute.As youlook through the code in this book, you will see that Iam in the habit of always using parenthesis to ensureexpressions are evaluated in the order l want them to.

    The final statement before the "while (1 =: 1):"statement may look like a syntax error or some kind ofcomparison, but it is an example of what I called amultiple assignment statement in the previous experi-ment. Neither is true; the expression saves the interme-diate calculation of i./6 in the variable j beforecompleting the evaluation and storing the result in thevariable i. This ability to embed assignments withinexpressions can help you simplily your programsand/or make them completely unreadable. When youfirst start creating your own C programs, I recommend

    that you do not try to combine statements as I havedone here. But when you gain some confidence thenyou might want to look for opportunities to takeadvantage of this capability. Especially look in situa-tions wbere the intermediate value of a calculation isneeded elsewhere in your application.

    With the five basic arithmetic oDerators and theabi l i ty to create ca lcu lat ions wi lh mul t ip le operators.you have the ability to develop expressions for thevast majority of applications that you are going to bework ing wi th. Before going on. t ry lo wr i te y our ownapplication like cExpression. Test out different expres-sions with the five operators listed above and with con-stant data in decimal, binary, hexadecimal, and ASCIIIorma ls.

    Experiment I 0-Bitr-r.rise Operators

    As well as being able to perform mathematicaloperations on the contents of variables, the C program-ming language has a number of operators that allowyou to perform Boolean arithmetic on the bit contentsof variables. These operators allow you to easilyprocess bit information, but they must not be con-fused with the logical operators described in the nextexpenment.

    The four basic bitwise operators are as follows:. & -bitwise AND. When two values are

    ANDed together, each bit in the result is loadedwith the AND value of the corresponding bitsin the two values (ser if both the bits are set).

    . I bitwise (inclusive) OR. When two values areORed together, each bit in the result is loadedwith the OR value of the corresponding bits inthe two values (set if either bit is set).

    . ^

    -bitwise XOR. When two values are exclu-sively ORed together, each bit in the result isloaded with the XOR value of the correspon-ding bits in the rwo values (set if only one of thetwo parameter bits is set).

    . - -bitwise negation.This operator will returnthe negated or complementary value for eachbit of the single input parameter (invert eachbit). This operator must never be confused withthe ! logical operator, which will be shown toinvert the logical value, not the bitwise value.

    Using these four operators, standard bitwiseBoolean arithmetic operations can be performed ondifferent values, as I show in cBitwise.c. After compil-ing cBitwise.c,I suggest that you work through thecode (including modifying values) in the MPLAB IDEsimulator as much as possible until you fully under-stand the operations work. When you are doing this,you should display the variables (i, j, and k) as binaryvalues in the Watch window.

    * incl"ude /* cBi tswise.c - Bi twise C operatols

    This Prograln Denonstlates how bitwis Booleanarithrnetic oDlatioas wolk in c.

    Note: Display the valiable values as \Bina!y".

    nyke predko0 4 . 1 0 . 0 2

    char i , j , k i / / use 8 Bi t . var iablea

    nain( )t

    Section Turo I n t r o d u c t o n y C P n o g n a m m i n g 35

  • j = a 3 7 i

    k = i & i t

    r r = i I i ;

    k = i ^ i t

    k = - i ;

    k = ( i * 2 )// Alitlu[ticw h i l e ( 1 = - 1 ) t

    l / / End cBi twise

    The operation of bitwise operators is very straigh!forward. Going through the example cBitwise experi-ment in the MPLAB IDE simulator, you should seethe Boolean arithmetic operations clearly when youdisplay the variables as binary in the order i, j, k. TheWatch window will display the two parameter valuesdirectly over the result, allowing you to compare theinputs and outputs to the logic gates directly. As shownin the last statement, bitwise operators can be com-bined with arithmetic operators without any specialconsiderations.

    Although the bitwise operators are straightforward,you can run into some difficult-to-debug situationswhen you write to registers in a PIC MCU (or anyother hardware device).To illustrate what I mean, con-sider the last statement of cBitwise and have it load aport directly. For this example, assume that the hard-ware device attached to this port saves the least signifi-cant four bits of the PORTA, and bit 7 of PORIA isconnected to a deyice clock. When the clock is pulsedhigh (or strobed), the hardware device saves the fourdata bits.The statement could be:

    poRTA = ( i * 2 ) - j + ( 1

  • The logic operators available to you in C are listed inTable 2-3 and return numeric true or false values. It isimportant to remember that logic operatorc are differ-ent from bitwise operators as they return essentiallybinary values (Tiue or False), where the bitwise opera-tor returns the logic operation for each bit.

    Table 2-3Logic OperatorgLagicOperator Operalion

    // E.DreaBion value

    == jt // r'IhaE is the value f,orFalae?

    l= j t / / Value f,or Tru?> jt // vallue f,or Falae?< i t / / val lu.o for Tru?

    != j ) && ( i > j ) , / / va lue f o rtrrue ANDFalB?

    t = i ) l l ( i > i ) t / / v a l u f o rTru6 ORFala?

    Hvt

    F'

    ini-lr )

    }J"r."8

    !"{

    *rH

    a

    FtqF.r.

    t dgjP

    FIX

    rdr-9{D{0{nt-,..

    Tru If BothTru if one

    = 1 & &= i & &

    Experiment 11-Logical Expressions0 4 . o 9 . 2 7

    i n t i = 5 ,tnt j = 10,int ElpvaLuet

    rnain ( )(Expvalue = i

    E.pvalue = i

    E:.9va].ue = iE Dvalue = i

    E.DvaIue = (i

    E:.pvalue = (i

    E .DVaIuE:.DVaIu

    E.Dvalu = t l l 0t

    E B ReturnTrue ifthe first value is greater than the second.A > = B Return True if the first value is equal to or greater than

    the second.A < B RetumTrue ifthe fi$t value is less than the second.A

  • which is equivalent to:

    i r ( j > 4 )i = 0x123{ t

    els

    The advantage of this type of programming trick isits apparent elegance. Although the single line lookslike it is much simpler than the full iflelse solution, youmight find that it uses a greater number of program-ming statements and file registers and that it takeslonger to execute due to the need to include the multi-ply routine. Additionally, the lack of gotos or diver-sions to different statements could result in astatement that has a constant execution time, whichcan be a significant advantage in some applications.And although it may not necessarily be more efficient,you should note that its operation is not intuitivelyobvious, and you and others will probably not under-stand what is happening in the statement by simplylooking at it. Statements like this are interestingcuriosities that should be avoided unless there is a tan-gible reason requiring their use.

    The pitfall that you can run into with C logic opera-tors is with the eq&ak to (==) statement.The doubleequals sign is a good solution to the problem of differ-entiating between the assignment equals and the com-parison equals, but it does not take into account theconditioning of people who work with other languageslike BASIC, in which a single equals sign in an i/or awhile statement rndicates a comparison. It is very easyto forget yourself and put in a single equals sign whentwo are required for a comparison.

    If a single equals sign is used in an expression like

    instead of the requir