67

Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM
Page 2: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Eas'j Debug'n

USING THE FEATURES OF

PICmiero ® PIC16F87x MICROCONTROLLERS

FROM

DAVID BENSON

VERSION 1.0

Page 3: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

NOTICE

The material presented in this book is for the education andamusement of students, hobbyists, technicians and engineers.Every effort has been made to assure the accuracy of this informa­tion and its suitability for this purpose. Square 1 Electronics andthe author assume no responsibility for the suitability of this infor­mation for any application nor do we assume any liability resultingfrom use of this information. No patent liability is assumed foruse of the information contained herein.

All rights reserved. No part of this book shall be reproduced ortransmitted by any means (including photo copying) without writ­ten permission from Square 1 Electronics and the author.

Copyright © 2002 David Benson

TRADEMARKS

PIC is a registered trademark ofMicrochip Technology Inc. in the U.S.A.PICmiero ® is a registered trademark ofMicrochip Technology Inc.:MPLAB is a registered trademark ofMicrochip Technology Inc.PICSTART Plus is a registered trademark of Microchip Technology Inc.PC is a registered trademark of Philips Semiconductors.SPI is a registered trademark of Motorola, Inc.

PUBLISHER

Square 1 ElectronicsP.O. Box 501Kelseyville,CA 95451 U.S.A.

Voice (707)279-8881FAX (707)279-8883EMAIL [email protected]://www.sq-1.com

Page 4: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

SasyDebugnUSING THE FEATURES OF

PICmicro ® PIC16F87x MICROCONTROLLERSFROM

~(QUAlf(1S [!]GETTING STARTED

• PlCmicro PlC16F87x series• F870 - my candidate for the Debug1n experimenter1s

part of choice• F876 - my second choice• F84 vs. F870 for learning purposes• Device programmer vs. bootloader vs. rCD

- Bootloaders- Microchip lCD

• What a debugger can do for you• Debugging methodology

- Single stepping- Breakpoint- Watch window- Debugging

• General information

PIC16F870

• Pins and functions• Package• Ports• Architecture - overview

- Program memory- File registers- Special purpose registers

• Configuration bits• F870 vs. F84

CIRCUITS FOR EXPERIMENTING

• Build your own- Simple test board - 87s board- 87s companion board

1

11

11

234444445

7

778889

101112

15

1518

Page 5: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PROGRAMMING THE F870 USING A DEVICEPROGRAMMER

• First F870 program - To be programmed by adevice programmer

19

19

PORTING YOUR APPLICATION FROM F84 TO F870 - F870 PROGRAMMED 23VIA A DEVICE PROGRAMMER

MICROCHIPICD 25

Description 25

User Board= Target Board 26

Using The Microchip ICD 26

• General considerations 26• First project 28

- First F870 program for use with rCD 28• MPLAB Operations 31

- Setting up the rCD 31- Toolbar 34- To run a program in real time via the toolbar 35- To reset the F870 via the tool bar 35- Watch window 35- Single stepping 39- Break point 40

Break on address match 40Clear breakpoint 40Break on user halt 41

- Powering down 41- Operating the 87s board stand alone after debug'n 41- Reconnecting the rCD After 87s board stand alone 41

operation- Firing up MPLAB and opening an existing project 41

• Conclusion 41

PORTING YOUR APPLICATION FROM F84 TO F870 - F870 PROGRAMMED 43VIA ICD

USINGTHE ICD" AS A MINI IN-CIRCUIT DEBUGGER FOR F84, F628 ETC. 44

CBLOCK ASSEMBLER DIRECTIVE 47

PIC16F87x 1a-BIT AID 49

• ADCON1• ADCONO• AID conversion procedure• Example

50515252

Page 6: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PORTING PIC'n TECHNIQUES C63 APPLICATIONS TO F870

• Using a device programmer- Port B as is

• Using Microchip rCD- Port B conflict- Split LED display- Keypad connections- Programming considerations

PIC16F877

• Disable AID on port E• Connect both power and both ground pins

Appendix A • Sources

Appendix B • Program Listings vs. Page Number

57

57575757596263

64

6464

65

66

Page 7: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

GETTING STARTED

PICmicro PIC16F87x SERIES

The PIC16F87x seriesincludessome new features, most notably the abilityto read from andwrite to program memory duringprogram execution whichmakesbootloaders and in-circuitdebugging possible. Otherfeatures included in the parts implement in-circuit debugging capa­bility supported by Microchip's in-circuitdebugger (ICD). Twoother significant newfeaturesare 10-bitAIDand the master synchronous serial peripheral (MSSP) which are also being incor­porated in non-16F87x devices(ie. are not 16F87x specific). The 10-bitAID is described in thisbook. The master synchronous serial peripheral (MSSP) is coveredin Serial PIC'n version 2.0.

F870 - MY CANDIDATE FOR THE DEBUG'n EXPERIMENTER'S PART OF CHOICE

The F870 has the following features which make it an excellent choicefor education and experi­mentation:

• Has most of the features which have made the F84 so popular.- Has amplefeatures to providea good basis for educational purposes.- Has flash program memory (a UV eraser is not required).- Is inexpensive.- Is readilyavailable.- Can be programmed using a variety of deviceprogrammers.

Many are inexpensive.• Has the following additional features.

- Cost is currently about $5 for single quantity ($1 less than the F84!).- AID on board (IO-bit).- Two8-bit timer/counters and one 16-bittimer/counter plus capture,

compare, pulsewidth modulation (CCP)module.- USART for serial communications.- Can write to or read from program memory duringprogram execution

(makesbootloaders and debugger possible, a BIG dealI).• 2 K program memory (no program memory pagingrequired - important for beginners).• 28 pins (mid-size).

F876 - MY SECOND CHOICE

The F876 is very similarto the F870. It has more program memory (program memory pagingrequired), 12C and SPI serial communications capability in hardware, and costsmore. You mayuse it if you wish.

16F84 vs.16F870 FOR LEARNING PURPOSES

Here is how the trade-off works out. The 16F870 has 10 more pins than a 16F84 plus AIDwhich adds complexity. The 16F870 can be used with an ICD which provides invaluable debug­ging capability. The abilityto debugfar outweighs the added devicecomplexity. I havedesignedthe examples in the book to minimize and/oravoidthe impactof devicecomplexity asyou get startedwith the learningprocess.

1

Page 8: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Ifyou are working your way through our PIC'n books and want the advantage of debuggingcapability, you can make simple changes at the beginning of the F84 programs and simplyuse the 16F870. How to do this is explained in the two brief chapters on porting your applica­tion from F84 to F870. The details are somewhat dependent on how the program is put into thePICmicro, hence two chapters.

The F84 is still a VERY useful part and is first choice for many applications, so you will want tolearn about it too. The current version of the part is the PIC 16F84A. I will simply refer to it asthe F84 in this book. F84 applications can be developed using the F870 and ICD to take advan­tage of the debugging capabilities and then ported to the F84. Details are provided in a chapteron the subject.

In the case of the 16C71 AID program in PIC'nUp The Pace, life is a bit more complicated asthe 16C71 is being discontinued. You may substitute a PICI6C711 as described on our web siteor move up to the 10-bit AID built into the F870 and the other F87x parts. Using the 10-bit AIDis explained in the chapter entitled "PIC16F870 10-bit AID".

The PICI6C63 examples used in PIC'nTec~ will work on the F870 and any otherPICmicro with the appropriate timer/counter penpherals on-chip. See the chapter entitled"Porting PIC'n Teebnlques C63 Applications To The F870" for an explanation.

SerIal PIC'n is an advanced level book. The examples may be easily ported to any PICmicrowith the appropriate peripherals on-chip.

DEVICE PROGRAMMER vs. BOOTLOADER vs. ICD

There are three ways to get code into an F87x device and run it.

• Device programmer• Bootloader• Microchip in-circuit debugger (lCD)

You already know about device programmers, so let's look at the two new methods made possi­ble by the design of the F87x parts. Each approach uses different F87x resources (port lines,memory, etc.) which means you can't use them in your application. The details and how to workwith them will be discussed as we go along.

Bootloaders

A bootIoader is a small chunk of code which is programmed into an out-of-the-way corner ofprogram memory using a device programmer. You can buy a device with the bootloader codepreprogrammed in it, or you might program the bootloader code into a device yourself: Thebootloader code is used to bring more code (your program) into the device and store it in thedesired location(s) in program memory so it can be executed. If your code does not work thefirst time (never happens!), revised code can be loaded and run. Using a bootloader, you can sitin front ofyour PC and write, run, modify, run, etc. your new application with ease.

There are free bootloaders on the internet, but I recommend melabs Loader frommicroEngineering Labs because it is commercially available and is supported. melabs Loaderconsists of software to run on a PC (on diskette) and bootloader code for the F87x as a .hex fileon diskette as well as preprogrammed into either a 28-pin F876 or 40-pin F877 device (yourchoice). The diskette and preprogrammed PICmicro are relatively inexpensive (around $40).See Appendix A - Sources.2

Page 9: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

melabs Loader requires an RS-232 interface which you can easily build yourself(see Ple'n Technlquu) and uses port lines RC7 and RC6 plus the on-board USARTin the F87x.

PC

melabsLoadersoftware

Microchip ICD

RC7r+-----.R5-232

Ir-------I Interface I--_~RC6 '-------\0'

Serialport

melabs Loader loadsusercodeinto F87xprogram memory

melabs Loaderbootloadercodeat top of programmemory - put thereusing adeviceprogrammer

The PC software which is used to control the ICD is included in MPLAB, so chances are youalready have it. If not, MPLAB is available for download at no cost from Microchip's web site(see Appendix A - Sources). It also comes with the ICD.

The ICD hardware consists of a board which is connected to the PC via a serial cable and toyour board (target) via 5 wires. The port lines used are RB7 and RB6. MCLR is used by theICD. The other two wires are power and ground. The ICD gets its power from your board.

You can sit in front of your PC and write, run, modify, run, etc. your new application with ease.In the off chance that your code doesn't behave properly the first time, debugging capability isright at hand.

PC

MPLABsoftware

Serial port

ICD.....---IRe7""'---1 Re6 F87x.....---IMCLR

MPLAB and ICDprogram usercodeinto F87xprogram memory

The ICD acts as a device programmer and will program blank F87x PICmicro devices, so aslong as you stick with the F87x series, the ICD and MPLAB serve as a complete developmentsystem.

3

Page 10: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

WHAT A DEBUGGER CAN DO FOR YOU

A debuggerallowsyou to run a program:

• In a your system (called the "target") exercising your hardware.• In real time.• Using timer/counter(s).• Using software timing routines.

and. stop program execution anywhere followed by:

• Examiningthe contentsof any register.

This provides a windowfor viewingwhat is going on insidethe microcontroller. Anyonewhohas fired up a new system and code to find NOTHING happening will immediately recognizethe value of a debugger.

DEBUGGING METHODOLOGY

Single Stepping

UsingMPLAB togetherwith the ICD allowsexecuting code one step at a time as the nameimplies. You will be able to observe the contents of selected registers and the operation of yourhardware as each program step is executed.

Breakpoint

A breakpoint is a place ofyour choosing where code execution is haltedfor the purposeofexamining the contentsof selected registers plus lookingat the state of the hardware at thatpoint. This is part of a trouble-shooting procedure. Thinkof code execution as a motionpicture(movie)and what you can see at the breakpoint as one frame of the motionpicture(snapshot).

Watch Window

MPLAB provides for creatinga watchwindowon the PC screenwhich displays the contents ofregisters you select as you single step through your code or when code execution is haltedat abreakpoint.

Debugging

The primarygoal is to write error-free code so debugging is not necessary.

Your brain is your most importantdebugging toolI Use it to look carefully through your non­workingcode before turningto the ICD.

The debuggerallows code execution eithera step at a time or by running to a breakpoint. Eitherway, the state of two things needs to be compared with your expectations, the hardware and theregistercontents. If there is a difference, a potential sourceof error (bug) is identified. Thenyou must think aboutwhy the difference occurred and fix the problem.

4

Page 11: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Note that the ICDIf\.1PLAB combination does not flash a message on the screen identifying abug. You must recognize it by noting there is a difference between anticipated results and actualresults.

I like to select a point in the code which corresponds (hopefully) to an easily recognizable hard­ware result, set a breakpoint there, and look at the hardware and the watch window register con­tents when program execution is halted there.

Another method for isolating bugs is the.divide and conquer approach. Set the first breakpointabout halfway through the code. This will tell you if the error (assuming only one error) is inthe first or second half of the program. Then divide the troublesome half in two and do the samething. This process may be repeated, but at some point, it will make more sense to select thebreakpoint carefully by looking at the code to see what location makes sense.

GENERAL INFORMATION

See our web site at http://www.sq-l.com for updates, for errata, and for downloading the codein this book at no cost.

5

Page 12: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PIC16F870

It is assumedthat the reader is either

• Familiarwith the F84 by workingthrough the examples in Easy PICln andPICln Up 'n1a Pace or someotherexperience.

or

• Beginningthe learningprocessusing these books and prefersto use the 16F870 anda debugger.

You may wish to obtain the Microchip Data Sheetfor the PIC16F870 as it contains a lot of detailinformation you may need as your applications get more sophisticated. The basics are presentedhere so you can get started.

PINS AND FUNCTIONS

~/Vpp 1RAO/ANO 2RA1/AN1 3

RA2/AN2IVref- 4RA3/ AN3/Vref+ 5

RA4/TOCKI 6RA5/AN4 7

Vss 8OSC1/CLKIN 9

osc2ICLKOUT 10RCO/T10so/T1CKI 11

RC1/T10SI 12Rc2ICCP1 13

RC3 14

Both ground (Vss) pins must be connected!

PACKAGE

28 RB7/PGD27 RB6/PGC26 RBS25 RB424 RB3/PGM23 RB222 RB121 RBO/INT20 vdd19 Vss18 RC7IRX/DT17 RC6/TX/CK16 RC515 RC4

The PIC16F870 is availablein a 28-pinskinnyDIP (0.3 inch wide) packagesuitablefor theexperimenter. The part numberis PIC16F870-I/SP. The clock oscillatorfrequency range is DCt020:MHz.

7

Page 13: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Program Memory

PORTS

Port A has 6 lines. All 6 lines may be used as general purpose digital I/O. Port lines RA5, 3,2,1 and 0 may be used in conjunction with the AID converter module. Port line RA4 is sharedwith the external timer/counter input called TOCKI. As a digital input line, the input is a Schmitttrigger. As a digital output line, it is open drain, so a pullup resistor is required. The output can­not source current, it can only sink current.

Port B has 8 digital I/O lines like port B on the F84. Port line RBO may be used as the INT lineto detect external interrupts. Port line RB3 is sometimes used for low voltage programming(LVP)(not discussed in this book). Port lines RB7 and RB6 are used in the in-circuit debuggingmode to communicate with the ICD.

Port C also has 8 lines which can be used as general purpose digital I/O. Port lines RCO, 1 and 2may be used in conjunction with the 16-bit timer/counter TMRI. Port lines RC7 and RC6 maybe used in conjunction with the on-chip USART for serial communications.

ARCHITECTURE • OVERVIEW

Program Memory

The PIC16F870 program memory is 14 bits wide and 2K words long. Program memory is flashand, unlike the F84, may be read from or written to during program execution. .

Pointedto by~resetvedor

OxOOOO0001 1---------1

Polntadtoby ~0002Interruptvader 0003

0004 J.-.-------t1---------1

Ox07FF L...- --'

Since the F870 has only one page (2K words) of program memory, paging is not an issue.

8

Page 14: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

File Registers

The file registers are 8 bits wide with the exception of the PCLATH register which is 5 bitswide. The file registers are divided into four banks. A simplified file register map which showsthe most commonly used file registers follows.

OxOO010203040506070809OAOBOC00OEOF101112131415161718191A1B1C101E1F20

Ox1F

BankOIndirect addressTMROPCLStatusFile selectPort APort BPort C

PCLATHINTCONPIR1PIR2TMR1LTMR1HT1CONTMR2T2CON

CCPR1LCCPR1HCCP1CONRCSTATXREGRCREG

ADRESHADCONO

GeneralPurposeRegisters96 Bytes

Ox808182838485868788898A8B8c808E8F909192939495969198999A9B9C909E9FAD

BFCO

OxFF

Bank 1Indirect addressOption register

File selectTRISATRISBTRISC

PIE1PIE2PCON

PR2

TXSTASPBRG

ADRESLADCON1GeneralPurposeRegisters32 Bytes

Ox100101102103104105106107108109lOAlOB10C10010E10F110

Ox17F

Bank 2

EEOATAEEADREEDATHEEADRH

Ox18018118218318418518618718818918A18B18C18018E

Ox1FF

Bank 3

EECON1EECON2

9

Page 15: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Special Purpose Registers· Overview Of Selected Registers

Status Register

The F870 Status Register is just like the one in the F84.

Option Register

The F870 Option Register is just like the one in the F84.

Program Counter

The F870 Program Counter is just like the one in the F84.

Control

Category NameHex

Address Function

Interrupt control

Timer counter control

Serial Communications

AID control

Memory control

Power control

PIR1 OCPIR2 ODPIE1 8ePIE2 8DTMR1L OETMR1H OFT1CON 10TMR2 11T2CON 12PR2 92CCPR1L 15CCPR1H 16CCP1CON 17RCSTA 18TXSTA 98TXREG 19RCREG 1ASPBRG 99ADRESH 1EADRESL 9EADCONO 1FADCON1 9FEEDATA 10CEEADR 100EECON1 18CEECON2 180

EEDATH 10EEEADRH 10FPCON 8E

Peripheral interrupt flag bitsData EEPROM write interrupt flagPeripheral interrupt enable bitsEnable data EEPROM write interruptTimer 1 register lowTimer 1 register highTimer 1 controlTimer 2 registerTimer 2 controlTimer 2 period registerCCP1 register lowCCP1 register highCCP1 module controlReceive status and controlTransmit status and controlTransmit registerReceive registerBaud rate generator registerAID result highAID result lowAID converter control 0AID converter control 1Data for read or writeAddressControl register for memory accessesUsed in memory write sequence -

not a physical registerData for read or write high *Address high *Reset differentiation flags

* Used for program memory operations

10

Page 16: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

CONFIGURATION BITS

The configuration bits and what they control are shown in the following diagram:

~ DeBUG~ BODeN~ PWRTE~ FOSC1 I FOSCO I13 0

Bits 13,12 &bits 5,4

Bit 11

Bit 10

Bit 9

Bit 8

Bit 7

Bit 6

Bit 3

Bit 2

Bit 1,0

CP<1:0>: Flash memory code protection bits (2)11 Code protection off10 Not supported01 Not supported00 Code protection on

DEBUG: In-circuit debugger mode select bit1 In-circuit debugger mode disabled, RB7 and RB6 are

digital I/O pinso In-circuit debugger mode enabled, RB7 and RB6 are

dedicated to the ICD

UNIMPLEMENTED: Read as "1"

HaT: Flash program memory write enable1 Unprotected - program memory may be written to by

EECON controlo Protected - program memory may not be written to by

EECON control

CPD: Data EE memory protect1 Protection offo = Protection on

LVP: Low voltage in-circuit serial programming enable bit1 Enabled - RB3 is programming pino = Disabled - RB3 is digital I/O pin

BODEN: Brown-out reset enable bit (1)1 Enabledo = Disabled

PHaTE: Power-up timer enable bit (1)1 Disabledo = Enabled

WDTE: Watchdog timer enable bit1 Enabledo = Disabled

FOSC1:FOSCO: Oscillator selection bits11 RC oscillator10 HS oscillator01 XT oscillator00 LP oscillator

Notes 1) Enabling brown-out reset automatically enables power-up timerregardless of value of bit PWRT. Ensure that power-uptimer is enabled anytime the brown-out reset is enabled.

2) Both of the CP bit pairs must be the same to enable programmemory code protection.

11

Page 17: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

F870 vs, F84

For the time being, we will ignore a lot of features and complexity found in the F870 to makeIife/leaming manageable.

The F870 has the following significant differences with respect to the F84:

• Port A- Bits 0, 1, 2, 3, and 5 may be used for AID applications or as digital VO.- Bit 4 is same as F84.

• Port B bit 3 may be used to tell the F870 whether the low voltage programming modeis enabled or not at reset.

• Port C present on F870.• File register map changes indicated in table below.• Low voltage programming in-circuit serial programming (LVP) option.

- Bit 7 in configuration word is LVP bit.l = program modeo= RB3 is digital I/O

• Configuration word has more options for F870.

Overview of selected file registers:

FileAddress

Ox07Ox08OxOEoxoe -

OxlFOx87OxIoeOxlOD

F84

UnimplementedEE DataEE AddressGeneral Purpose

File RegistersUnimplementedUnimplementedUnimplemented

F870

Port eUnimplementedUnimplementedSpecial Purpose

File RegistersTRISeEE DataEE Address

The PICSTART Plus and ICD do not use the low voltage programming (LVP) mode. It isimportant to keep it disabled when using the ICD and/or the examples in this book.

12

Page 18: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Configuration WordComparison

13

F84

Program memorycodeproted

o

Programmemorycode protect

13 0

F870~ DEBUG~ BODEN~ PWRTE~ FOSC1 I FOSCO I

Y 1 l L ~SCselectProgram memory Watch dog

code protect Power-uptimer enable

Program memorycodeproted

Brown-out reset

low voltage in-circultprogramming

Data EE memoryprotect

Program memorywrite enable

Unimplemented

ICDmede

These bits can only be accessed during normal programming (not LVP).

For low voltage in-circuit serial programming:

• Bit 7 in configuration word must be set to enable low voltage in-circuit serialprogramming.

• Use a pull-up resistoron RB3 to enable low voltage in-circuit serial programmingon reset.

The configuration bit takes precedence (ie. the pull-upalone will not enable low voltagein-circuit serial programming on reset).

When low voltage in-circuit serial programming is not wanted:

• Low voltage programming enabledin the configuration register(bit 7) is the default,so it must be clearedin the processof programming the F870.

• Ignoring the step above and leavingthe RB3 pin floating or pullingit up to +5V willcause the F870 to come up in the low voltageprogramming modeon reset (troublel),

13

Page 19: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

CIRCUITS FOR EXPERIMENTING

BUILD YOUR OWN SIMPLE TEST BOARD • 87s BOARD

The 87s board is designed to hold the 28-pinF87x parts, particularly the F870. It includes a zeroinsertion force (ZIF) socket, clockoscillator, resetcircuitand means for connecting to externalcircuitry. A modularphonejack provides a simplemeans of connecting to the ICD via a 6-con­ductorphonecable. A 47 K pull-up resistor is used on MCLR(reset)per Microchip's ICD datasheet.

+SV

RB7 RB6 AB5 RB4 RB3 RB2 RBl ABO Vdd Vss RC7 RC6 ReS RC4

+SV Gnd

O.ltd 10J,Lf

4.0MHzClockOsc

N.C.

+5V

PIC16F870

Drn:'ANppVddGndRB7RB6N.C.

47K

ModularJack­see Detall Drawing

+SV -

15

Page 20: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

I used female headers for external connections (except power and ground) via wires poked intothem. You may prefer terminal blocks or some other method.

The photo shows a double row female header and the drawing shows two single row femaleheaders. After some experience, I recomm end two single row female headers spaced appropri ­ately for enhanced finger clearance. FCI is one manufacturer and calls them BERGCON ®System PC board mount vertica l card connectors . They are available from Mouser Electronics.The I x 14 size is used on the 87s board and the other two sizes are used on the 87s companionboard described in the next section.

pos itions

1 x 81 x 1 41 x 18

Mous er Sto c k Number

64 8-66951-008648- 6 69 51-0 1464 8- 66 951 -0 18

A modular phone jack is used to connect to the ICD via cable. A printed circuit board style jackis shown . One manufacturer is tyco Electronics AMP. The part number is 5204703.The Digi-Key part number is A9049-ND.

16

Page 21: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The modular phonejack is connected as shown:

.400

.400

.125 OlaThru2 PlacesComponentLead Size Thru6 Places

TopView

ModularJack6-Conductor

tyco Electronics I AMP

Mfgr. PIN 520470-3Digi-Key PIN A9049-ND

gcm,VppVdd GooRB7N.C.AS6

Note: Microchip's drawings showpin 1 of the modular connector on the ICD connected to portB, bit 3 on the targetF87xPICmicro. Thisis not necessary as it is NOT used.

The 87s boardwill run withoutbeing connected to the ICD. Remember to pullup RB7 andRB7ifnot in use.

The 87s companion board(described in the next section) or a solderless breadboard may be usedalongside the 87s boardto provide pullup resistors, LEOs, etc. for experimenting. In eithercase,connection is via wires stripped at both ends.

17

Page 22: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

875 Companion Board

The 87s companion board providescommonly used components forexperiments. The assortmentincludes both SPST toggle (4) andSPST momentary push-button (4)switches, 8 LEOs with current limit­ing resistors, aSK ohm 15 tum pot(for AID experimen ts) and pullupresistors. This is an examp le ofwhat can be done for convenience insetting up experiments. You mayhave an idea for an assortmentwhich will better suit you specificneeds.

As you will see in the accompanyingphoto, I used an LEO bar graphinstead of 8 separate LEOs. SIPresistor packages containing 9 resis­tors (bussed) make the board smallerand the wiring easier.

18

+5V Goo

0 0

0.1 II' ' 0 II'

=~ =~

- -. ~n0 •

•0 •0 •

"y

0 • -~• I

0 •n •

0 •y~

0 • 'r•..!.. ••

.~

o M- oI- Iof--+- 0

of-+- 0~

'rof--+- 0

of--+- 0

of--+- 0@-

Iof--+- 0

of-+- 0 J>-of--+- 0 1--

0 0

0~ 0 Jr-4-

0

4-0

~0

~0

0 0

04-

0

4- l0 0

~ y

0 0 5Kn lS Tum,

4- 0.7 5 Wall0 0

~4- L- All Pull~s 10 xn

Page 23: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PROGRAMMING THE F870USING A DEVICE PROGRAMMER

It is assumed that you have your favorite PICmicro device programmer available and know howto use it.

FIRST F870 PROGRAM • TO BE PROGRAMMED VIA A DEVICE PROGRAMMER

We will modify the first example program in Sasy Plein designated pictl.asm. This programsimply writes a bit pattern to the eight port B pins which are connected to 8 LEOs.

i=======PICT1.ASM===========================10/14/97==list p=16f84radix hex

i-----------------------------------------------------i cpu equates (memory map)porth equ Ox06i-----------------------------------------------------

org OxOOO

start movlw OxOO iload W with OxOOtris portb iCopy W tristate, port B

outputsmovlw OxOf iload W with OxOFmovwf porth iload port B with contents

of Wcircle goto circle idone

end;-----------------------------------------------------iat blast time, select:

memory unprotectedi watchdog timer disabled (default is enabled)

standard crystal (using 4 MHz osc for test)power-up timer on

19

Page 24: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

6800

+5V

Reset

RB7 RB6 RB5 RB4 RB3 AB2 RB1 ABO Vdd Vss RC7 RCS ReS AC4

PIC16F870

+5V MCrn TOCKI CLKI CLKO CCP1Vpp RAO RA1 RA2 RA3 RA4 RA5 Vss OSC1 OSC2 RCO RC1 RC2 RC3

'-----tIt----4II....---4_-..--._ +5V +5V.-..._-+--.----.I

+5V

20

4.0MHzCIockOsc

N.C.

All PulJup Resistors 10K

Page 25: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

With the F870 (or F876), we can ignore a lot of the fancies, but we cannot ignore the AID andmust tum them off if they are not to be used. In order to do that, we must use file register bankswitching in order to reach the AID control register ADCONt which resides in bank t. To dothis, we will need to add the address of the ADCONt register to the equates. Since we have touse bank switching to write to the ADCONt register, we might as well add equates for theTRISA, TRISB and TRISC registers and write to them instead of using the TRIS instruction.

The _CONFIG assembler directive is included in the program listing to select:

• Oscillator type XT.• Watchdog timer off/disabled.• Power-up timer on/enabled.• Code protection off (controlled by two 2-bit pairs).• Brown out detect on/enabled.• LVP disabled (must).• Data EE memory protection off.• Program memory unprotected - memory written to by EECON.• ICD mode disabled.

3 F

~~13 12 11 10 9 8

7

~765 4

1

~3 2 1 0

o 0 0 1 1 1 000 1

II l L 'COscXTWatchdog disabled

Power-up timerenabledProgram memory codeprotection off

Brown-out resetenabledLVPdisabled - RB3digitalVO

DataEEmemory protection 011Program memory uJ1)rotected -memory writtento by EECON control

UnimplementedICDdisabled

Program memorycodeprotection off

The configuration word is h13F7t l•

21

Page 26: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Followingis the code examplemodified for the F870:

i==c====PGMR1.ASM==========================12/20/01==list p=16f870__config h'3f71'radix hex

i----------------------------------------------------

statusportaportbportctrisatrisbtriscadconl

cpuequequequequequequequequ

equates (memory map)Ox03OxOSOx06Ox07Ox8SOx86Ox87Ox9f

;----------------------------------------------------bit equates

rpO equ Si----------------------------------------------------

orgstart bsf

movlwmovwfmovlwmovwfmovwfmovwfbcfmovlwmovwf

circle goto

end

OxOOOstatus,rpOb'OOOOOllO'adconlb'OOOOOOOO'trisatrisbtriscstatus,rpOOxOfportbcircle

iswitch to bank 1iturn off A/D, port A

iinputs/outputs

iback to bank 0;load w with bit pattern;load port B with contents of Widone

;-----------------------------------------------------iat device programming time, select:

memory unprotectedwatchdog timer disabled (default is enabled)standard crystal (using 4 MHz osc for test) XTpower-up timer onbrown-out reset enabledlvp disableddebug mode disabled

;=====================================================

22

Page 27: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PORTING YOUR APPLICATION FROM F84 TO F870 ­F870 PROGRAMMED VIA A

DEVICE PROGRAMMER

For portingF84 applications to the F870 where the F870will be programmed directly by adevice programmer, the following must be done:

• Move start of generalpurposefile registers from OxOC to Ox20• Configuration bits:

- LVP disabled, RB3 is digital I/O- DEBUGdisabled (ICD mode disabled).

• AIDdoes not exist on the F84, so ADCONI must be writtento duringinitialization todisableAID on pins RAO, 1,2,3, and 5. Writing Ox06 tothe ADCONI registerat addressOx9F (bank 1)will do the trick.

• Can use port B.

23

Page 28: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

MICROCHIP ICD

DESCRIPTION

The Microchip in-circuit debugger (lCD) consists of software which runs on a PC (included inMPLAB) and hardware which comes in two forms (at this writing) . The simplest version con­sists of one board with a DB-9 connector for serial communication with a host PC and a 6-con­ductor modular phone jack for communication with a PIC 16F87x PICmicro microcontroller.The PICmicro resides in a so-called "target" board which is the user's (your) board . The ICDderives its power from the target board . The ICD board is referred to in the Microchip literatureas the "MPLAB In-circuit Debugger Module". It is sometimes packaged and sold separately asthe "MPLAB ICD Simple Suite".

The more complex version sold by Microchip includes a header, a demo board and an F877(40-pin part). I suggest that you buy the debugger module by itself(but with cables) and startout using a 28-pin F870 . If you have already purchased all three boards, put the other two inyour closet for now. The idea here is to start out with the minimum amount off stuff to deal withwhile getting started . Life is much easier that way.

With the lCD, you can step through assembly source code on-screen while observing what thehardware is (or is not) doing . You can select registers to watch (view) by their labels (names) asyou step through the program . You can set a breakpoint (place to stop program execution) andrun the program at normal speed plus exercise the hardware up to that breakpoint. Then you canlook at the contents of the registers of your choosing.

25

Page 29: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The ICD also serves as a device programmer for F87x devices (only).

USER BOARD = TARGET BOARD

The 87s board describ ed earlier is set up to be used with the ICD. You can easily set up yourown board in a similar way by providing the modular phone jack and using the 47 K pull-upresistor on MCLR (reset)

lCD, 87s Board, and 87s Companion Board

USING THE MICROCHIP ICD

General Considerations

When Microchip's ICD is employed, the following F87x resources are utilized by the ICD:

• Port B bits 6 and 7 are used for ICD serial communication with the F87x.• Lose 1 level of stack when ICD is used.• Address OxOOOO in program memory must contain NOP instructi on.• Memory:

Proces sor File Registers Us ed Program Memor y Us e d

F870 Ox70 , Oxo s s - OxOSF Ox 06E O - Ox 07 FFF8 7 6, F877 Ox70, Oxl ES - OxlEF Ox l FOO - Oxl FFF

For porting F84 applications to the F87x where the F87x will be programmed by the lCD, thefollowing must be done:

• Move start of general purpose file registers from OxOC to Ox20• Configuration bits:

- LVP disabled, RB3 is digital I/O- DEBUG enabled (lCD mode enabled).

26

Page 30: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

• AID does not exist on the F84, so ADCONI must be written to during initialization todisable AID on pins RAO, 1,2,3, and 5 (28-pin device) as well as REO, 1 and 2(40 pin device). Writing Ox06to the ADCONI register at address Ox9F

(bank 1)will do the trick.• Cannot use port B bits 6 and 7 (used by ICD).• Lose 1 level of stack when ICD is used.• Address OxOOOO in program memory must contain NOP instruction.• File register Ox70 must not be used.

27

Page 31: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

First Project

For our first ICD project, we will again modify pictl.asm from Easy PIC-n. It will be necessaryto tum off the AID converters on port A and move the 8 LEOs to port C as only 6 lines are avail­able to us on port B. !fyou used the program pgmrl.asm earlier, it can be modified easily forthis experiment.

First F870 Program For Use With The leo

We will modify the first example program in Easy PIC'ndesignated pictl.asm. This programsimply writes a bit pattern to the eight port B pins which are connected to 8 LEOs.

;=======PICT1.ASM===========================10/14/97==list p=16f84radix hex

i-----------------------------------------------------cpu equates (memory map)

portb equ Ox06i-----------------------------------------------------

org OxOOO

start movlw OxOO ;load W with OxOOtris portb iCOpy W tristate, port B

outputsmovlw OxOf iload W with OxOFmovwf portb iload port B with contents

of Wcircle goto circle idonei

endi-----------------------------------------------------iat blast time, select:

memory unprotectedwatchdog timer disabled (default is enabled)standard crystal (using 4 MHz osc for test)

i power-up timer on

Not all of the 8 bits ofport B are available for your use as RB7 and RB6 are used by the ICD.We will use port C instead.

28

Page 32: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

+5V r : .... :t:J-.... "T ...... "T ...... "T "T .... .."T ..... -- --- -- - -'ICDa • ..~ +5V..~ ...~ ...~ ...~ ..~

r.. ~ ...~ .. ~ .. ~ .. ~ .. ~ .. ~ .. ~6800

RS7 RB6 RB5 RB4 RB3 RB2 RBl ABO Vdd Vss RC7 ReG RCS RC4

) PIC16F870

+5V MCi:R TOCKI ClKI CLI<O . CCPlVpp RAO RAl RA2 RA3 RA4 RA5 Vss 0$01 OSC2 RCO RCl RC2 RC3

AU PuUup Resistors 10K

47K"~

a.y

~. 1000

Reset L"!!!!-

1.----..-..---.--+-----4..-._ +SV

+5V

T4.0 MHz

ClockOsc

kN.C. L

1N.C.

-L-

With the F870 or F876, we can ignore a lot of the fancies, but we cannot ignore the AID andmust tum them off if they are not to be used. In order to do that, we must use file register bankswitching in order to reach the AID control register ADCONI which resides in bank 1. To dothis, we will need to add the address of the ADCON1 register to the equates. Since we have touse bank switching to write to the ADCON1 register, we might as well add equates for theTRISA, TRISB and TRISC registers and write to them directly instead ofusing the TRISinstruction.

Type the following example in MPLAB or download it from our web site. Call it icd1.asm.Create a new project icdl.pjt. In the Edit Project dialog box, change the development mode toMPLAB SIM:, PIC 16F870. Do this even though we will be using the ICD and not the simulatoras a way to keep some things from happening until we are ready to deal with them. Assembleicdl.asm to create the .hex file icdl.hex.

Note the following:

• NOP instruction at beginning.• The CONFIG assembler directive is omitted to avoid confusion as the

ICD doesn't use it. The selections are made using a dialog box.• When using the ICD (as opposed to a device programmer), brown-out reset

is disabled and debug mode must be enabled.

29

Page 33: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

i=======ICD1.ASM===========================12/21/01==list p=16f870radix hex

;----------------------------------------------------i

statusportaportbportctrisatrisbtriscadconl

cpu equates (memory map)equ Ox03equ Ox05equ Ox06equ Ox07equ Ox85equ Ox86equ Ox87equ Ox9f

i----------------------------------------------------bit equates

rpO equ 5j----------------------------------------------------

orgnop

start bsfmovlwmovwfmovlwmovwfmovwfmovwfbcfmovlwmovwf

circle gotoi

end

OxOOO

status,rpOb'OOOOOllO'adconlb'OOOOOOOO'trisatrisbtriscstatus,rpOOxOfportccircle

iswitch to bank 1iturn off A/D, port A

iinputs/outputs

iback to bank 0iload w with bit patterniload port C with contents of Widone

;-----------------------------------------------------iat device programming time, select:

memory unprotectedi watchdog timer disabled (default is enabled)

standard crystal (using 4 MHz osc for test) XTi power-up timer oni brown-out reset disabled

lvp disableddebug mode enabled

;=====================================================

Sincebits 7 and 6 of portB are usedby the ICDfor communication withthe hostPC, we are leftwith 6 of the 8 portB linesfor our applications. Whenwriting your application code, it isalrightto use instructions whichwrite to all 8 bits of portBand TRISB. TheMPLAB ICDtakescare of the housekeeping so that ICD communications on bits 7 and 6 are notaffected by theseinstructions.

30

Page 34: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

MPLAB OPERATIONS

Setting Up The ICD

Connect the lCD to your PC per Microchip's instructions. Connect the lCD to your 87s boardusing a short 6·conductor modular phone cable. Connect your 87s board to a suitable 5 volt DCpower supply. Tum on your host PC. Fire-up MPLAB. At this point, it is assumed that youhave a .hex file suitable to be programmed into the F870 on your 87s board. The icd I projectshown above will be used as an example here. Remember to put in the Nap instruction atOxOOO.

Open your project (icdI.pjt in this case).

With the F870 in the ZIF socket, power-up your 87s board. The red LED on the lCD boardshould be blinking indicating that communications have not yet been established between the PCand the lCD .

Project>Edit Project.

The Edit Project dialog box will appear.

Edit Project g'i

F!roiecl==,"",,===:'=====~==~

Target Filen me

licdl .hex

Include Path,-------,--Library Path

1 - -

Linker Script Path

I!... Q« ..JI

Cancel I:

Help

Development Mode: !M PLAB leo PIC16FB70 I Change...

Language Tool Suite: IMicrochip ~I

Project Fi'es:~=======l~~!!!~~~licdl (.hex]icdl [.asm)

31

Page 35: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The development mode selected will be whatever you were using last. Click on the Change but­ton.

The Development Mode dialog box will appear.

Help

Details...

APplyCancelIOK

None (Editor Only) , Processor:IPIC16F870

!V MPLAB SIM Simulator Requires OnChip resources lor~> MPI.AH ICE b nulalm debugging. .

Only one breakpoint may be setPICMASHR f .mulutm ! Click 'Details' lor additional" ' "'f'l''' r. I.t inlormation on PIC16F870." "'_ .... c,mu <\ m

Click on the Tools tab.

Select (click on) MPLAB ICD Debugger.

Select the PIC16F8 70 processo r.

Click on Apply. The MPLAB ICD dialog box will appear.

..El 2MHz-l0MH;.E.l

F!'YI: Vel 2.31.00

Ignore it for the momen t.

Click on OK in the Development Mode dialog box.

32

Page 36: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Close the Edit Project dialog box.

Return to the MPLAB ICD dialog box.

Select the com port you are using for the ICD.

MPLAB will now establish communications with the ICD. Respond to any error messageswhich may appear to complete establish ing communications. The red LED on the ICD boardshould now be on (not blinking) indicating that communication is establish ed between the PCand the ICD board.

Select processor speed 2 MHz to 10 MHz (default).

Click on Options.

The ICD Options dialog box will appear,

: ICD 0 ptions Q ffir r::ip'Coofiguralion Bits

Device: ~. Oscillator: XT .El.: ~

;:;"1Watchdog Timer: Off/Disable

Power Up Timer: On/Enable ElBrown out Detect: Off/Disable r;'

','Low Voltage Program: Disable .El.

Code Protect Data EE: code protection 0 ff piFlash Memory Write: Memory written to by EECON .El

Code Protect: Code Protect ion 0 ff .El,;;lID 's and Checksum ::Program Options .

Checksum:IOx171 B<3F31 > I Start Address: OxOOOO

ID Code: 1171 B I End Address: Ox06DF

E:]Use Checksum as ID P Program MemoryP Configuration Bits

1.,.Voltag es ·r P ID Locations

~ VDD : 15.30 v +/.5%I] iUpdate I r EEPROM DataP Erase All before Program

, VPR: 113.35 v +/.51 E..Enable Debug Mode~.'

1 ' Biiiiin :-:'Reall I[ Program r Verify - Erase ; l~-': AlIifr

~, Downloall ICD-Ojii;'i'ilting System Self Test

33

Page 37: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Make the following selections:

• PIC16F870.• Oscillatortype XT.• Watchdog timer off/disable.• Power-up timer on/enabled.• Brown out detect off/disabled (must).• LVP disabled(must).• Code protection off• Flash memory write - memory writtento by EECON(must).• Code protection off

Be sure the debugmode enablebox under Program optionsis checked.

Note again that the _CONFIG directive is notused by the lCD and is not included in the sourcecode to preventconfusion.

Close the lCD Optionsdialogbox.

Click on Programin the MPLAB lCD dialogbox to program the F870.

Note that each time your code is changed, it is necessary to reprogram the chip as describedabove. A dialogbox will pop up to remindyou.

Stuffhappens. Watch the statusbox. When programming is complete, "Waiting for user com­mand" will appear in the MPLAB lCD dialog box status indicator.

The MPLAB lCD dialogbox staysopen all the time the lCD is in use. It can be minimized.Minimizethe MPLAB lCD dialogbox.

Toolbar

Todebug programsusing :MPLAB lCD, we will use four buttonson the debugtoolbar at the topof the lv.1PLAB window. You can discover the rest by "hacking" as the need or curiosity arises!Selectthe debug toolbar using the "change toolbar" button.

OJ OJ ITIIIJ OJ DReset Processor

StepThroughProgram

Debug Toolbar

34

Page 38: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

To Run A Program In Real Time Via The Toolbar

Click on the run button (green traffic light) on the toolbar.

Hex OxOF should now be displayed at the port C LEDs.

To Reset The F870 Via The Toolbar

Click on the reset processor button on the toolbar.

The first line of code after the NOP instruction will be highlighted .

Watch Window

To create a watch window:

Window>Watch Windows>New Watch Window.

The Add Watch Symbol dialog box appears .

Add Walch Symbol mSymbol:

II

~16F870adconO :c O.~!:J

adconladconl Croseadr eshadresl

Por pJOrtiba Icc plconccprl hccprll p i Helpeeadr

Scroll up and down the menu and select the registers you would like to watch as your programexecutes.

In this case, select W by highlighting w. Click on the Add button .

Select port C by highlighting porte. Click on the Add button .

Notice that porte appears twice in the list. The list is made up from two sources . One is a stan­dard list for the device you are using . The other is the registers identified in the equates in yoursource code.

35

Page 39: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Clos e the Add Watch Symbol dialog box.

The watch window Watch_ I is now on-screen .

I! Watch 1 e~m- -Address20007

Symbo l1'1

porte

Ual ueH ' 00'H' 00'

I find it helpful to have the contents of a port disp layed in binary. Let's customize (edit)Watch I.

Click on the little square button in the upper left hand comer of Watch_I .

A drop -down menu appears. Select Edit Watch.

The Edit Watch Symbol dialog box appears.

Edit Watch Symbol I?:iSymbol:

1'--- _wportc

.,.

Help

Click on porte to highl ight it.

Click on the Properties button.

36

Page 40: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The Properties dialog box appears.,

• •• •

Eormal

Hexadecimal Decimal

:~:a.~~if: ASCII

MChip f' !~liJ( lEEE U~liJ(

Size

a-bil 16-bil 24-bil

32-bil

.!Uole Order

~. Hiotr.blw Low:High

Cancel

bit..3

x bit..l

Help

Under Format, click on Binary to select it.

Click on OK.

Close the Edit Watch Symbol dialog box.

The watch window now looks like this:

:Addr es s

1

2 0007

SymbolI~

por te

UalueH' 00'B'OOOOOOOO '

D IX

37

Page 41: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Note that a watch window can be saved so that it will be there each time a project is opened.

Save the watch window you have just created as icd 1.wat. To do this , click on the little squarebutton in the upper left comer of the watch window.

A drop-down menu appears.

Click on Save Watch.

The Save Watch dialog box appears.

Help

CancelEj d:\~ mplabI3l exampleCJ mplCJ mplebx

eJ template

'Walch 'Window Files ('.1

~~

walch_1 .wat

list Files of Jype:

IBl

Name the watch window icd 1.wat. Click OK.

If you close this watch window and then want to open it later, useWindow>Watch Window>Load Watch Window.

Watch windows are saved as files . To delete a watch window, the file must be deleted.

38

Page 42: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Single Stepping

Reset the processorvia the toolbar icon. Notice that the first line ofyour program (not countingNOP) is highlighted. The processoris stopped at the point where the highlighted line is the oneabout to be executed. Click on the single step button on the toolbar. The next instruction is exe­cuted. Notice that sometime is requiredfor communication betweenthe PC and the F870 tofetch the contentsofthe selectedF870 registers for display. You can single step your waythrough icd1.asmto the instruction labeled "circle", Observethe changesof the contents of theW register and port C in the watch window.

As you single steppedthrough the code the first time, the LEDs were all off untilmovwf porte was executed. Now step through the secondtime. Four of the LEOs willcome on after movwf trise is executed(soonerthan the first trip through). The reasonis that the contentsof the port C register is OxOO after reset and remainsso until some other datais written to it. Writingto the TRISCregisterto make port C outputs results in the contentsofthe port C registerbeing output immediately. On the first trip throughthe code, the contentsisOxOO. On the secondtrip throughthe code, the contentsis OxOF.

Ifyou want to play with this, add the following line of code and move the "start" label.

org OxOOOnop

start elrf porte ;LEDs offbsf status,rpO ;switeh to bank 1etc.

Testfor results.

39

Page 43: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Break Point

Break On Address Match

One breakpoint may be set. The processor breaks after executing the instruction stored at thataddress.

To set a breakpoint on address match:

Reset the F870 using the button on the toolbar.

Highlight (as in typing text) the last line of code you want executed.

Click the right mouse button .

A small dialog box will appear.

Break Point(s)TracePoint(s)Trigger Pointls]

Select Break Point(s).

The line of code selected will now be displayed in red text.

Click the toolbar run button to run to the breakpoint.

The F870 will stop at the address you selected. The next line of code will be highlighted.

If execution does not stop at a breakpoint, do the following:

Options>Development Mode.

Click on Break Options tab .

Make sure Global Break Enable is selected (checkmarked).

Clear Breakpoint

Debug>Clear All Breakpoints.

40

Page 44: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

BreakOn UserHalt

To set a breakpoint on user halt:

• Click on the Halt button on the toolbar as the program is running.or

• Debug>Run>Halt.

Powering Down

The power-down sequence is the reverse of the power-up sequence

• Tum off power to the target board which will power-down the ICD.• Tum off power to the host computer.

Operating 875 Board Stand Alone After Debug'n

During the debugging process, the Enable Debug box in the ICD Options Window has beenchecked. This causes code to be written into the program memory space used by the debuggerwhich tells the F870 to look for the debugger on reset. Operating stand alone, the debugger willnot be found and your program will not be executed. To avoid this, you will need to:

• Uncheck Enable Debug in the ICD Options window.• Reprogram the F870.

Since port lines RB7 and RB6 will not be used by the ICD when the 87s board is operated instand alone mode, you may want to connect them to pullup resistors.

Reconnecting The ICD After 875 Board Stand Alone Operation

To reconnect the ICD to do more debugging or test the hot new feature you now want to add toyour project you will need to:

• Check Enable Debug in the ICD Options window.• Reprogram the F870.

Since port lines RB7 and RB6 will be used by the lCD, remember to remove the pullup resistors(if any).

Firing Up MPLAB And Opening An Existing Project

Open the project. The MPLAB ICD dialog box will appear. The selections will be the ones youmade the last time the project was saved.

Remember to think about the Enable Debug checked vs. unchecked status when you open a pro­Ject.

Proceed with whatever you opened the project to do.

41

Page 45: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

CONCLUSION

You will find that, when using MPLAB, the sequence or selection of dialog boxes that come upand the selections made in them are somewhat dependent on what you did last, perhaps goingback to a project you did last month. Also, Microchip likes to make software changes. Be pre­pared to hack a little!

The Reconnect button in the MPLAB leo dialog box is a feature you will use a lot. The blink­ing LED on the leo debugger board will prompt you.

42

\

Page 46: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PORTING YOUR APPLICATION FROM F84 TO F870 •F870 PROGRAMMED VIA ICD

For portingF84 applications to the F870 wherethe F870will be programmed by the lCD, thefollowing must be done:

• Move start ofgeneral purpose file registers from OxOC to Ox20• Configuration bits:

- LVP disabled, RB3 is digital I/O- DEBUGenabled (ICDmode enabled).

• AIDdoes not exist on the F84, so ADCONI must be writtento duringinitialization todisableAIDon pinsRAO, I, 2, 3, and 5. Writing Ox06 tothe ADCONI registerat address Ox9F (bank 1) will do the trick.

• Cannotuse portB bits 6 and 7 (usedby ICD).• Lose 1 level ofstackwhen ICD is used.• Address OxOOOO in program memory mustcontain NOP instruction.• File registerOx70 must not be used.

43

Page 47: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

USING THE ICD AS AMINI IN-CIRCUIT DEBUGGER

FOR F84, F628, ETC.

The lCD, 87s board, F870, and a simple cable/plug assembly can be used to simulate and debugF84, F628, and other I8-pin part applications. We will use the F84 as the example. The Port AI/O lines of the F870 which correspond to F84 Port A I/O lines are used. Port C of the F870 isused in place of port B on the F84 because the F870 RB7 and RB6lines are used by the ICD.This means that once the application is debugged, the references to "port Cit in the code must bechanged to "port B" as part of converting the code for use on the F84. Note that the weakpullups and other special features associated with port B of the F84 cannot be used/simulatedusing this method. The other rules for porting an F870 application to an F84 apply. There isvery little involved in doing the conversion, but pay attention to the details!

All PUll~ Resistors 10K+5V

JeD -t ~

.~ .~ .~ "~ "~ "I" +Y IRB7 RB6 RB5 RB4 RB3 RB2 RB1 ABO Vdd Vss RC7 ReG ReS RC4

PIC16F870

+5V MCUi lOCKI ClKI CLKO CCP1Vpp RAO RA1 RA2 RA3 RA4 RA5 Vss OSC1 OSC2 ReO 001 RC2 RC3

47K"'~

~

rt 1000

Reset•

+5V+5V

T

LN.C.

4.0 MHzClockOsc

!~N.C.

Onlarget

r r rRA1 RAG OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

CLKI CLKO

) PIC16F84A Plug

lOCKIRA2 RA3 RA4 MCi:R Vss ABO RB1 RB2 RB3

1 1Onlargel

45

Page 48: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The cable/plug assembly wires connect to the appropriate sockets on the 87s board. The plugplugs into your F84 target board F84 socket so that only the I/O is connected. The power,ground, clock oscillator, and MCLR lines are not connected via the cable/plug assembly.

I made a simple plug using :

• A chunk of printed circuit prototyping board (I8-pin DIP's worth) .• Two 9-pin chunks of single row machined pin header.

The single row machined pin header I used is MILL-MAX part number 800-10-064 -10-002000.It has 64 pins and is scored so that pieces of desired length may be broken off. The Digi-Keypart number is ED 7564-ND.

I filed a notch in one end of the printed circuit board for pin 1 identification Gust like an IC).

The larger (0.030 inch dia.) ends of the pins were soldered to the board. The smaller (0.024 inchdia.) ends of the pins were left protruding for insertion into the target F84 board's socket. I gluedthe header segments to the board with small drops of glue. A machined pin IC socket was usedto hold the header segments in alignment while the glue set. The IC socket was removed priorto soldering the header segment pins to the board. After the soldering operatio n was completed,the F84 ends of the 5 unused pins were cut off and filed flush with the plastic portion of theheader segments.

A design improvement would be to make your own PC board for the purpose and bring thewires off one end of the board in a direction parallel to the plane of the board as opposed to per­pendicular to the plane of the board as shown. The trace/wire side of the board could be encap­sulated in casting resin for durability.

46

Page 49: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

CBLOCK ASSEMBLER DIRECTIVE

The CBLOCK assemblerdirective is used to definea block of labels in consecutive general pur­pose file register addresses. For example, insteadof:

temp equ Ox20count equ Ox21save equ Ox22

Do this:

cblock Ox20tempcountsave

endc

The first label "temp" will be assigned address Ox20. The last label II save" will be assignedaddress Ox22. More than one label may appearon a line if the labels are separated by commas.

cblock Ox20temp, count, save

endc

The assemblerdirectiveENDC is used to define the end of the block of labels.

So why am I telling you this in the middle of a debug'n book? If you use the mini debuggerdescribed in the previouschapterand debugcode in an F870 followed by moving it to an F84 asan example, you won't have to retypethe addresses of all the labelsdefinedusing CBLOCK.Merely change the one address following the CBLOCK directive(changeOx20 to OxOC).

47

Page 50: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PIC16F870 10-BIT AID

The PIC16F870 has 5 pinswhichmay(or may not)be used as AID channels. Theseare port A,bits 5,3,2,1,0. The five analoginputsare multiplexed into one sample and holdcircuit. The out­put ofthe sampleand hold is the input to a successive approximation converter. The referencevoltagemaybe the logic supply (5 volt for our example) to the PIC16F870 (range0-5V) or anexternal reference via pins RA2and RAJ. If an external reference is used, only4 AID channelsare available. The intricacies of using an external voltage reference are beyond the scopeof thisbook.

Important electrical specsare:

Vain 0 to 5V if Vref = 5v logic supplyVref 5v logic supply for this exampleMaximum source impedance 10K

The AID conversion resultis a 10-bitdigital number in two registers.

Tworegisters are usedto control the AID converters and two are used to holdthe resultof theconversion.

Register

AID control 0AID control 1AID result highAID result low

ADCONOADCON1ADRESHADRESL

Hex Address

1F9F1E9E

Bank

o1o1

49

Page 51: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

ADCON1

ADCONI controls the port pin functions and the format of the AID result.

~ PCFG3 IPCFG2 IPCFG1 I PCFGO I Ox9F

7 1

Power-on reset 00000000

Bit 7 ADFM: AID result for.mat select bit1 Right justified, 6 most significant bits of ADRESH

read as "0"0 Left justified, 6 least significant bits of ADRESL

read as "0"

Bit 6, 5, 4 ONXMPLEMEN'lED: Read as ..0"

Bit 3,2,1,0 PCFG3:PCFGO: AID port configuration control bitsSee table below

Abbreviated list of configuration control bits:

PCFG3, 2, 1, 0AN4RAS

AN3RA3

AN2RA2

AN1RA1

ANORAO Vref

0000 A A A A A Vdd0100 D A D A A Vdd011x D D D D D

1110 D D D D A Vdd

A analog inputD digital Ilo

See Microchip PIC16F870 Data Book for complete list.

AID result format is controlled by the AIDformat selectbit (ADFM) which is bit 7 in ADCONI.The result may be right or left justified as shownbelow.

7 ADRESH o 7 ADRESL o

Right-justified10 bits

7 ADRESH o 7 ADRESL o

50

Left-justffied10blts

Page 52: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The result can be leftjustified and the lower 2 bits ignoredto give 8-bit resolution. The resultcan be rightjustified and the resultused as a 16-bitnumberin arithmetic operations.

ADCONO

The ADCONO registercontrolsthe AIDmodule.

IADCS1 IADCSO~GO/~~ Ox1F

7 1

Powor-on reset 00000000

Bits 7,6

Bits 5,4,3

Bit 2

Bit 1

Bit 0

ADCS1:ADCSO: AID conversion clock select bits00 = Fosc/201 = Foscla10 = Fosc/3211 = Frc (clock derived from RC oscillator)

CHS2:CHSO: Analog channel select bits000 channel 0 (RAO/ANO)001 channel 1 (RA1/AN1)010 channel 2 (RA2/AN2)011 channel 3 (RA3/AN3)100 channel 4 (RA5/AN4)

GO/DONE: AID conversion status bitIf ADON bit = 1

1 AID conversion in progress (setting thisbit starts the AID conversion)

o AID conversion not in progress (this bitis automatically cleared by hardware whenthe AID conversion is complete)

Unimplemented, read as "0"

ADON: AID on bit1 AID converter module is operatingo = AID module is shut off and consumes no

operating current

51

Page 53: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

AID CONVERSION PROCEDURE

The procedure for performing an AID conversion is:

• Configure analog input pin(s) as input(s).• Configure the port A pins - done once during the setup portion of the main program.• Select right vs. left justification of the AID result.• Set up AID interrupt if used.• Select = enable an AID channel.• Wait for the AID to acquire the data (20 usee for example that follows).• Start the conversion - set go/done bit in ADCONO regilliu".• Use AID conversion complete interrupt or polling go/done bit in ADCONO register

to detect conversion completion.• Read data in AID result registers ADRESH and ADRESL.• Clear AID conversion complete interrupt flag (ADIF, bit 6 in PIRI register) if

using interrupts.• Ifyou want to do another conversion, wait 2Tad (16 usee for our example,

see details below). Tad is the AID conversion time.

How wil!..lY.e know when the conversion process is complete? There are two ways to do this.The go/done bit (bit 2) in the ADCONO register may be polled. It is set to start the conversionprocess and is cleared when the conversion is complete. An alternative is to use interrupts. TheADIF bit which is bit 6 in the PIRI register is the conversion complete interrupt flag. It is set onconversion completion. Note that it must be cleared in software as part of the interrupt serviceroutine. Of course, the interrupt must be enabled prior to starting the conversion if this methodis used. Bit 6 of the PIEI register is the AID interrupt enable (ADIE) flag.

Conversion complete:

• ReslJ!1.ip ADRES registers.• Go/done bit in ADCONO (bit 2) is cleared.• AID interrupt flag bit (ADIF) in PIRI (bit 6) is set.

EXAMPLE

This example shows how to use channel 0 on pin RAO/ANO and display the result via 10 LEDs.

We will make a simplifying assumption about timing by assuming it is not critical to get the AIDconversion done in the shortest time possible. We will use a 4 mHz clock oscillator. The clockfrequency is divided to obtain the clock source for the converter function. The data book talksabout clock period (clock period - Tosc), so it may be better to think of the clock period beingmultiplied rather than clock oscillator frequently being divided. We will use the largest clockperiod multiplier which is 32. Ifyou develop an application where time is of the essence, youwill need to refer to the data book for timing considerations/options/calculations. Our objectivehere is to simplify matters and to get something working.

PIC16F8704 MHz clock, Tosc= 0.25 J.1SecAID clock source = Tad = Toscx32 = 8 useeVref= 5V

52

Page 54: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

- -

+5V rICD Or PulJ'4>S -..." Stand-alone

r r.... ..~ ..~ ..~ +5V

rRB7 RBG RB5 RB4 RB3 RB2 RB1 RBO Vdd Vss RC7 ReG ReS RC4

PIC16F870

+5V MCiJi TOCKI CLKI CLKO CCP1• Vpp RAO RA1 RA2 RA3 RA4 RA5 Vss OSC1 OSC2 RCO RC1 RC2 RC3

+5V,c> 5K, 15 Tum,

---~ 0.75 Watt

+5V

T4.0MHz

ClockOsc

N.C.

kN.C.

All Pullup Resistors 10K

53

Page 55: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

meas

b'00001110'

PortA, Bit 0 Analog Input,Result Left Justified

54

Select ANOSelectConversion

ClockTumOnANO

Display At PortBAnd CLEOs

Delay200 MillisecondsVia Subroutine

b'10000001'

Foscl32. ANO SelectWaitTo StartConversionAID On

Page 56: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

i=c=====ICD3.ASM=============================1/3/02==list p=16f870radix hex

i----------------------------------------------------istatusportaportbportcintconadreshadconOtrisatrisbtriscadresladconlcountncountmcounttemp

cpuequequequequequequequequequequequequequequequequ

equates (memory map)Ox03Ox05Ox06Ox07OxObOxleOxlfOx85Ox86Ox87OxgeOx9fOx20Ox21Ox22Ox23

i----------------------------------------------------i bit equatesrpO equ 5;----------------------------------------------------

start

i

meas

test

orgnopbsfmovlwmovwfmovlwmovwfmovwfmovlwmovwf

bcfclrfbcfbcfbcfmovlwmovwfcallbsfbtfscgotomovf

movwfbsfmovfbcfmovwf

OxOOO

status,rpOb'OOOOOOOl'trisab'OOOOOOOO'trisbtriscb'00001110'adconl

status,rpOportcportb,lportb,Ointcon,7b'lOOOOOOl'adconOdel 20adconO,2adconO,2testadresh,w

portcstatus,rpOadresl,wstatus,rpOtemp

;switch to bank 1; inputs/outputs

iinputs/outputs

iport A, bit 0 analog inputbits 5,3,2,1 digital I/O,result left justified

iswitch back to bank 0iLEDs off

iglobal interrupt disableiconfigure A/D - select ANO; select conv clock, ANO onidelay 20 microsecondsistart conversionitest go/done bit

iconv complete, get A/D resultms 8 bits

idisplay ms 8 data bits via LEDSiswitch to bank 1iqet AID result ls 2 bits;switch to bank 0;store for disection

55

Page 57: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

do 0

wait

btfssgotobsfbtfssgotobsfcallgoto

temp,?clr 1portb,ltemp, 6clr_Oportb,Odebouncemeas

;display via LED

;display via LED;wait a while (200 milliseconds);look at voltage again

i------------------------------------------------------------clr 1

clr 0

bcfgotobcfgoto

portb,ldo 0portb,Owait

;display via LED

;display via LED

i----------------------------------------------------- ------~

del 20 movlwmovwf

repeat decfszgotoreturn

OxO?countcountrepeat

idelay 20 microseconds

i------------------------------------------------------------debounce movlw Oxff ;M

movwf mcount ito M counterloadn movlw Oxff iN

movwf ncount ito N counterdecn decfsz ncount,f idecrement N

goto decn iagaindecfsz mcount,f ; decrement Mgoto loadn ; againreturn idone

;------------------------------------------------------------end

;-----------------------------------------------------iat device programming time, select:

memory unprotectedwatchdog timer disabled (default is enabled)standard crystal (using 4 MHz osc for test) XTpower-up timer onbrown-out reset disabledlvp disableddebug mode enabled

;=====================================================

Tum the pot and observe the port B and C LEDs.

This program has two time delays in it, so ifyou have difficulties, setting a breakpoint instead oftrying to single step your way through will be useful.

For applications where the AID result is to be manipulated mathematically, the result would beright justified and treated as a 16-bit number.

If 8-bit resolution is all that is required for your application, the two LEDs on port B can bedeleted and the code for the example may be easily changed to eliminate the use of the ADRESLregister and the two port B lines.

56

Page 58: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PORTING PIC'n TECHNIQUES C63 APPLICATIONSTO F870

The primary thing that needs to be done is to tum off the AID converters early in the program.

USING A DEVICE PROGRAMMER

When using a device programmer for porting Ple'nTec~ example programs from theC63 to the F870, port B may be used without modifying the circuit or the code. With the excep­tions of the AID and configuration word considerations described here, the C63 examples fromPle'n Techniques may be used without modification.

For porting F63 applications to the F870 where the F870 will be programmed directly by adevice programmer, the following must be done:

• Configuration bits:- LVP disabled, RB3 is digital I/O- DEBUG disabled (lCD mode disabled).

• AID does not exist on the C63, so ADCON1 must be written to during initialization todisable AID on pins RAO, 1,2,3, and 5. Writing Ox06 tothe ADCON1 register at address Ox9F (bank 1) will do the trick.

• Can use port B.

USING THE ICD

Port B bits 7 and 6 are used by the lCD which means some minor changes are necessary. Theeasiest thing to do is swap the upper 4 bits of ports Band C. This effects only those programswhich include the following:

• Displaying data using 8 LEOs which must now be split between the two ports• Scanning the 10-key keypad.

57

Page 59: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The modified schematic is shown below.

6

DIP Socket543 2 o

+5V.--t--el"'-+ -+-...,

KeypadColumnPuD~

+5V

Tesa Note: Port B and Port CLinesPoInI are not shown In their physlcaJ

locations on the device.

r--__ +5V

ICD Or PulIupsIf Stand-alone

47K

RC7 ~6 ~S RC4 RB3 RB2 RB1 ABO Vdd Vss RB7 RB6 RBS RB4

PIC16F870

+5V acm TOCKI CLKI CLKO CCP1Vpp RAG RA1 RA2 RA3 RA4 RA5 Vss OSC1 OSC2 RCO RC1 RC2 RC3

Reset

+5V

Serial OutputTo PICILCD.Input

TMRO Input +5V

TMR1 Input CCP1

58

All Pullup Reslstom 10K4.0 MHz

CIoc:kOsc

F870BOARD

• Cap =22 pf (2 reqd:Xtal =32.768 KHzSockets to allow removal.Partsusedfor extemalclock

experiment only

Page 60: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The C63 programsin PleinT~ are listed in the following table. The programs whichneed to be modified for F870 use in conjunction with the ICD are identified.

PIC'n Techniques C63 ProgramsBy Page Number Modification Required

-----------------------------------------------------tst63.asm 40 Split LED display

tmr2.asm 46 OK as iststtmr2.asm 50 OK as is

tmr1.asm 63 OK as isread.asm 68 Split LED displaycapt.asm 71 Split LED displaycmpr.asm 75 OK as issngl.asm 80 OK as is

one128.asm 82 OK as isfree.asm 85 OK as is

freeadd.asm 89 OK as isperiod.asm 95 Split LED display

pdccp.asm 100 Split LED displayfreq.asm 107 Split LED display

seconds.asm 110 OK as istime.asm 114 Split LED display

hdwpwmx.asm 120 OK as isccppwm.asm 124 OK as is

hdwpwmy.asm 129 OK as isccppwmx.asm 137 OK as is

decent63.asm 144 Change keypad column connectionspulsgen.asm 155 Change keypad column connectionfreqgen.asm 166 Change keypad column connection

pdck.asm 179 OK as isfreqck.asm 192 OK as is

Details on these modifications follow.

Split LED Display

In this situation where a byte-wide port is not available for displaying data or a bit pattern via8 LEOs,we can solvethe problem by splitting the bits between two ports.

PortC Port B

I~I~I765 432 1 0

Bits

59

Page 61: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

i=======ICD2.ASM===========================l2/29/0l==list p=l6f870radix hex

;----------------------------------------------------

statusportaportbportetrisatrisbtriscadconlcrack

cpuequequequequequequequequequ

equates (memory map)Ox03Ox05Ox06Ox07Ox8SOx86Ox87Ox9fOx20 ;save reg for split subroutine

;----------------------------------------------------i bit equatesrpO equ Si----------------------------------------------------

start

orgnopbsfmovlwmovwfmovlwmovwfmovwfmovwfbcfmovlw

OxOOO

status,rpOb'OOOOOllO'adconlb'OOOOOOOO'trisatrisbtriscstatus,rpOOxOf

iswitch to bank 1;turn off A/D, port A

iinputs/outputs

iback to bank 0iload w with bit pattern

;-----------------------------------------------------movwfcall

cracksplit

isave

._----------------------------------------------------,circle goto circle idonej-----------------------------------------------------split btfss crack, 0

goto clr 0bsf portb,O

dO_l btfss crack,lgoto clr 1bsf portb, 1

do_2 btfss crack, 2goto clr 2bsf portb,2

do_3 btfss crack, 3goto clr 3bsf portb,3

do_4 btfss crack, 4goto clr 4bsf porte, 4

do S btfss crack,Sgoto clr Sbsf porte,S

do 6 btfss crack, 6

60

Page 62: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

clr 4

clr S

clr 6

clr 7

gotobsfbtfssgotobsfreturnbcfgotobcfgotobcfgotobcfgotobcfgotobcfgotobcfgotobcfreturn

clr 6portc,6crack,7clr_7portc,7

portb,OdO_lportb,ldo_2portb,2do_3portb,3do 4portc,4do_Sportc,Sdo_6portc,6do_7portc,7

i-----------------------------------------------------end

i-----------------------------------------------------;at device programming time, select:

memory unprotectedwatchdog timer disabled (default is enabled)standard crystal (using 4 MHz osc for test) XTpower-up timer onbrown-out reset disabledlvp disableddebug mode enabled

i=====================================================

For the PIC'n Tecbnl~ programswhich use 8 LEDs on port B (identified in the table asneeding a split LED display), define the register "crack" in the equates and call the subroutineshown in the following demonstration program. In other words, substitute the guts of the demoprogram for movwf portb in the PIC'n Techniques program.

61

Page 63: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

Keypad Connections

A keypad is used in three projectsin the chapteron Designing AndbuildingYour Own TestEquipment.

F870BOARD PICILCD

RA1... RAO..

TO AD

I III LCD

PortB PortC J./ ~ .",.

,/3

KEYPAD BOARD

- +5VDC

...~.~ ~~

1000

O~ 1 2 3

1 _ --A ...4 5 6-V" .....

Port B2 - --A ...

7 8 9- -V" ..3- --A ... • 0 #.. •V" ......

4 ""'".....

PortC 5 ""'".....

6 ""'".....

Use Pullup ResistorsOn F870 Board

The lines connected to port B bits 4, 5, and 6 are movedto port C bits 4, 5 and 6 (see, also,schematic shown previously). The keypad code modifications are straightforward. The pro­grams effected are:

62

• decent63.asm• pulsgen.asm• freqgen.asm

page 144page 155page 166

Page 64: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

The code changeswhich followapplyto all three programs.

Add porte equ Ox07

Replace movlw b'011100000'movwf trisb

With movwf trisbmovlw b'011100000'movwf trise

iport B inputs/outputs

iPort B outputsiport C inputs/outputs

In the subroutine seanl0 (pages 149, 160, and 171):

Replace btfss portb,S ;test eolumn 2

With btfss porte,S ;test eolumn 2

Replace tsteol movf portb,w iread port Bandlw Ox70 ;mask off rows and bit 7

With tsteol movf porte,w ;read port Candlw Ox70 ;mask off bits 7, 3, 2, 1, 0

DIP switches 5, 6, and 7 are closed to enablethe pullup resistors (see schematic).

Programming Considerations

The following must be done:

• Configuration bits:- LVP disabled, RB3 is digital I/O- DEBUGenabled(lCD modeenabled).

• AID does not exist on the C63, so ADCONI mustbe writtento duringinitialization todisableAID on pinsRAO, 1,2,3, and 5. Writing Ox06 tothe ADCONI register at address Ox9F (bank 1)will do the trick.

• Cannotuse port B bits 6 and 7 (usedby ICD).• Lose 1 level of stackwhen ICD is used.• Program memory

- Address OxOOO mustcontainNOP instruction.

63

Page 65: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

PIC16F877

Almost all of what you have learned in this book applies to the other members of the F87x fami­ly of devices. The F877 is very popular. It has more pins and more goodies than the F870.Now that you understand the F870, you will have an easy time moving up. There are threethings to do and keep in mind.

• Get a Microchip PICI6F877 Data Book for reference.• Be sure to connect both power and both ground pins. There are two of each.

Not doing so is a common beginner mistake.• There are 3 more AID pins located on port E.

When porting an F84 application to an F877:

ADCONI must be written to during initialization to disable AIDon pins RAO, 1,2,3, and 5 as well as REO 1 and 2. Writing Ox06 tothe ADCONI register at address Ox9F (bank I) will do the trick.

64

Page 66: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

APPENDIX A - SOURCES

Digi-Key701 Brooks Avenue SouthThief River Falls MN 56701-0677Tel 800 344 4539Web http:f./www.digikey.com

Jameco Electronics1355 Shoreway RoadBelmont CA 94002-4100Tel 800 831 4242Fax 800 237 6948Web http://www.jameco.comemail [email protected]

JDR Microdevices1850 South 10th StreetSan Jose CA 95112Tel 800 538 5000Fax 800 538 5005Internet Orders http://www.jdr.com

Marlin P. Jones & Assoc IncP.O. Box 12685Lake Park FL 33403Tel 800 652 6733Fax 800 432 9937Order Online http://www.mpja.comemail [email protected]

Mouser Electronics1000 N. Main StreetMansfield, TX 7603-1511Tel 800 346 6873Order Online http://www.mouser.comemail [email protected]

Microchip Technology Inc.2355 W. Chandler BlvdChandler AZ 85224Tel 480 792 7966Fax 480 792 4338Web http://www.microchip.com

Electronic ComponentsModular Phone JackMachined Pin Header

Electronic Components

Electronic Components

Electronic Components

Electronic ComponentsFemale Headers

PICMicro microcontrollersDevelopment SystemsIn-Circuit Debugger

65

Page 67: Eas'j Debug'n - the-eye.euthe-eye.eu/public/Books/Electronic Archive/EasyDebuging.pdf · 2016-02-20 · SasyDebugn USING THE FEATURES OF PICmicro ® PIC16F87x MICROCONTROLLERS FROM

microEngineering LabsP.O. Box 60039Colorado Springs CO 80960Tel 719 520 5323Fax 719 520 1867web http://www.melabs.eomemail [email protected]

Milford Instruments120 High StreetSouth Milford, LEEDS UK LS25 SAOTel 01977 683 665Fax 01977 681465Web http://www.milinst.demon.eo.ukeMail [email protected]

PICMiero ProgrammersDevelopment BoardsBootloader

PIC Development Kits

APPENDIX BPROGRAM LISTINGS vs. PAGE NUMBER

66

pgrnr1.asmied1.asmied2.asmied3.asm

22306055