a1 a beginners guide to the microchip pic

61
Microchip products are available from: 1 COMPONENTS Farnell Com~onents Ltd. . -. .. - . . - Sales, Marketing a1 Canal Road, SALES: TECHNICAL SUPPORT: DATALINE: r- - i d Administration Centre, Leeds, LS12 2TU Tel: 01 13 263631 1 (24 Hrs) Fax: 011 3 263341 1 (24 Hrs) Tel: 01 13 2799123 Tel: 011 3 2310160 (24 Hrs) (Data Sheets Only) 9 ISBN 1-899013-01-6 A BEGINNERS GUIDE TO THE MICROCHIP PIC I - 1 COMPONENTS BY NlGEL GARDNER

Upload: cinematic3006

Post on 08-Apr-2015

411 views

Category:

Documents


15 download

TRANSCRIPT

Page 1: A1 A Beginners Guide to the Microchip PIC

Microchip products are available from:

1

C O M P O N E N T S

Farnell Com~onents Ltd. . -. . . - . . -

Sales, Marketing a1 Canal Road,

SALES:

TECHNICAL SUPPORT: DATALINE:

r - -

i d Administration Centre, Leeds, LS12 2TU

Tel: 01 13 263631 1 (24 Hrs) Fax: 011 3 263341 1 (24 Hrs) Tel: 01 13 27991 23 Tel: 011 3 2310160 (24 Hrs)

(Data Sheets Only) 9

I S B N 1-899013-01-6

A BEGINNERS GUIDE TO THE MICROCHIP PIC

I-1 C O M P O N E N T S

BY NlGEL GARDNER

Page 2: A1 A Beginners Guide to the Microchip PIC

).a 9 I

h- 3 I A - A BEGINNERS GUIDE

OL- 9 I TO THE MICROCHIP PIC I

4Pi 9

*; 3 REVISION 3

BY NlGEL GARDNER

Page 3: A1 A Beginners Guide to the Microchip PIC

T he information contained in this publication regarding dtwlta applications and the like is intended by way of suggestion only and nr'ry

be superseded by updates. No representation or warranty is given and no liability is assumed by Bluebird Technical Press Limited or Arizona Microch~p Inc. with respect to the accuracy or use of such information, o r infringement of patents arising from such use or their compliance to EMC standards or otherwise. Use of Arizona Microchip's products as critical components in life support systems is not authorised except with express written approval by Arizona Microchip. No licenses are conveyed, implicitly or otherwise, under intellectual property rights.

Copyright O Bluebird Technical Press Limited 1998. All rights reserved. Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of Bluebird Technical Press Limited, with the exception of the program listings which may be entered, stored, and executed in a computer system, but may not be reproduced for publication.

Typeset and printed in the UK by: Character Press Limited, Tel: 01462 896500. First printed in 1998.

Circuit diagrams produced with Labcentre lsis Illustrator. Flowcharts produced with Corel Flow.

I TECHNICAL PRESS LTD

Publ ished By: BLUEBIRD TECHNICAL PRESS LIMITED,

ICKNIELD WAY, BALDOCK, HERTFORDSHIRE, SG7 5 6 6 . TELEPHONE: 0 1 4 6 2 8 9 6 8 0 8 FACSIMILE: 0 1 4 6 2 8 9 6 7 0 0

Emai l : s i rnon@charac te r .u -ne t .com

. Preface

T his book, A Beginners Guide to the Microchip PIC is now in it's third revision which includes additional and revised information on the range Microchip PIC products.

I thank you for buying this book and wish you luck in your quest to master the exciting world of the PIC.

Thanks to Gordon McNee for his contribution on the MPLAB Simulator, extracted from his book "The Greatest Little PIC Book" which covers the 8 pin PIC'S.

This book is dedicated to my wife June and my daughter Emma who now borrows my flashing led's, strippers, screwdrivers etc!

Nigel C Gardner May 1998

Page 4: A1 A Beginners Guide to the Microchip PIC

Contents

Preface Product Development The Idea Basics Microprocessor Microcontrollers Why use the PIC? Hardware Design Inside the PIC Pin configuration Which PIC to choose? Hardware requirements

. Reset circuitry Oscillators Pic part numbering I10 circuit Mains Interfacing Analog Inputs Software design Logic truth tables Binary addition and subtraction Hexadecimal notation - ASCII conversion table Source code writing Program structure Universal header Assembler directives Macros Program development The PIC instruction set Bi t operations Byte operations Byte operations specifying a destination Internal registers Status register

ill v i vi 2 4 5 5 8 8

10 10 11 12 13 14 15 17 18 20 20 2 1 2 1 23 24 25 2 6 2 8 3 0 30 3 1 3 1 3 2 34 38 3 8

m F i 9 Contents (cont~n~ea) a BEGINNU;IS GUIDE m WE MICROCHIP R

Lookup tables 40 Subroutine placement 41 Long calls and long goto's 42 Pulse width detection 42 Inputs/outputs 43 Multiplexed inputs 46 Ram resetting and clear 48 Reset vectors 49 Bit test from the RETLW 50 TMRO interrupt uses - 16Cxx only 50 RTCC 50 Watch dog timer 52 The stack 56 Interrupts 57 Software or polled interrupts 58 Interrupt driven software 59 Page boundaries 62 16Cxx CALLS to data tables 6 3 AID conversion block I 63 16C84 the E2 based PIC 66 Other periferals in the PIC family 68 Assemble Software 69 Assembling programs 69 Debug Software & Hardware 72 Development & debug ,. 7 2 Development tools and systems 7 2 MPLAB 74 PIC project boards 81 Program the PIC 83 Code protection 84 Serialisation 8 5 Windowed device development 86 PIC projects 89 Contact numbers 100 Part numbers for development tools 102 The author 103 PIC pinout 104

Page 5: A1 A Beginners Guide to the Microchip PIC

Product Development

roduct development is a combination of luck and experience. Some of the simplest tasks can take a long time to develop and perfect in proportion to the overall product - so be warned where tight

timescales are involved.

To design a product one needs -time - peace and quiet - a logical mind and most important of all a full understanding of the requirements.

The easiest way I find to begin any development is to start with a clean sheet of paper together with the specification or idea.

Start by drawing out a number of possible solutions and examine each to try to find the simplest and most reliable option. Don't discard the other ideas at this stage as there are possibly some good thoughts there.

P

Draw out a flow chart, block diagram, ilo connection plan or any suitable drawing to get started.

Build up a prototype board or hardware mimic board with all the ilo configured. Don't forget i/o pins can be swapped to make board layout easier at a later date - usually with minimal modification to the software.

And then start writing the code - in testable blocks - and gradually build up your program. This saves trying to debug 2000 lines of code in one go!

If this is your first project - THEN KEEP IT SIMPLE - try out just switching a LED or two from push buttons to get familiar with the instructions, assembly technique and debugging before attempting a mammoth project.

Build up the program in simple stages - testing as you go. Rework your flowchart to keep it up to date.

The Idea

An idea is born - maybe by yourself in true EUREKA style or by someone else having a need for a product - the basic concept is the same.

NO ICE :A

1 YES YES

PIC DEVELOPMENT FLOWCHART

Page 6: A1 A Beginners Guide to the Microchip PIC

Before the design process starts, the basic terminology needs to be understood - like learning a new language. So in the case of microcontroller designs based on the PIC, the PIC language (instruction set, terms and development kit) need to be thoroughly understood before the design can commence.

Now lets get started with the general terms, some facts about the PIC and the difference between Microprocessor and Microcontroller based systems.

Basics

Lets start with some basic terminology used.

Microcontroller A lump of plastic, metal and purified sand which without any software does nothing. When software controls a microcontroller, it has almost unlimited applications.

110 A connection pin from the microcontroller to the outside world which can be configured as input or output. 110 is needed in most cases to allow the microcontroller to either communicate, control or read information

Software The information that the microcontroller needs to operate or run. This needs to be free of bugs and errors for a successful application or product. Software can be written in a variety of languages like C, Pascal or Assembler (one level up from writing your software in binary).

Hardware The microcontroller, memory, interface components, power supplies, signal conditioning circuits and all the components connected to it to make it work and interface to the outside world. Another way of looking at (especially when it does not work) is that you can kick hardware.

Simulator The MPLAB development environment has it 's own inbuilt simulator which allows you access to some of the internal operation of the PIC. This is a good way of testing your designs if you know when events occur. If an event occurs 'somewhere about there1, you might find the simulator restrictive. Full trace, step and debug facilities are however available

ICE In Circuit Emulator - (ICE PIC or PIC MASTER) - a very useful piece of equipment connected between your PC and the socket where the microcontroller will reside. It enables the software to be run on the PC but looks like a microcontroller at the circuit board end. The ICE allows you to step through a program, watch what happens within the micro and how it communicates with the outside world.

Programmer A unit to enable the program to be loaded into the microcontrollers memory which allows it to run without the aid of the ICE. They come in all shapes and sizes and costs vary. Both the PICSTART PLUS and PROMATE CE from Microchip connect to the serial port.

Source File A program written in a language the assember and you understand. The source file has to be assembled before the microcontroller will understand it.

Assembler A software package which converts the Source file into an Object file. Error checking is built in, a heavily used feature in debugging a program as errors are flagged up during the assembly process. MPASM is the latest assembler from Microchip handling all the PIC family.

Object File This is a file produced by the Assembler and is in a form which the programmer, simulator or ICE understands to enable it to perform i ts function. File extension is .OBJ or HEX depending on the assembler directive.

List File This is a file created by the Assembler and contains all the instructions from the Source file, with their hexadecimal values along side and comments you have written. This is the most useful file to examine when trying to debug the program as you have a greater chance of following what is happening within the software than the Source listing. The file extension is .LST

Other Files The error file (.ERR) contains a l i s t of the error but does not give any indication as to their origin. The COD file is used by the emulator.

Bugs Errors created unknowingly by you. These range from simpel typin errus to incorrect use of the software language. Most of these

Page 7: A1 A Beginners Guide to the Microchip PIC

bugs will be found by the compiler and shown up in a .LST file, others will have to be sought by trial and error.

Microprocessor

A microprocessor or digital computer is made up of three basic sections - CPU, I10 and Memory - with the addition of some support circuitry.

Each section can vary in complexity from the basic to all bells and whistles.

Taking each one in turn:

Inputloutput (110) can comprise digital, analogue and special functions and is the section which communicates with the outside world.

The central processor unit (CPU) is the heart of the system and can work in 4, 8 or 16 bit data formats to perform the calculations and data manipulation.

The memory can be RAM, ROM, EPROM, EEPROM or any combination of these and is used to store the program and data.

An oscillator is required to drive the microprocessor. Its function is to clock data and instructions into the CPU, compute the results and then output the information. The oscillator can be made from either discrete components or be a ready made module.

Other circuitry found associated with the microprocessor are the watch dog timer - to help prevent system latchup, buffering for address and data busses to allow a number of chips to be connected together without deteriorating the logic levels and decode logic for address and I10 to select one of a number of circuits connected on the same bus.

It is normal to refer to a Microprocessor as a product which is mainly the CPU area of the system. The I10 and memory would be formed from 'separate chips and require a Data Bus, Address Bus and Address Decoding to enable correct operation.

nv-

vo DIGITAL

PWM ANALOG

US232 12C 4

i

TYPICAL MICROPROCESSOR SYSTEM

Microcontrollers

The PIC on the other hand is a microcontroller and has all the CPU, memory, oscillator, watchdog and I10 incorporated within the same chip. This saves space, design time and external peripheral timing and compatibility problems, but in some circumstances, can limit the design to a set memory size and I10 capabilities.

The PIC family of microcontrollers offer a wide range of 110, memory and special functions to meet most requirements of the development engineer.

You will find many general books on library shelves exploring the design of microcontrollers, microprocessors and computers, so the subject will not be expanded or duplicated here other than to explain the basic differences.

Why use the PIC?

Code Efficiency The PIC is an 8 bit microcontroller based on the Harvard architecture - which means there are separate internal busses for program and data. The throughput rate is therefore increased due to

Page 8: A1 A Beginners Guide to the Microchip PIC

simultaneous access to both data and program memory. Conventional microcontrollers tend to have one internal bus handling both data and program. This slows operation down by at least a factor of 2 when compared to the PIC

Safety All the instructions fit into a 12 or 14 bit program memory word. There is no likelyhood of the software jumping into the DATA section of a program and trying to execute DATA as instructions. This can occur in a non Harvard architecture microcontroller using 8-bit busses.

Instruction Set There are 33 instructions to be learnt in order to write software for the 12C50x1 16C5x family and 35 for the 16Cxx devices. All the instructions used by the PIC are based on registers, and are 12 bits in length for the 16C5x family or 14 bits wide for the 12C67x 16Cx family. Each instruction, with the exception of CALL, GOTO' or bit testing instructions (BTFSS, INCFSZ) executes in one cycle.

Speed The PIC has an internal divide by 4 connected between the oscillator and the internal clock bus. This makes instruction times easy t o calculate, especially if you use a 4MHz crystal. Each instruction cycle then works out at 1 US. The PIC is a very fast micro to work with eg a 20MHz crystal steps through a program at 5 million instructions a second! - almost twice the MIP speed of a 386SX 33!

Static Operation The PIC is a fully static microprocessor, in other words if you stop the clock, all the register contents are maintained. In practice you would not actually do this, you would place the PIC into a Sleep mode - this stops the clock and sets up various flags within the PIC to allow you to know what state it was in before the Sleep. In sleep, the PIC takes only i t s standby current which can be less the 1 uA.

Drive Capability The PIC has a high output drive capability and can directly drive LED'S and triacs etc. Any I10 pin can sink 25mA, an 8 bit port 1 OOmA.

Options A range of speed, temperature, package, I10 lines, timer functions, serial comms, EEPROM, AID and memory sizes are available from the PIC family to suit virtually all your requirements.

Versatility The PIC is a versatile micro and in volume is a low cost solution to replace even a few logic gates - where space is at a premium.

Security The PIC has a code protection facility which is one of the best in the industry. Once the protection bit has been programmed, the contents of the program memory cannot be read out in a way that the program code can be reconstructed.

Development The PIC is available in windowed form for development and OTP (one time programmable) for production. The tools for development are readily available and are very affordable even for the home enthusiast.

Page 9: A1 A Beginners Guide to the Microchip PIC

I n order to design any system, both hardware and softwarre rrsed trl he fully understood. The hardware needs to be covered before tho roftwr~a as this interfaces with the outside world.

The topics covered in this section are -

inside the PIC which PIC to choose minimum hardware requirements reset circuitry, timers oscillators part numbering I10 expansion mains interfacing inputs and outputs analog inputs

Inside the PIC

The working heart within the CPU area is the ALU or Arithmetic Logic Unit and contains one register, the W or Working register. The PIC differs from a number of other microprocessors in having only one main register for arithmetic and logical operations. The W register is 8 bits wide and holds any data for transfer within the CPU.

Also within the CPU core are Data Register Files which fall into two categories -those which serve as I10 and Control and those acting wholly as user RAM.

The dedicated registers are used for functions such as port direction control, the result from an AID conversion or the value which has to be sent via an RS232 link.

The undedicated registers on the other hand are used for temporary storage of information eg counting down a time, holding the number of bits received from an input etc.

2 - g , e z s & % %,E $ g g $; Z F on: ::

BAUC PIC BLOCK DIAGRAM

Page 10: A1 A Beginners Guide to the Microchip PIC

The STACK is allocated to the PROGRAM COUNTER to enablc d progrrtrr tn know where to return after a CALL to a subroutine. On the ISCSx, I?( 'ION series, the STACK is 2 deep while the 16Cxx, 12C67x families has the 51At k increased to 8 deep.

Separate busses for program instructions and data are used It) microcontrollers based on Harvard Architecture t o speed up dab1 throughput and improve software safety. This architecture allows simultaneous access to both data and program memory.

Pin Configuration

see card in back of book .)

Microchip have adopted the sensible approach and made all 18 pin, 28 pin narrow and 40 pin devices with the same pin configuration.

Which PIC to choose?

The I10 requirements should be known at the start and this will determine the product chosen during development.

When you start to write the code, don't worry which memory size to choose. It is easier to look at the requirements as you go along.

If simple analog interfacing is required i.e. measuring resistance, the 16C5x family may well suffice, however, if AID converters and interrupt functions are needed, the 16C7x family will f it the bill or if non-volatile data storage is needed, then the 16C84 is the logical choice.

A comprehensive list of products is given in the back of the book, but it is advisable to consult the Microchip data sheets or web site for the latest product information.

There are also a number of options available for the final device chosen for your product depending on whether the application will need field updating, permanent installation and security or for volume applications, factory programmed and serialised devices.

Hardware Requirements

The minimum hardware requirement to run the PIC is an oscillator. This can be in the form of a resistor and capacitor or a crystallceramic resonator and two capacitors. The reset line must be connected to the supply voltage as internal circuitry will handle resetting the PIC in normal operating conditions.

I -- 4 - A ~ +

X I I) MCLR > A1 1

401 16 OSCI

2 A3 -

l5 OSC2

N ~2 I b RTCC

8 82 -

\ PICIGCXX 83

84 10

C 3 C l B5 -

C 3 IOONF In 9 ffi$ 87 A

YI

\ - - I 1

- -

MINIMUM HARDWARE REQUIREMENTS

The new PIC12C50819 (8 pin devices) have the option to use either an external oscillator or it's own internal 4MHz oscillator - saving 2 pins for 110.

The next stage is to provide external reset components or brown out reset protection if required. Some of the 16Cxx family have brown out detection as part of the internal circuitry with an additional testable bit in the PCON register. This bit indicates if the supply voltage to the PIC has dipped to between 3.8 to 4.2 volts for greater than 100 micro seconds.

A decoupling capacitor of 100nF should be connected across (m the power supply tracks as close as possible to the PIC.

Tracks carrying power and ground should be as wide as practicable to lower their resistance which helps minimise electrical noise problems.

Page 11: A1 A Beginners Guide to the Microchip PIC

TO THE MICROCHIP PIC Hardware Des,gn A BEGINNERS GUIDE TO THE MMlCROCHlP PIC I

Reset Circuitry

Reset circuitry is important within a microprocessor/microcontroller system for the following reasons:-

To ensure that a known state exists for certain registers i.e. program counter, I10 and control registers. To allow the clock sufficient time to settle at the correct frequency. To ensure that if there is a dip in the supply voltage that the micro restarts properly.

The PIC has built in Power On Reset circuitry. If the power supply to the PIC rises at a rate greater than 0.05VlmS i.e. < IOOmS OV to 5V, then the internal reset circuitry will cope.

Some low frequency crystal oscillators need greater than 18mS to start up. In this case, and in those cases where the power supply takes longer than IOOmS to rise, an external RC reset circuit may be required In applications where there is a likely hood that the supply rail may dip or brown out (not a complete loss of power), extra reset circuitry needs to be added to ensure a clean reset following a brown out.

T ' ' y R 4 1 h MCLR AI

L - I

BASIC RESET CIRCUIT RESET WITH BROWNOUT DETECT

In applications requiring a pre-set voltage trip point, a device such as the Texas Instruments TL770 or Dallas Econo Reset could be used to force a reset if the supply voltage falls below a pre-set value, ensuring an accurate protection against brown out.

Oscillators

The PIC will accept crystal and RC oscillators in a number of options.

16C5x PIC suffix -XT Crystal or Ceramic Resonator - general purpose - 4MHz max -RC ResistorICapacitor time constant - low cost - 4MHz max -HS Crystal or Ceramic Resonator - high speed - 2OMHz max -LP Crystal or Ceramic Resonator - minimum current - 40kHz max

Windowed devices can be programmed to any of the above configurations for development purposes, suffix -JW.

The latest version of the 16C5x family now have an A suffix following a number and package type. The main difference with the A suffix devices is that the oscillator type is chosen at the programming stage as opposed to the time of purchase. The 16Cxx devices are chosen by frequency and the oscillator type is selected at the programming stage.

In the RC oscillator design, the resistor should be in the region 5k to 100k. High R values i.e. IM make the oscillator sensitive to noise, humidity and leakage, the latter two being a product of the PCB and its environment. Values of R below 2.2k can cause instability or even lack of oscillation.

The capacitance part of the RC oscillator needs to be >20pF. Even though there is usually enough capacitance floating around the pins, no external capacitor will make the oscillator prone to hand capacitance effects and variations of PCB layout etc.

When choosing the R and C values, avoid large C and R as the leakage of C and resistance of R may also effect the frequency stability.

Selection graphs and tables are shown in the data sheets to assist in the choice of components.

Page 12: A1 A Beginners Guide to the Microchip PIC

If you are using an RC oscillator, a clocW4 will be avdlnt~le o ~ \ 1 1 . OSCZICLKOUT pin. This could be used within your circuitry to drlvs A/ converters, LCD driver chips etc.

Ckck from External System

16 A2

OSCl A3

PIC Part Numbering

The PIC comes in a number of packages, speed and oscillator functions. Devices such as the 16C5x are available in standard DIL or SO packages and are purchased by the type of oscillator. The A series of PIC'S (16C54A for example) are purchased by the maximum speed at which they run (-04, -10, -20) - oscillator type selection is made at the programming stage. This option makes inventory control that much easier and at no cost penalty to the user. Package options for standard PIC'S are P - plastic, SO - surface mount and JW -windowed. Temperature ranges are designated as normal 0 to +70 deg C, I - industrial -40 to +85 deg C and E - extended -40 to +I25

deg C. so a 4MHz 16C54 in plastic would be PIC16C54-XTP and a 10MHz 16C84 in SO industrial temp would be PIC16C84-1011SO.

110 Circuit

PORT A 16C5X

PORTA

PORT A 1 6CXX

DATA BUS 7 PORTA

OUTPUTS \

110 PINS

INPUTS

TRlS PORTA

16C7X ONLY I

Page 13: A1 A Beginners Guide to the Microchip PIC

LA BEGINNERS GUIDE TO ThE MICfjKHp PC. - kid . I

ONLY

TERRUPT

t t t GIE INTE RBlE

PORT B CONTROL AND INTERRUPTS

The basic 110 circuitry needed to interface to a PIC can be a push button and a LED. This is all that is required for one of the first examples to try with a PIC - press button, turn on LED.

The PIC can drive LED'S directly and can sink 25mA or source 2OmA on a pin -see data sheets for maximum port and device limits. This current capability enables the PIC to drive a wide range of devices from LCD and logic products to direct drive of triacs connected to the mains.

On the 16Cxx family, there is a the facility to turn on a weak pull up on PORT B. This is set in the OPTION register and eliminates the need for a resistor pack when PORT B is used for inputs.

hardware Deslgn 1 An additional PORT A pin (A4) is provided on the 16Cxx devices which also functions as the TOCLK input. As an input, the pin is buffered via a Schmitt trigger. When configured as an output, the pin is an open collector.

In order to use the A4 pin as an output, a current feed needs to be present to see any change in output state. This can be in the form of a 10k pull up resistor. As the output is open collector, remember that the logic for this pin is reversed - a logic 1 turns on the transistor and hence pulls the pin to logic 0. Note that this pin has no source capability - only sink.

Mains Interfacing ,

Development of circuitry attached directly to the ( l mains should always be carried out wi th an isolation

transformer and earth leakage protection. And preferably with someone else around t o pick up the pieces if it all goes wrong.

An electric shock of :-

5mA wil l cause a muscle spasm which could result in you catching a hand on a protruding object or throw you backwards off a chair lOmA wil l cause severe pain 30mA wil l cause respiration t o cease 75mA stops the heart.

Skin resistance varies from 5k if wet with salt water t o 100k if dry and lightly making contact - ohms law wil l tel i you the rest.

lnterfacing to the mains can be achieved in one of two ways:-

a) an opt0 isolator b) 2 x 2.4M resistors in series with the mains input. Both methods have their advantages and disadvantages.

The opt0 gives safety, especially when the end user has access to the circuitry so applications are completely isolated from the user.

On the other hand, lamp dimmers can happily run directly from the mains

Page 14: A1 A Beginners Guide to the Microchip PIC

with capacitive power supplies and a resistor fed into one of the portr 1t1 provide zero crossing detection.

A2 A3 OSCl

BOJINT OSC2 MAINS 8

7 B2 AWMRO

TYPICAL MAINS INPUT CIRCUITS

Analog Inputs

The PIC 16C7x series have an inbuilt 8 bit analog to digital converter. A voltage presented to the A/D converter will be measured and converted to one of 256 levels. If the voltage falls outside the measuring limits of the AID, input scaling is needed to ensure that the input voltage falls within the conversion range.

For example if a sensor produces 0 to 3V and the A/D has a reference of 5V, the best resolution for the sensor will be 51255 = 19.6mV

hardware Des~gn h On the other hand, if the sensor is boosted to 5V or the A/D reference is reduced to 3V, the resolution then becomes 11.7mV.

If the voltage is too high, then it needs to be attenuated before being fed to the AID. The simplest form of attenuator is a pair of resistors acting as a potential divider providing they don't load the source.

Calculation of resistance is made by straight ratios as the current drawn by the A/D is negligible, however, ensure the values are high enough to prevent resistors heating on high voltage divider networks, e.g. a 0-20V supply needs to be fed into the 16C71 as part of a bench power supply. A resistor chain of 20K will dissipate 20mW. The resistor chain can be made from a 15K and 5K giving a 0-5V input to the PIC.

If resistor tolerance needs to be compensated for, the 5K could be replaced with a 4K7 and a 1 K multiturn trimmer. A 20V reference is applied to the top of the 15K resistor and the voltage is set to precisely 5V a t the input to the A/D by adjusting the trimmer.

Boosting up a signal is achieved by use of op amps. The op amp gain is determine by the choice of feedback resistors and again, a multiturn trimmer can be employed if precision is required.

Associated with the A/D are three registers to contend with ADCONO, ADCONl and ADRES. The ADRES is the register holding the result of the A/D conversion process - more on these registers in the software section.

t". TO PIC

Page 15: A1 A Beginners Guide to the Microchip PIC

Software Design

SOFTWARE DESIGN 6 3 I

Having understood the hardware and how to connect the PIC to the real world, the software needs to be tackled to enable the PIC to start doing something. If you have already worked with software, some of the following information may be familiar.

The software design comprises - d3 an understanding of logical functions hexadecimal notation . source code writing use of assembler directives macros to save time writing code program development the instruction set internal registers subroutines lookup tables I10 port setup reset vectors TMRO (RTCC) WDT interrupts the stack AID conversion E2 based PIC3

Logic Truth Tables

When working with any logic based product, be it CMOS logic or a microcontroller, it is important to understand how an Inclusive OR differs from an Exclusive OR. As the PIC uses logical processes for data manipulation, the following truth tables are shown to add clarity to the terms found later in the PIC instruction set.

IOR (Inclusive OR) XOR (Exclusive OR)

Input A B Output Input A B Output 0 0 0 0 0 0 0 1 1 . 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0

AND Compliment (invert)

Input A B Output Input A Output 0 0 0 0 1 0 1 0 1 0 1 0 0 1 1 1

Binary Addition and Subtraction

This also needs to be understood when working with the PIC or other logic based systems.

Addition 0 + 0 = 0 Subtraction 0 - 0 = 0 0 + 1 = 1 1 - 0 = 1 1 + 0 = 1 1 - 1 = 0 1 + 1 = 1 plus 1 carried , 0 - 1 = 1 plus 1 borrowed

to next column from next column e.g. 0110 (6) e.g. 0110 (6)

001 1 + (3) 0011 - (3) 1001 = (9) 0011 = (3)

Hexadecimal Notation

A microcontroller uses binary internally to operate. If a program is written in binary it is unwieldy and difficult to debug.

e.g. the value 11010100 in binary converts to D4 in hex, when added to an instruction such a ADDLW, the result becomes 11 11 101 1010100. It therefore becomes easier to write:

Page 16: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICRDCHIP PIC Software Des~gn

ADDLW OD4H ; the H signifying hexadecimal for the assembler

The hexadecimal system is an easier way to write numbers for use with microcontrollers, but binary is still useful when setting up registers and I10 ports i.e. port b bits 0 to 3 and 7 as inputs, 4 to 6 as outputs becomes :-

MOVLW B'10001 I I I' ; B specifies binary for the assembler TRlS PORTB ; set up port with contents of W register

Below is a table to help conversion between hexadecimal, decimal and binary numbers from 0 to 15. This is especially useful when examining registers, coding software or manipulating bits on I10 ports. In time the conversion will become automatic.

Binary 4 2 1

For larger numbers, use the following hex to decimal conversion table.

Software Design A BEGINNEE GUIDE TO THE MICROCHIP PIC

ASCII Conversion Table

HEX msb 0 1 2 3 4 5 6 7

Isb bits 0 0000 1 0001 2 0010 3 001 1 4 01 00 5 0101 6 01 10 7 01 11 8 1000 9 1001 A 1010 B 101 1 C 1100 D 1101 E 1110

- F 1 1 1 1

EOT DC4 $ ENQ NAK % ACK SYN & BEL ETB ' BS CAN ( HT EM ) LF SUB * VT ESC + FF FS I

I

Page 17: A1 A Beginners Guide to the Microchip PIC

BA WINNERS GUIDE TO M MICROCHIP PC Software Des~gn

This table will be used extensively for applications using serial communications and sending characters to intelligent displays such as 16 characters by 2 line.

The ASCII symbols in the above table are:

NUL - Null SOH - Start Of Heading STX - Start Of Text EOT - End Of Transmission NAK - Negative Acknowledg SYN - Synchronous Idle ETB - End Transmission Block CAN - Cancel EM - End of Medium SUB - Substitute ESC - Escape FS - File Separator GS - Group Separator RS - Record Separator US - Unit Separator SP - Space (blank)

Source Code Writing

DLE - Data Link Escape DC - Device Control EXT - End Of Text ENQ - Enquiry ACK - Acknowledge BEL - Bell BS - Backspace HT - ~orizontal Tab LF - Line Feed VT -VerticalTab FF - Form Feed CR - Carriage Return SO -Shift Out 51 - Shift In DEL - Delete DC1 -Xon DC3 - Xoff

When writing programs, it is important to follow 4 basic rules:

1 Always comment your software - you or someone else will inevitably need to come back to the program at a later stage and without comments, what made sense at the time will be garbage later.

2 Use a universal header for your programs. This reduces the work load, creates a consistent format and reduces the number of variables you have to remember. An number of examples are found in the programs on disk.

3 Put all your subroutines in one area. With the 16C5x this should be at the top of each memory page (OO-FFh) - I will explain why later.

what you want the software to do and show where you need to interface with the real world (110).

Program Structure 't

Start off at the top of your program with the header information. Things like who wrote it, when, what revision, which PCB the program ties up with etc. This enables those reading the program to know how it stands in relation to the rest of the design.

Next place the equates, #define's, list p=16m etc. to enable the assembler 3 : to do it's work. Then start the program with it's origin or 0RG statement.

An equate or EQU is a way of telling the assembler that where it finds a name, to replace that name with the value it's equated to e.g. porta equ 5.

Wherever the assembler finds the word porta within your program, it will substitute the value 5 in it's place.

1 6 3 I A #define on the other hand tells the assembler to substitute two values

! where it finds a certain word e.g. #define led portb.4

d $ Wherever the assembler finds the word led, it substitutes 6.4 (or portb.4) in

d 3 it's place.

I This has a major benifit when modifying code - you only need to change ' the port definition in one place to change from led1 being on porta.2 to portc.6 - the assembler does the rest ( but don't forget to change the port

I direction register if required ).

1s: 9 Labels are used as a marker to point the assembler to a specific line in the (tl 3 program i.e. goto test1 or caN convert

I 6 9 Labels, equates, #define and comments should be the only text which I should appear in the left most position on a line. All other text and

assembler commands should be indented. Comments are preceded by a 1

(ti 3 semicolon and are ignored by the assembler.

4 Prepare a flowchart or some form of drawing to help you remember &! 4 I l ) r - - - I A - d h -m

Page 18: A1 A Beginners Guide to the Microchip PIC

J BEGINNERS GUIDE TO THE MICROCHIP PIC Software Deslgn

e.g. ; this is a comment porta equ 5 #define , led portaf3

org 0 start goto start

end

Ensure no duplication of equates and labels exists within the program. The assembler might not pick these out and will cause havoc when debuging. e.g.

TEMP EQU 5 ; sets the value 5 to TEMP

ADDLW TEMP ; correct operation using TEMP

GOT0 TEMP ; will cause program to jump ; to address 5 instead o f ; label TEMP which may be at address 45

Another useful tip is to build a library of subroutines, macros and code chunks. It's a bit like a cake recipe -take 20 lines of LED.ASM and 5 lines of SWITCH.ASM etc.

When you write code, there must be a start and an end. The start is always defined when the PIC resets. The end must be defined by you - this does not mean that the program can't

loop around for ever, but it must not just stop in mid air. A program falling off the end will continue to cycle and fails to make sense to anyone trying to fault find - even though it may work sometimes!

Universal Header

;WRITTEN BY ;DATE REV ;FILE SAVED AS xxx.ASM ;FOR PIC I6Cxx ;RESONATOR 4MHz ;WATCHDOG ENABLEDIDISABLED

I

;CODE PROTECTION ONIO FF ;SOFTWARE FUNCTION (describe what the code is actually for or what it

is doing)

LIST put the list o f assembler directives here - see below for further details

;********GENERAL EQUATES *****

TMRO EQU 1 , ; COUNTER PCL EQU 2 ; PROGRAM COUNTER STATUS EQU 3 ; STATUS REGISTER

; add in additional equates for other registers and bits where required i.e. other pic's

ORG OOH ; change address depending on pic type see ,- reset vector section

GOT0 INIT ; this is where you want the program to start

INIT ; the program starts here ; YOUR PROGRAM

END ; and ends here - this must appear on the last line o f the ; program so the assembler knows where to stop.

Page 19: A1 A Beginners Guide to the Microchip PIC

The equates for registers can be saved as 16Cxx.H for example and be called up from within the source code by means of an INCLUDE "16Cxx.H" statement. The 110 equates can be omitted from P1C.H as their use will vary from program to program. This reduces the source file size by a very small amount but the resulting .OBJ and .LST files will be the same either way.

Sample headers are available via the Microchip web site and are also supplied with the MPLAB.

Assembler Directives

In addition to all the instructions used for writing code (ADDLW, MOWVF etc.), there are a number of assembler directives which can speed up code writing. An assembler directive is a command written in the source code to control, direct or save time when assembling and has no effect on the operation of the software. The result of incorporating assembler directives will be seen in the .LST file after assembly. Some of these mentioned already include #define and org. A full l is t is given in the MPASM assembler users guide, but some of the more useful ones are described here:

PAGE forces a page eject to allow sections of program to be printed individually.

LINES sets the number of lines to be printed per page. Useful when printing to non-standard sheets of paper.

C specifies the column width for printing. C=80 is used for narrow A4 size pages, C=132 for wide printers or condensed printing.

INCLUDE pulls in external files into the program. A use for this is where you have a file set up with pre-defined macros, a file with all the general equates and register definitions for the processor to a file containing a large lookup table (thermistor voltage to temperature conversion).

i t s use would be include "P1CREG.H" or include "c:\picbnacros.asm "

RES reserves memory locations for use within a program. One way t o define the register equates at the start of a program is

temp 1 equ Och temp2 equ Odh count equ Oeh

This can be replaced with :-

org Och temp 1 res 1 temp2 res 1 \

count res 1 \ \

this then allows additional labels to be inserted into the l is t of registers j without re-assigning the registers.

IF ELSE ENDlF

This directive allows customisation of a program at the assembly stage. An example of this could be to select the reset vector for a PIC based on the part number or in data comms where the number of bits, stop bit and parity could be selected when the program is assembled. This then allows unused code to be left out - reducing the overall program size.

If on a data comms program, the choice is to output the most significant or least significant bit first, the program would normally need to be completely different. If however the IF ELSE ENDiF commands are used, at each occurrence of a test for MSB being a 1 or 0, the appropriate code would be inserted into the assembled program.

e.g. IF MSB rrf xmit-reg, f ; if MSB = true or 1 then this line will

; be compiled ELSE

rlf xmit-reg, f ; otherwise this one will END IF

ORG specifies the origin for code following the statement. it is used to specify where the program starts, where a section of code begins (interrupt vector for example) or where a block of memory will start.

LIST used to pass information to the assembler regarding the

Page 20: A1 A Beginners Guide to the Microchip PIC

processor being used, lines per page, column width and format the program has been written in (radix).

e.g. list C=80, n=55, p=16c84; r=hex

Macros

Macros are a way of saving code writing by calling up commonly used routines from a library (via the include command). This saves the re-typing information time and time again and allows consistency in program writing. A macro library could include bit testing, led flashing, ald conversion routines, port setups, E2 routines etc. and can be called with just one line of programming.

e.g. set-A0 macro ; this defines the start o f the macro bcf adcon0,O bcf adcon0, 1 endm ; and this the end

would enable the following to take place:-

se t-A0 ; selects channel call conv ; call to a convert subroutine

This saves remembering which bits need to be set or cleared for a particular ald channel and when assembled, looks like this in the .LST file:

bcf adcon0,O bcf adcon0, 1 call conv

Program Development

There are three basic routes to software development. Using an ICE, using a programmer and a handful of EPROM based PIC'S or using the simulator.

Even when you have an ICE, you will need a few re-programmable devices to allow testing of the final product.

Start off with at least 5 EPROM or an EEPROM version as you will soon become impatient waiting 10 to 20 minutes for erasure of a PIC.

As the devices get larger, so the erase time increases. In the case of 16C84 development, there is no EPROM version ( - the device is electrically erased when re-programmed.

If you are developing without an ICE, create a simple routine which can flash a led on a spare pin. The call to this routine can then be moved within the program to determine where the program has reached or not as the case may be. If the LED flashes, the previous code was executed - if it didn't, then move the call further back in the program.

The PIC Instruction Set

The instructions can be split into 3 groups - Bit, Byte and Literal I Control operations.

Most of the operations take 1 clock cycle (oscillator frequencyl4) to execute. The exceptions are those involving a test i.e. BTFSS, DECFSZ. If the operation results in a skip, an extra clock cycle is invoked. This makes program timing easy to calculate especially if working with a 4MHz oscillator - luS instruction cycles. Lets start with the simplest -

Bit operations a

Instruction Status Affected Meaning

BSF f,b none set the bit b in file f e.g. BSF PORTABITO ;turns bit 0 on on port a

BCF f,b none clear the bit b in file f e.g. BCF STATU5,ZERO ;clears zero bit

GOT0 k none the program jumps to label i address k

An example using these three instructions i s

SQ BSF PORTA,BlTO ; set port a bit 0 pin high

Page 21: A1 A Beginners Guide to the Microchip PIC

g Software Des~gn

BCF PORTABITO ; set port a bit 0 pin low GOT0 SQ ; goto SQ and do it all again

This program generates a pulsing output on the Port A, Bit0 pin.

BTFSS f,b none test bit b in file f and if it is set i.e. logic 1, then skip the next instruction if it is logic 0 then do the next instruction

e.g. BTFSS STATUS,CARRY

BTFSC f,b none test bit b in file f and if it is clear i.e. logic 0, then skip the next instruction if it is logic 1 then do the next instruction

e.g. BTFSC SWITCH1

Byte operations

NOP none do nothing e.g. NOP

NOP ; wastes 2 clock cycles use this instruction to create short delays or allow ports and external peripherals to settle between write and read operations.

CLRW z clear or reset the contents of the W register to zero

CLRF f z clear or reset the contents of file f to zero

MOWVF f none copy the contents of the W register into the file f

e.g. MOVWF TEMP

Literal 1 Control Operations

OPTION none copy the contents of W into d i, (1 6C5x, 12C50x only) the-option register ,.' (5. I $

I si 9

e.g. MOVLW OFH OPTION ; loads OPTION

; register with OFH

SLEEP T0,PD the PIC is placed in a sleep or standby condition. The register contents are frozen and the PIC draws a fraction of the operating current On a wakeup from sleep, the 16C5x family will jump to the reset vector, whereas the 16Cxx family continue on the next line of code. i

CLRWDT TO, PD the watchdog timer register is set to zero

TRlS f none the contents of W are placed in the (1 6C5x, 12C50x only) port control register f, where f=5,

6 or 7 e.g. MOVLW B1llllOOOO'

TRlS PORTB ; makes portb ; upper 4 bits inputs and ; lower 4 bits as outputs

CALL k none a call is made to a subroutine labelled k. the contents of the W register will be transferred for use within the subroutine if required

e.g. CALL TEMP-CONVERT

RETLW n none return from a call or subroutine with a value n in the W register

e.g. RETLW 2OH ; returns to calling address + 1 with 20H in ; the W register

MOVLW n none the value n is moved into W e.g. MOVLW 36H

IORLW n Z the value n is inclusive ORed to W e.g. IORLW OC4 H

Page 22: A1 A Beginners Guide to the Microchip PIC

) BEGINNERS GUIDE TO THE MICRKHIP PIC Software Des~gn

ANDLW n Z the value n is ANDed to W e.g. ANDL W 8'0000011' ; will mask off all but the lower 2 bits

XORLW n Z the value n is exclusive ORed to W

This example tests for equality between the contents of register TEST and a number VALUE in the W register.

MOVF TES7; W ; store contents in W XORLW VALUE ; exclusive or the contents o f W

; with VALUE B TFSS - Z ; test Zero bit in Status register

; if contents are the same, Zero bit ; is set

GOT0 NOT SAME ; not equal ' GOT0 SAME ; both are equal

Byte operations specifying a destination

If the result destination is not specified in instructions like ( IORWF, ADDWF etc., the default destination is the file - not the W register. If an operation on a file is to be carried out

and the file contents are not intended to change, ensure that W is specified as the destination. Alternatively specify the destination for ALL instructions which use a destination. The W register can not be specified as the file in INCF W for example nor another register such as INCF TEMeCOUNT. e.g.:

ADDWF TEMP, W ; stores result in W register leaving ; TEMP intact

ADDWF TEMR F ; stores result back in TEMP ; overwriting previous value

IORWF f, d Z inclusive OR the contents of W with file f and place the result in destination d

e.g. IORWF COUNTF places the result of the OR function back in the file COUNT

ANDWF f,d z AND the contents of W with file f and place the result in destination d

e.g. ANDWF TEMRW places the result of the AND function

Software Des~gn s in the W register leaving the contents of the file TEMP alone

XORWF f, d Z ' exclusive OR the contents of W with file f and place the result in

I destination d

ADDWF f, d C,DC,Z add the contents of W with file f and place the result in destination d

e.g. ADDWFDAT-IN, W

SUBWF f, d C,DC,Z

COMF f, d

MOVF f, d

DECF f, d

INCFSZ f, d

e.g. INCFSZ GOT0 GOT0

DECFSZ f, d

z

Z

z

z

none

subtract the contents of the W register from file f and place the result in destination d.

compliment the contents of file f and place the result in destination d

movelcopy the contents of file f and place the result in destination dl where d is either a file or W

increment or add 1 to the contents of file f and place the result in destination d

Decrement or subtract 1 from file f and place the result in destination d

increment the file f and store the result in destination d. if the result is zero, skip the next instruction

TEMR W LOOP END-LOOP

none decrement file f and if the answer is zero, skip the next instruction. store the result in destination d

Page 23: A1 A Beginners Guide to the Microchip PIC

RRF f, d C rotate or move all the bits one place to the right. bit 0 ends up as the Carry bit and the Carry bit becomes bit 7. the

I result is put in destination d

RLF f, d C rotate or move all the bits one place to the left. bit 7 becomes the Carry bit and the Carry bit becomes bit 0. the result is put in destination d

SWAPF f, d none the upper and lower nibbles are swapped over. the result is places in destination d

ADDLW n C,DC,Z the value n is ADDed to W

SUBLW n C,DC,Z the value W is subtracted from n and the result placed in W - NOT SUBTRACT LITERAL FROM W as it is written!

RETURN none return from a subroutine leaving the contents of the W register as they were.

RETFIE none return from an interrupt

OPTION and TRIS are only used with the 16C5x and 12C50x families and though they are accepted by the assembler, are not recommended for the 16Cxx family.

PIC16CXX SPECIAL INSTRUCTION MNEMONICS

These instructions are recognised by the Assembler and substituted in the program listing. They are a form of shorthand similar t o Macros.

ADDCF f,d Add Carry to File BTFSC Status, Carry

INCF f,d Z

ADDCF f,d Add Digit Carry to File BTFSC Status, Digit Carry

INCF f,d Z

B k Branch GOT0 k

BC k Branch on Carry BTFSC

GOT0

BDC k Branch on Digit Carry BTFSC

GOT0

BNC k Branch on No Carry BTFSS

GOT0

BNDC k Branch on No Digit Carry BTFSS

GOT0

BZ k Branch on Zero BTFSC

GOT0

BNZ k Branch on No Zero BTFSS

GOT0

CLRC Clear Carry BCF

CLRDC Clear Digit Carry BCF

CLRZ Clear Zero BCF

MOWF f Move File to W MOVF

NEGF f,d Negate File COMF

INCF

SET0 Set Carry BSF

SETDC Set Digit Carry BSF

SETZ Set Zero BSF

SKPC Skip on Carry BTFSS

SKPNC Skip on No Carry BTFSC

SKPDC Skip on Digit Carry BTFSS

SKPNDC Skip on No Digit Carry BTFSC

SKPZ Skip on Zero BTFSS

SKPNZ Skip on Non Zero BTFSC

SUBCF f,d Subtract Carry from File BTFSC

DECF

SUBDCF f,d Subtract Digit Carry from File BTFSC

DECF

TSTF f Test File MOVF

Status, Carry

k

Status, Digit Carry

k

Status, Carry

k

Status, Digit Carry

k

Status, Zero

k

Status, Zero

k

Status, Carry - Status, Digit Carry - Status, Zero

f,w z f,f

f,d z Status, Carry

Status, Digit Carry - Status, Zero

Status, Carry - Status, Carry - Status, Digit Carry - Status, Digit Carry - Status, Zero

Status, Zero

Status, Carry

f, d z Status, Digit Carry

f, d z f,f z

Page 24: A1 A Beginners Guide to the Microchip PIC

To modify software to run on a 16Cxx in place of a 16C5x1 the code needs to be changed from:

'MOVLW OFH ; sets port a direction to upper nibble TRlS PORTA ; outputs lower nibble inputs MOVLW 07H ; sets rtcc 1256 internal clock OPTION

to BSF RPO ; sets up page 1 o f registers MOVLW OFH M O W F TRlSA MOVLW 07H M O W F OPTREG BCF RPO ; restores page 0 o f registers

Internal Registers

Even though some of the registers are common to each PIC, their position in the register map may vary. This is also true of the spare registers whose beginning and end addresses change from product to product.

See programmers card in back of this book or Microchip Data Book for details.

Status Register

This register contains all the arithmetic status of the ALU, the Reset status and the Page select bits. The contents of the Status register are updated after certain instructions which modify the W register.

Some instructions do not update the Status register (SWAPF ( DECFSZ, NOP etc.) - see full l is t in programmers card.

When examining the Status register, use BTFSS and BTFSC commands to look at individual bits as these commands don't effect the Status register. When writing to the register, use the BSF, BCF and MOWVF commands. e.g.

MOVLW VALUE ; load VALUE into W SUBWF TEMeF ;subtract VALUE from TEMPstore result in TEMP BTFSS - Z ; test status Zero to check if result is 0 GOT0 NOTZERO ; resulto0 GOT0 ZERO ; result = 0

Register - STATUS

Register address 03H - bits are Readwrite with the exception of TO & PD

bit 7 16C5x PA2 16Cxx IRP RP1 RPO

- Zero bit 1 if result in w = zero

- Power Down bit set to 1 by power up or CLRWDT set to 0 by SLEEP Time Out bit set to 1 by power up SLEEP or

I

CLRWDT set 0 by WDT timeout

Program page for C5x family Register page selection on Cxx

, Spare bits on C54 & C55

( Program Address Area) (Data Register Page) = Page 0 (000H - 1FFH) (OOH - 7FH) = Page 1 (200H - 3FFH) (80H - FFH) = Page 2 (400H - 5FFH)

1 = Page 3 (600H - 7FFH)

Spare readlwrite on C5x series, Indirect address bank select bit on Cxx 0 = Bank 0,1 (00 - 7Fh) 1 = Bank 2,3 (100h - 1FFh)

Page 25: A1 A Beginners Guide to the Microchip PIC

5 Software Des gn

A Carry occurs when bit 7 overflows (in an addition) or bit 0 is borrowed (in a subtraction) e.g. 1 subtracted from 00000000 gives 11 11 11 11 and the Carry bit cleared. A Digit Carry occurs when the a borrow or carry occurs between bit 3 and bit 4 in the W register. e.g. adding 1 to 00001 11 1 gives 00010000 and the DC bit set.

Lookup Tables

A lookup table is an extremely useful method for data conversion and reference, implementation with the PIC is very easy to perform.

This program converts temperature in Celsius to Fahrenheit. The Celsius value is placed in the W register prior to a CALL CONVERT, and returns with the Fahrenheit equivalent in the W register.

CONVERT ADDWF PC,F ; adds the contents o f the W register ; to the Program Counter and places ; the result in the Program Counter

RETLW .32 ;lineOreturns32Fif W=O RETLW -34 ;line 7 o f table RETLW -36 ; line 2 o f table

conversion table

RETLW .81 ; line 28 o f table RETLW .82 ; line 29 o f table

; the. in front o f the value signifies a decimal ; number

If 28 is present in W at the CALL, then this value is added to the Program Counter, the PC is then incremented by 28 steps and returns the value 81 in W.

Lookup tables can also be used for pulse width measurement where the value of the pulse width is compared with a table to determine a 1, 0 or noise.

When returning from a CALL, the value in the W register ( will not effect the Status bits. If you need to test for a 0 in

a RETLW 0, add an IORLW 0 after the CALL statement to allow an update of the Status bits.

Software Des~gn , A BEGINNERS GUIDE TO THE WIICFIOCHP PC

The following shows the use of a lookup table for BCD to 7 Segment conversion. The value to be outputted is held in register OUTDAT and the display is attached to Port B. The output data is in the format x a b c d e f g for common anode LED displays, where x is an unused bit.

MOVF OUTDA7; W ; load OUTDAT into W CALL CONVERT ; call conversion routine MOVWF . PORTB ; send it to the display

CONVERT

RETLW RETLW RETLW RETLW RETLW RETLW RETLW RETLW RETL W RETLW

ADDWF PC

8'0 1000000' B'01001111' B'OOO 100 10' B'00000110' B'01001 100' B'00700100' 8'0 1 100000' B'00007111' B'00000000' B'0000 1 100'

; add contents o f W to the program ; counter ; comp of 0 in 7 segment ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ; 7 ; 8 ; 9

Subroutine Placement

Subroutines should be placed at the top of pages. The reason being:-

PROGRAM COUNTER

These bits are set by instruction

changed by GOTO, forced to 0 by CALL

PA0 (STATUS register)

PA1 (STATUS register)

Page 26: A1 A Beginners Guide to the Microchip PIC

Since A8 is set to 0 by a CALL instruction, (or any instruction with the PC as the destination) subroutines must reside in the lower half (first 256 words) of a program page as this is the section automatically returned. If the subroutine is placed in the upper half of a page, the CALL will result in the program jumping to the called address less 256, in other words it crashes!

Long Calls and Long Goto's

Long calls to subroutines or programs in other pages can be achieved by setting the respective page bits first.

Page 0 Page 1

I I

Page 2 Page 3

The long call can be used where space is at a premium for subroutines at the top of a page. In the above diagram, the CALL loads the PC into the STACK - the GOT0 does not effect the STACK, but modifies the PC. The RETLW reloads the PC with the original contents of the STACK and hence returns to the base page.

Pulse Width Detection

This code example uses the RETLW in a lookup table to determine if a reset pulse has been sent in amongst a series of other pulses. The routine TIM-CNV converts the result of how long a signal was present on the Dl line to the type of pulse detected. This method of pulse width testing can be expanded to look for logic 1,O or noise.

In the MAlN routine, the Dl bit is tested for active low and when this occurs,

Software Des~gn . A BEGINNERS GUIDE TO THE MICROCHIP PIC

the TIMES register gets incremented for each time slice that the Dl pin is low. When the pin finally goes high, the timing routine is exited and a comparison is made to determine if the pulse detected was a reset pulse. In this case only the reset pulse was of interest.

.***************TIME M E A S U R E * * * * X * * * * * * * * * * X X X * X * * X X I

TIM-CNV ADDWF PC,F ; add W to program counter RETLW. 0 RETLW 0 ; this area is noise RETLW 0 RETLW 0 RETLW 1 ; this area is the reset pulse RETLW 1 ; to be detected RETLW 1 RETLW 0 RETLW 0 RETLW 0 ; this area is a pulse which is RETLW 0 ; too long

;******************MAIN PROG STARTS HERE****************

MAlN BTFSS PORTA,DI ; LOOK FOR START OF DATA GOT0 MAIN ; LOOP FOR START OF DATA CLRF TIMES

TIME1 INCF TIMES, F ; MEASURE DELAY LENGTH CALL DELAY ; CALL TO TIME PERIOD SLICE BTFSS PORTAID/ ;LOOKFORSTATUS GOT0 TlMEl MOVF TIMESIW ; LOAD TIMES FOR LOOKUP TABLE CALL TIM-CNV ; CONVERT PULSE WIDTH IORLW 0 ; UPDATE STATUS REGISTER BTFSC STATUSIZ ;TEST FOR ZERO RETURNED

; FROM TABLE GOT0 MAlN the rest of the program continues here

Inputs I Outputs

Before any I10 can be undertaken, the port control registers must be set up. These determine whether the port is an input or output, or in the case of

41

Page 27: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICROCHIP PIC Sofrware Des~gn

the 16C7x analog or digital.

The 16C5x series uses the TRlS command to transfer the contents of the W register to the respective port control register. It's easy to remember 1 =INPUT, O=OUTPUT

e.g. code for a 16C5x

CLRF PORTB ; ENSURE PORT IS CLEAR MOVLW OOH ; MAKE PORT OUTPUT TRlS PORTB ; DO IT

To establish a port for mixed input and output on a 16Cxx, the result could be:

CLRF PORTB ; ENSURE PORT IS CLEAR BSF RPO ; REGISTER BANK 1 MOVLW OFH ; MAKE BITS 0-3 INPUT AND 4-7 OUTPUT M O W F TRlSB ; TRANSFER TO PORT DIRECTION REGISTER BCF RPO ; REGISTER BANK 0

Input ports are read with a MOVF PORTx,W or MOVFW PORTx and data is only valid a t that moment as input ports are non latching.

Output ports are latched and written to by a MOWF PORTx.

Individual port bits can be modified with a BSF and BCF command and read with a BTFSS or BTFSC command.

Bi-directional ports need special attention when writing code. Instructions like BCF and BSF read the whole port into the ALU, execute the bit operation and then write the whole

of the ALU back to the port. Care must be observed in such circumstances to prevent erroneous data being written to the port. This is most likely to occur when a pin has its direction modified from input to output - old data would st i l l be present in the port output register.

Where a port has multiple functions as in the case of the 16C7x1 an additional register (ADCON1) needs to be set up to select analog or digital.

Software Des~gn ; A BEGINNERS GUIDE TO THE MlCR@€dilP PIC a

This register has only 2 bits 0&1 (3 bits for the 16C7314) and is at address 88H (Page 1).

It is very important to set up this register on the C7x as the default is analog inputs on reset and therefore requires modification for digital 110 port operation.

To set up PORT A as digital inputs, the following code can be used in the initialisation section:

CLRF PORTA ; CLEAR PORT BITS BSF RPO ; CHANGE TO PAGE 1 OF REGISTERS MOVLW B'00000011' ; SET UP DIGITAL BlTS MOVWF ADCON1 ; DO IT MOVLW B'0001 1 1 1 1' ; SET UP AO-A4 AS INPUTS MOWIIF TRISA ; DO IT BCF RPO ; BACK TO PAGE 0 OF REGISTERS

Lets start with a simple task - press a button and turn on a LED. The push button is on PORTA ,BIT0 and the LED is on PORTB,BITO. A full listing for the program LEDl-xx.ASM can be found on the accompanying disk.

READ1 BTFSS SWITCH ;TESTFORSWITCHCLOSURE GOT0 $-1 ; IF OPEN LOOP AND RETEST BSF LED ; IF CLOSED, TURN ON LED BTFSC SWITCH ; TEST FOR SWITCH TO OPEN GOT0 $-1 ; IF CLOSED LOOP AND RETEST BCF LED ; TURN OFF LED GOT0 READ1 ; GO BACK TO START

The $ in the GOT0 is used in place of a label and means this line, 0-1 refers to the previous line and a Q+2 means two lines further on.

A modification to the above program enables a toggle action to take place. The ON button is attached to PORTA,BITO and the OFF button to PORTA,BITl. The LED is on PORTB,BITO.

Page 28: A1 A Beginners Guide to the Microchip PIC

READ1 BTFSS SWITCH1 ; TEST FOR SWITCH CLOSURE GOT0 $-I ; IF OPEN,LOOP AND RETEST BSF LED1 ; IF CLOSED, TURN ON LED

I BTFSS SWITCH2 ; TEST FOR SWITCH CLOSURE GOT0 $-I ; IF OPEN, LOOP AND RETEST BCF LED1 ; TURN OFF LED GOT0 READ1 ; GO BACK TO START

If the software makes use of successive operations to the I10 ports, it must be remembered that a port is read at the beginning of an instruction cycle and a write is at the end of an instruction cycle.

Care must be taken if a read follows a write on the same port ( as time should be allowed for pin voltages to stabilise. The addition of a NOP or any other.'non port' instruction can

help eliminate any potential errors.

Multiplexed Inputs

To enable I10 expansion, there are a number of options available.

If extra processing power is needed, then use a Slave PIC to communicate with a Master PIC. This adds 110 and reduces the processing requirements on each processor. You can get many PlCs communicating well, but be warned, the debugging of such a system is a nightmare.

Alternatively you can add additional I10 lines in the form of the 74HC244 (Octal Tri-State buffer) and 74HC373 (Octal D-Type Transparent Latch). This has been successfully used on a production line tester where 32 110 lines were required to interface to a PLC 6 relays, a stepper motor and 3 opt0 isolated mains feeds - all connected to a 16C55!.

Interfacing is relatively simple. With Port A connected as the control to the 74HC devices, Port B can be used as Inputs and Port C as Outputs.

Alternatively all the lines from the buffers andlor latches could be connected to Port B with the software controlling both the latcheslbuffer selection and the port direction control register. This method of I10 expansion could be used with the 16C54 where the I10 is expanded to 32.

Software Design f

MOVLW OFH ; enable OUT4 & OUT8 ; inputs are active low, outputs ; are active high

M O W F PORTA ;doi t CLRF PORTB ; clear PORT B and latch outputs MOVLW 03H ; set all I10 inactive MOVWF PORTA ; do it

I10 EXPANSION USING EXTERNAL CHIPS

The following example has been used to measure the phase angle, and hence the output power of a light dimmer with respect to a mains reference. This example uses only one half cycle during testing and both inputs are fed via opt0 isolators. The delay called allows a 0 to 100% (0 to 64H) output measurement of power and will be determined by the clock speed.

; ***********PHASEANGLE MEASURMENT******************

; RETURN VALUE IN HEX IN REGISTER 'POWER' IN RANGE.0 TO 64H ; CALLS DELAY - a time intervals to give 100 steps in half a mains cycle this ; delay will be dependant on the clock speed of the PIC

Page 29: A1 A Beginners Guide to the Microchip PIC

ANGLE CLRF POWER ; PRELOAD 100 PERCENT MAlN BTFSS PORTB,REF ; HOLD AND WAIT FOR

; REFERENCE VIA OPTO ' GOT0 MAIN ; CLEAN EDGE

MA2 BTFSC GOT0 6 TFSS

INCF CALL B TFSS GOT0 RETLW

PORTB, REF MA2 PORTB, TEST

POWER, F DELAY PORTB, REF MA2 0

,-TEST FOR BIT ; LOOP ; TEST FOR DIMMER OIP ; VIA OPTO ; INCREMENT DIMMER REG ; WAITA WHILE ; CHECK FOR END OF CYCLE ; LOOP

RAM resetting and clear

The following program clears file registers 08H to 1FH i.e. all the spare registers. The program uses the File Select Register and the Indirect Addressing Register

MOVLW 8 ; move literal 8 into W M O W F FSR ; move the value 8 into

; the file select register (4) LOOP CLRF INDADD ; clear the contents o f the

; file pointed to by the file select register INCFSZ FSR, F ,- increment the FSR and store the

; result back into the FSR GOT0 LOOP ; repeat until all files are cleared

** the program continues here **

This addition to the start of a program is highly recommended for new programmers. If using an ICE, the old register values may st i l l be displayed - this does not give a

true picture as a program is stepped through.

Reset Vectors

After a reset has occurred, the PIC sets the Program Counter to a pre-set value. This is needed to ensure you have a known program start point.

The Program Counter reset addresses are :-

PIC Reset Vector

16C54, 16C55, 12C508 1 FFH 16C56, 12C509 3FFH ? I

16C57 7FFH 16C58 7FFH 16Cxx, 12C67x OOOH

Use the following piece of code to clarify the reset vector and hence your starting point. This ensures that when the PIC resets, it knows where to go and what to do.

For the 16C5x family, use this as the reset routine:-

ORG lFFH ; change this value for PIC used GOT0 INIT ; specifies where to start program

starts here*************** I

ORG 0 ; The program memory start address INIT ; the actual start of the program.

For the 16Cxx family, use this as the reset routine:

ORG 0 ; the reset point INIT ; the actual start o f the program.

Failure to add these lines can cause the ICE to flag up an error and the program to start at the beginning of the subroutines instead of the initialisation sequence.

Page 30: A1 A Beginners Guide to the Microchip PIC

b BEGINNERS GUIDE To ME MICROCHIP PIC c & 7 A BE GUDE TO THE MCFIOCHIP PIC I

Bit Test from the RETLW

The RETLW command does not affect the status register, so in order to determine if the value passed from the subroutine is a 1 or 0 for example, follow the CALL statement with an IORLW 0. This will OR 0 with the contents of the W register, but more importantly, update the Zero bit in the Status register.

TMRO Interrupt uses - 16Cxx only

The TMRO interrupt can be useful when handling pulse strings coming in from outside sources - motor speed controllers for example. The interrupt occurs when the TMRO overflows from OFFh to OOH. By preloading the TMRO, the time interval before the overflow occurs can be varied. This can be especially useful in applications requiring precise timing intervals where the internal clock can be used as the TMRO source (TIME4.ASM).

An application using the TMRO interrupt could be a watering system where a flow sensor feeds i t s pulses into the TMRO input, via the prescaler to average the flow, and into the RTCC register. If a 16C71 is used, then an input from a potentiometer can be used to change the preload value to the TMRO and hence varying the metering factor for a water valve - see PIC Cookbook Vol 2 for full circuit and software.

RTCC (Real Time Clock Counter) - TMRO

The TMRO is clocked by either an internal or external signal. External signals are buffered by a schmidt to reduce the likely-hood of false counts. For applications such as speed control, rate indicators or frequency counters, use the TMRO with an external clock feed. The internal clock feed to the TMRO can be used as part of a Real Time Operating System (RTOS) is a piece of software which handles multi-tasking applications such as data comms.

The TMRO can be configured with a pre-scalar to average or slow the inputted signal to a more acceptable rate for the software to handle.

Resetting the TMRO to zero is accomplished with a CLRF TMRO instruction, the pre-scalar will also be cleared. The pre-scalar is also cleared with a MOWF TMRO or BSF TMRO, 2.

Configuration of the TMRO is via the OPTION instruction on the 16C5x family and by writing directly to the Option Register (81 H) on the 16Cxx. The Option Register has 6 control bits associated with the TMRO and are best shown:-

bit 6 5 4 3 2 1 0 PRESCALER register RBPU RTS RTE PSA PS2 PSI PSO RATE

0 0 0 2 0 0 1 4 0 1 0 8 0 1 1 16 1 0 0 32 1 0 1 64 1 1 0 128 1 1 1 256 Prescaler Assignment 0.. TMRO 1.. WDT TMRO Signal Edge Increment 0.. Low - High on TMRO Pin 1 .. High - Low on TMRO Pin TMRO Signal Source 0.. lnternal from CLKOUT 1 .. Externallon TMRO Pin Port B pull-up - 16Cxx only 0.. enabled 1.. disabled

The TMRO allows accurate timing or event counting to be carried out while programs are running.

This example for a l6C5x illustrates how the TMRO can be used when called as a subroutine with a value in W indicating the total delay. Modification of the bit test on the TMRO at label LONG2 will change the length of the delay loop as will changing the TMRO prescaler.

Page 31: A1 A Beginners Guide to the Microchip PIC

INIT MOVLW 8'1 00001 11' ; TMRO PRESCALER I256 OPTION ; 256uS PER COUNT GOT0 MAIN

;******* LONG DELAY I6mS * VALUE IN W REGISTER

LONG CLRF MOWVF

LONG2 BTFSC GOT0 CLRF D ECFSZ GOT0 RETLW

TM RO ; CLEAR TO START COUNT ; USE THIS REGISTER TEMPORARILY TMRO, 5 ;TEST RTCC BITS 64*256uS = l6mS B- 1 TM RO ; YES, SO CLEAR RTCC COUNTF ; DECREMENT UNTIL ZERO LONG2 0

If the prescaler is used with the TMRO, it can't be used simultaneously by the Watch Dog Timer. The prescaler can be switched between WDT and TMRO under software control.

MO VL W B'xxOxOm' ; 1 SELECT INT CLOCK AND PRESCALER OPTION ; 2 IF NEW PRESCALER VALUE IS 000 OR

; 3 001 THEN SELECT ANY OTHER ; 4 VALUE AS TEMPORARY

CLRF TMRO ; 5 CLEAR TMRO AND PRESCALER MO VL W B'xxxxlxxx' ; 6 SELECT WDT BUT NOT PRESCALER OPTION ; 7 D O I T CLRWDT ; 8 CLEAR WDT AND PRESCALER MOVLW B'xxxxlm' ; 9 SELECT NEW PRESCALER VALUE

Lines 1 & 2 are only required if an external TMRO source is used. Lines 7 & 8 are necessary only if the desired prescaler value is 000 or 001.

This method of changing between TMRO and WDT avoids a RESET condition.

Watch Dog Timer (WDT)

A4lTOCKI

[Xt TOCS PSA TMRO

A WDT ENABLE INTERRUPT

O N OVERFLOW (1 6Cxx)

I I

PRESCALER l w A ; ; p G t j p s A H ~ l (pso-psz) 1 NOTE

BlTS PSA. TOCS AND PSO-2 ARE IN THE STATUS REGISTER ?

WATCH DOG TIMEOUT

Ft-3 TIMER 0 AND WATCHDOG TIMER I

errors in the software or external electrical spikes. The WDT provides a type of heartbeat to the PIC in that if you don't clear the WDT register a t regular 4.9 intervals, it forces the PIC to reset.

This is an excellent feature and comes into i ts own for applications such as security systems where you can't afford a lock up on the main control panel.

& Products that have to conserve power and only need to be turned on

I periodically also benefit from the WDT for example a pocket pager might

ei only require a 10% on time to successfully operate.

Configuration of the WDT is via the OPTION instruction on the 16C5x and

I 12C50x family and by writing directly to the Option Register (81 h) on the 9 16Cxx. The Option Register has 4 control bits associated with the WDT and

are best shown:-

The purpose of the WDT is to help prevent the PIC, or any other processor from getting latched up into a loop. This can and does happen through

Page 32: A1 A Beginners Guide to the Microchip PIC

bit 3 2 1 0 PRESCALER register PSA PS2 PSI PSO RATE TIMES (APPROX)

- Prescaler Assignment * 0.. TMRO 1.. WDT

The remaining bits in the Option Register are associated with the TMRO (Real Time Clock Counter). The WDT has a nominal time-out period of 18mS at 20 deg C and a 5V supply, however, if the supply voltage is outside 5V or the temperature is anything other than 25C, then the time will vary. See the data sheet for guidance of time versus temperature and voltage. By use of the pre-scaler bits in the Option Register, the time-out period can be extended up to 2.35. The WDT is cleared or reset with a SLEEP or CLRWDT command. The software therefore has to issue either of these commands to prevent the WDT from causing a Reset.

e.g . MOVLW B1OOOOO1 1 1' ; TMRO PRE-SCALER 1256 OPTION ; WDT NO PRE-SCALER

MAIN CLRWDT ; CLEARS WATCHDOG EACH TIME ; PROGRAM PASSES THIS POINT

For secure or safety critical code include only one CLRWDT instruction in the main loop, as the more CLRWDT instructions there are, the less effective it will be.

When a reset is generated, two bits in the Status Register indicate what caused the reset. These bits are TO and PD (Time Out 81 Power Down).

TO PD Reset caused by I

I

0 0 WDTwake-upfromSLEEP 0 1 WDT time-out not during SLEEP 1 0 external reset from SLEEP (WDT off) 1 1 Power up condition

By examining these bits immediately after a reset has occurred, the program can determine how to react and where to branch. e.g.

INIT BTFSC STATUS'TO ;TESTTIMEOUTBIT GOT0 SCAN ; NOT SET SO WATCHDOG TIME-OUT -t

; ELSE FIRST TlME POWER UP

MOVLW B1OOOO1 1 1 1' ; SETUP PORTA TRlS PORTA ; ALL INPUTS

It is important to ensure applications which do not use the ( WDT but are put in a SLEEP mode, do not have the WDT bit

set during device programming. It is easy to forget when programming a number of associated products like a transmitter and receiver, that the receiver needs a WDT to prevent lockup but the transmitter needs only to be activated by a button press. In this case if the transmitter has i t s WDT bit programmed, the program just loops and never manages to transmit.

e.g. ORG OOH

START CALL INIT CALL DELAY ; if DELAY is> WDT time-out period CALL SCAN-KEYS ; the program will just loop back MOVWF GP ; to START and never get to BTFSC GP,BITO ; the SLEEP command BCF PORTA, LED SLEEP

In noisy environments it is advisable to update the OPTION ( and TRlS registers at regular intervals.

Page 33: A1 A Beginners Guide to the Microchip PIC

~BEGINNWS GUIDE TO THE MICROCHIP PIC Software Design

I : A BEGINNERS GUIDE TO ME MICROCHIP PIC

12C50x 16C5X

RESET

(MAKE THIS I ; I A NO,,

INTERRUPT INTERRUPT EXECUTED

PROGRAM RESETS JUMPS TO

PROGRAM HANDLE I CONTINUES k INTERRUPT I The Stack

On the 16C5x and 12C50x family there is a 2 level stack. When a CALL is made the current value of the program counter is placed in STACK 1. A RETLW transfers the value in STACK1 back to the program counter.

If another CALL is made without a return, the value of STACK 1 is transferred to STACK2. If a further CALL is made, STACK 2 gets overwritten by STACK 1 and you have lost your place in the software.

In practice this allows you to make one CALL from within a CALL. It is easy t o forget how deep into the stack you have gone when entrenched in heavy programming or disturbed by an interruption. This potential bug is not picked up by the Assembler and can lead to no end of development problems. The ICE or simulator can detect a stack overflow or underflow.

A method I have adopted to overcome this is to use lumps of BlueTack. Besides giving me something to take my frustration out on, I move a lump from keyboard left t o right when I make a CALL. I know instantly if I have exceeded the stack depth or not returned from a CALL as only with the RETLW statement do I move the lump back from right to left.

CALL

P C RETLW xx STACK 1

STACK 2 + >2 C A L L S PROGRAM C R A S H E S

f C A L L \ or INTERRUPT +

RETLW xx R E T U R N

STACK 2

STACK 3

STACK 4

STACK 5

STACK 6

STACK 7

Substitute anything available to hand in place of Blue-Tack.

The 16Cxx and 12C67x families are provided with an 8 level stack so there should be no problems in program crashing due to stack overflow unless the programming has a major bug. As with the 16C5x family, a CALL moves into the stack and a RETLW, with the addition of RETURN and RETFIE, brings you out.

lnterrupts

lnterrupts are used to alter the normal flow of a program to perform some other function e.g. to pause data transmission when a message is received on a data comms system.

All

Page 34: A1 A Beginners Guide to the Microchip PIC

lnterrupts take the form of two distinctive types - software and hardware. The software interrupt is used in circumstances where the microcontroller has no inbuilt interrupt capability - this is called polled software. On the other hand, the hardware interrupt has al l the hooks and control mechanism built into the microcontroller.

A polled interrupt has an advantage over hardware interrupts in that you know the status of all the registers etc. when an interrupt occurs, however, the interrupt will only be accessible to the outside world when you poll the port. On the other hand, the hardware interrupt acts instantly.

Software or Polled lnterrupts

The PIC16C5x family do not have a hardware interrupt capability and will need to use polled software.

FUNCTION 1

4

4 POLLED SOFTWARE INTERRUPTS

The following example is used to monitor a change on a port set up as an input and will cause the program to jump to a different subroutine if a change of state is detected, otherwise it will continue in the main loop. The port is initially read and the contents stored in a register. When the POLL routine is called, the current port status is compared with the previous value and if a change has occurred, a lookup table determines where the program will branch to.

MAlN BTFSS GOT0 BTFSS GOT0 BTFSS GOT0 BTFSS GOT0 GOT0

PORTAO ; Test input and if low then INPUT-1 ; branch to label INPUT 1 PO RTA, I INPUT-2 PORTA,2 INPUT2 PORTA,3 INPUT-3 MAIN ; none of the above so look again

Interrupt Driven Software

The 16Cxx devices have inbuilt interrupts but can also use the polled technique if required. lnterrupts are a very useful feature for microprocessors as they allow external events to interrupt the normal software flow. This results in the execution of code for a specific purpose i.e. in communications software an interrupt from the input pin causes the software to decode the incoming data.

INTERRUPT PROGRAM SOURCES

FUNCTION

INTERRUPT DRIVEN SOFTWARE

The priority of interrupts is determined by the order in which ( the interrupt flags are read in the interrupt handler.

The hardware interrupt can be configured to cause the program to jump to another section of code when either an internal or external event occurs. In the case of the 16C71, interrupts can be selected from 4 sources:-

Page 35: A1 A Beginners Guide to the Microchip PIC

completion of an AID conversion an external interrupt from PORT B bit 0 a change in state on PORT B bits 4 to 7 TMRO overflow from FFH to OOH

The 16C84 has an E2 write completion interrupt. This is needed as the E2 write time is nominally 10mS - which equates to a lot of wasted cycles if a program is waiting for the E2 write to be completed.

Any of the above will cause an interrupt to the main software flow. Only one interrupt can be handled at any time as the first interrupt will prevent any additional interrupt actions - by clearing the GIE bit. If an interrupt occurs during an interrupt, this will only be evident by examining the interrupt flags for any further changes at the end of the interrupt routine and before issuing the RETFIE command. If any changes have occurred, the software can be looped back to the interrupt entry point where the type of interrupt is determined.

When an interrupt occurs (it can happen anytime), it is wise to save the contents of both the STATUS and W register so that the values can be restored after the interrupt has been handled. This becomes especially noticeable when an interrupt occurs during an LCD display routine - the result of the interrupt software may well change the contents of the W register and upset the information displayed after the RETFIE is executed. To get over this problem, adopt the following code into the interrupt routine. The interrupt handler need not reside at 04H providing a GOT0 is located in i t s place.

ORG 04h ; Interrupt Vector PUSH movwf W-Sa ve ; Preserve w reg

swapf status, W ; Preserve zero flag mowvf S-Sa ve ; Save the status register

; Interrupt routine ; code sits here ; not forgetting to clear any ; interrupt flags before returning from the interrupt

endint ; test here for any further interrupts from other sources

POP swapf S-Save , W ; Restore Status reg mowvf status ; without changing any bits I

swapf W-Save ; Restore W reg without I

swapf W-Save , W ; changing the status bits retfie ; Return from interrupt

Upon entering an interrupt handler, it is important to check if the interrupt is a valid one or if there are a number of possible interrupts pending, which one to service first. This is easily achieved by testing the interrupt flags in INTCON and other registers and acting accordingly.

Before an interrupt can occur, the respective interrupt ( enable bits need to be set together with the Global lnterrupt

Enable (GIE) bit in the INTCON register - see data sheet for full information.

INTERRUPT

ADDRESS

ALL FLAGS CLEARED

INTERRUPT FLAGS

DO ROUTINES IN INTERRUPT

& CLEAR FLAGS

INTERRUPT OPERATION ON 16CXX

Page 36: A1 A Beginners Guide to the Microchip PIC

Page boundaries in Program Memory and how to cross them - 16C5x family

The 16C56, 16C5718 have a program memory of 1024 and 2048 words respectively each 12 bits wide - equally divided into pages of 512 words. To address 2048 words on the 16C5718, you theoretically require an 11 bit address field but due to a 12 bit wide program memory data bus, only 9 bits of the address can be used the 3 remaining bits form the instruction.

The extra 2 bits required are found in the status register - bits 5&6. These two page select bits determine which of the four pages the program runs in. The page boundaries are 0 - IFFH, 200H - 3FFH, 400H - 5FFH and 600H - 7FFH.

To access code in another page, first set the correct page select bits in the status register, then use a CALL or GOT0 instruction to execute the move. The 9 bits following a GOT0 plus the 2 page select bits form the full 11 bits which is loaded into the program counter. The program then continues t o execute from this point. (note: the subroutines must sti l l reside in the lower half of each page.)

Any subsequent CALL or GOT0 instructions will keep the program running in that page.

An example of such a program covering multiple pages is:-

ORG OOH ; start o f the program this is page 1

BSF STATUS,BITS ; set up the page select BSF STATUS,BIT6 ; bits for page 3 CALL PAGE-3 ; call the subroutine

BCF STATUS,BITS ; reset the page select bits BCF STATUS,BIT6 ; to the first page

; continue with program here

ORG 0600H ; Page 3 PAGE3 ; the subroutine

RETLW 0 ; return back

If the program calls a subroutine in another page - as above - the current program counter value is put onto the stack. When you return from the CALL, the page select bits will still be those of the previous page -they must be modified prior to any further CALL or GOT0 statements required by the current page. Failure to do so will take you to the previous page.

Look closely at the way you write the code and location of subroutines as each CALL to another page adds at least 4 instructions to the program.

16Cxx CALLs to data tables.

Great care should be taken with CALLs to data tables outside program memory 00 to OFFh.

Take the case of a lookup table starting at 120h which is called from say address 1 IOh, upon execution of the RETLW xx statement, the program will jump back to address 11 h.

In order to ensure the program will return to the correct point in the software ( I I I h), a page selection needs to occur, as with the 16C5x series, but this time the bits are held in the PCLATH register. PCLATH holds the upper address bits for the program counter and is not automatically updated by certain instructions. In order to get over the problem of programs skipping back to the base page, the correct page selection should be made within the PCLATH registers. I

The above call then becomes:

BSF PCLATH, BIT0 ; indicating page 1 (1 00h to 1 FFh) CALL CONVERT

at which point the RETLW xx will restore the program to address 11 1 h. Remember to set the bits in PCLATH back to the correct page following the

# CALL to prevent further confusion.

AID Conversion Block

The A/D converter block on the 16C7x is made up of a number of registers to select and control the various options. As the A/D input is fed via Port A

Page 37: A1 A Beginners Guide to the Microchip PIC

(and Port E on the 16C74), there is an added requirement to select between analog and digital.

The default port configuration for the 16C7x family is ( ANALOG not digital - so ensure you set up ADCON 1 correctly.

The registers associated with the whole AID and Port A block are:-

ADCONO channel select, conversion clock, AID onloff, interrupt flag and startlend conversion

ADCONI input selection for analog or digital ADRES result of AID conversion TRlSA input 1 output select for digital selected bits PORTA input 1 output read 1 write register for digital selected bits INTCON AID interrupt enable

Below are the registers and their bit usage for the 16C71 - see data sheet for other 16C7x devices.

Register - ADCON 0 - Control and Status - address 08H - all bits are Readwrite power on reset value = OOH

bit 7 6 5 4 3 2 1 0 ADCSI ADCSO spare CHSl CHSO GOIDONE ADlF ADON

AID switch 1= on 0= off

AID Interrupt flag I = complete

Conversion StartIEnd I = Go O= Done

AID Channel Select 00: PortA 0 01: PortA 1 10: PortA 2 11: PortA 3

AID Conversion Clock 00: fosd2 01: fosd8 10: fosd32 11: internal RC oscillator

Software Des~gn 1 Register - ADCON 1 - Port A Control - address 88H - bits 0&1 are

I

Readwrite bits 2-7 not used - power on reset value OOH

bit 1 0 AO,Al A2 A3 Vref 0 0 Analog Analog Analog Vdd 0 1 Analog Analog Ref Input A3 1 0 Analog Digital Digital Vdd 1 I Digital Digital Digital

The following example illustrates the AID converting a voltage from a multiturn potentiometer connected between OV and Vcc. The voltage is fed into A0 and the binary result is displayed on Leds attached to Port B. This is only a section of a program - the full program ADC1.ASM is on the accompanying disk.

MOVLW 8'1 1000001' ; SETAID INTERNAL RC CLOCK ; CHANNEL 0, AID RUNNING

M O W F ADCONO ; DO IT

MAIN MOVLW .10 ; LOAD DELAY TIMER , MOVWF TEMP

<

DECFSZ TEMe F ; WAIT A WHILE FOR GOT0 $-I ; SAMPLE & HOLD

. ; TO SETlLE BEFORE ; CONVERSION

BSF ADCON0,GO ; START CONVERSION BTFSC ADCON0,GO ; TEST FOR END OF GOT0 5-1 ; CONVERSION

MOVF ADRES, W ; LOAD AID RESULT INTO W M O W F PORTB ; DISPLAY IT GOT0 MAlN

Page 38: A1 A Beginners Guide to the Microchip PIC

1 I

TRlSA MUX 85H CONTROL

7 6 5 4 3 2 1 0 PORTA ADCS1 ADCSO CHSZ CHSI CHSO GOIDONE ADIF A W N

I OSH I - ADCONO

AID CONVERSION BLOCK - 16C7~

16C84 - The EZ based PIC

The 16C84 has E2 (electrically erasable) memory for both program and data storage areas. The data storage area is a non-volatile storage and is in addition to the static ram data registers. In all other respects, the 16C84 behaves as any other device in the family. The advantage of the E2 over the windowed devices for development is in cost -there is no windowed 16C84. An ideal application is in alarm systems which either modify their own code or learn codes from the users - no external non-volatile memory is required t o maintain data when power is removed.

Programming of the data E2 takes approximately 10mS per byte and must follow a set procedure in order to work to minimise the chances of spurious writes. Data read takes only 3 clock cycles.

The following block diagram illustrates the structure of the registers associated with the E2 block.

To read data from the E2 READ MOVFW TEMP ; Temp holds the address

; o f ram location to read

M O W F EEADR ; Move the value into ; address register

BSF RPO ; Page 1 registers BSF EECON1,RD ; Enable read BTFSC EECON1,RD ; Wait for read to finish GOT0 $-I. BCF RPO ; Return to page 0 registers

; Data is now in EEDATA register

Writing data to the E2 has to follow an exact sequence otherwise no write takes place. Non interrupt driven example

WRITE MOVF W TEMP1 ; Temp 1 holds the address ; o f ram to write

MOVWF EEADR ; Move the value into ; address register

MOVFW TEMP2 ; Temp2 holds data to ; be stored

M O W F EEDATA ; Move the value into ; the data register

BSF RPO ; Page 1 registers BSF EECON1, WREN; Enable the write MOVLW 55H ; Must use these next 4 lines M O W F EECON2 ; in this exact MOVLW AAH ; sequence in order for M O W F EECON2 ; the data to be written BSF EECON1, WR ; Write the data BTFSC EECON1, WR ; Wait for write to finish GOT0 $-1 BCF RPO ; Return to page 0 registers RETURN

It is advisable to separate the read and write routines in case of program errors.

4

During programming, both program and data E2 can be written using a PICSTART Plus programmer.

Page 39: A1 A Beginners Guide to the Microchip PIC

Assemble Software s 9 I 9 EElF WRERR WREN WR RD

EEADR 09H

16C84 DATA E2 DATA BLOCK

Other Periferals in the PIC family.

We have covered some of the many periferals available across the range of *3

I PIC3 available from Microchip. Setting up RS232 communications, PWM, SPI and 16 bit Counters are relatively easy once you have mastered the basics of register setup and manipulation. Examples covering the use of these periferals can be found in PIC Cookbook 1 & 2 as well as Microchip Application notes.

Assemble Software

Having written the program, it needs to be assembled, putting it into a format which can be used by the PIC. The source code file is assembled using the MPASM.EXE program which is part of the MPLAB environment.

Assembling Programs

Assembling a program requires you to provide the assembler with certain information so the resulting code is compatible with the target system. Fortunately, the PICSTART Plus, PROMATE, ICEPIC and PICMASTER use the same file format.

These options can be included in the source file in a LlST statement.

e.g. LIST F=INHX8M, P=16C71, R=HEX

The most important of these is the P= which tells the assembler which processor is being targeted. If this is omitted from the source file, an excessive amount of errors will be produced - over the ones carefully inserted by yourselves -try it and see the result.

But before we can assemble a program, we need one written.

Take the example of pressing a button to turn on a LED. This program needs 3 basic building blocks - initialisation - test the switch - do something with the LED.

We need to ensure the output bits are cleared, then set up the port direction registers and finally test the input bit and depending on the condition, set or clear the output accordingly.

The flowchart for this follows with the program written along side for clarity.

Three versions of the program are included on the disk to show the differences between various processors. The files are:-

Page 40: A1 A Beginners Guide to the Microchip PIC

LEDI-54.ASM - 16C54 version LEDI-71 .ASM - 16C71 version LEDI-84.ASM - 16C84 version

Part of the .LST file produced for the 16C54 looks like this:-

0020; ********** THE PROGRAM ********** 002 1 0022 ORG 00 ; program starts here 0023

0000 OCOF 0024 INIT MOVLW OFH ; set up port a as inputs 0001 0005 0025 TRlS PORTA ; do i t 0002 0065 0026 CLRF PORTA ; clear port 0003 0066 0027 CLRF PORT6 ; clear port 0004 OCOO 0028 MOVLW 00 ; set up port b as outputs 0005 0006 0029 TRlS PORTB ; d o i t

0030 0006 0605 0031 MAlN BTFSC BUT ; test if button is pressed 0007 OA06 0032 GOT0 MAIN ; not so loop until pressed 0008 0506 0033 BSF LED ; button pressed - turn on led

0034 0009 0705 0035 OFF BTFSS BUT ; test for button release OOOA OAO9 0036 GOT0 OFF ; not so loop until released 000B 0406 0037 BCF LED ;button released - turn off led OOOC OA06 0038 GOT0 MAIN ; loop back to start

0039 0040 ORG 1 FFH ; reset vector for 16C54

01 FF OAOO 0041 GOT0 INIT 0042 0043 END ; the end of the program

Comment field Instruction

Line Number Actual Code

Memory Location

When assembled, the .HEX file used to program the PIC looks like this:-

Attempting to debug a program by examining the .OBJ or HEX file is guaranteed to get you committed.

TURN ON Fl

OFF LED v

Page 41: A1 A Beginners Guide to the Microchip PIC

,P BEGINNERS GUIDE TO THE MICROCHIP PIC D P ~ L P ioftware a t i a r a 3 r3 TO THE M~CROCMIP PIC I

Debug Software & Hardware

Development and Debug

Once the product has been designed and software written, the product needs to be debugged to eliminate all the potential problems and to fine tune the design to ensure it meets the original specification. This section of the product design can sometimes take the longest.

A number of tools are available to meet engineering as well as financial requirements.

In this section we will cover:

development tools , software simulator /

software sources technical support hardware kits debugging the product

Development Tools and Systems

Development tools fall into various degrees of function and price. The simplest development kit comprises a PC, programmer and UV eraser (not needed for the 16C84). This allows basic development using the program - try modify loop.

If code trace, breakpoint and single stepping are required or a faster development time is called for, then an ICE is needed. The ICE comes with various levels of function and priced accordingly from those not running at full speed to the ICEPIC and PICMASTER running under Windows.

PICSTART Plus This is a Windows based development environment (MPLAB) with built in assembler, simulator and serial port programmer. It can be used to develop and program any of the PIC devices from 8 to 40 pin. Approx £ I20

PROMATE CE The PROMATE CE is a universal programmer which can be used in a PC hosted or stand-alone mode. The programmer has a range of socket modules for all devices and packages and comes complete with PC software. Approx £250

PICMASTER CE This is the Windows based In Circuit Emulator with real time trace, hardware breakpoints, program step, code modify and external trigger inputs together with source level debug and on line help - uses either an internal card for standard PC's or PCMCIA adapter for laptops. Approx £ 1500

ICE PIC This is the Windows based In Circuit Emulator with hardware breakpoints, program step, code modify and external trigger inputs together with source level debug and on line help. The ICE PIC communicates via an RS232 interface to any PC. A version of the ICE PIC is also available with real time trace. Approx £550

ICE PIC JUNIOR Two version are available covering 16C5x and 16Cxx families. They have all the facilities of the ICE PIC but are supplied without case and power supply (optional extras). Approx £350 for 16C5x. 16Cxx £350 plus £99 for each additional daughter board.

MPASM The universal assembler for all the 16C and 17C devices. Various Intel HEX formats are available as well as an output for PRO MATE, PICSTART Plus, ICE PIC and PICMASTER tools. Supplied as part of MPLAB.

MPSlM Available as either a DOS based simulator or as part of MPLAB. It has unlimited breakpoint facility and trace to file and single step is provided. The DOS version needs a stimulus file to run. Supports all 16Cxx and 17Cxx devices.

f uzzyTECH Fuzzy logic development tool running under Windows. Full simulation and integration of code into existing products. Two versions are available - explorer and full (dongle protected). Both versions come with a development board and tutorial.

Bulletin Board Microchip BBS accessed via local telephone numbers to obtain all the latest product information, application notes, development

Page 42: A1 A Beginners Guide to the Microchip PIC

software, silicon release notes and special interest groups to discuss your problems with other users or Microchip engineers. There are also some Internet mailboxes running Microchip product discussion groups.

SEEVAL Serial EEPROM development board which performs E2 read and write functions for test and development. This is ideal for solving those awkward problems with EEPROM applications.

Total Endurance Serial EEPROM endurance modelling. The software is supplied in both DOS and Windows formats to help predict life expectancy for products incorporating E2 technology. The calculations are based on user defined parameters and outputs the results in PPM or FITS.

A full l i s t of Microchip order codes is given at the back of the book.

MPLAB

Instalation of MPLAB.

To install MPLAB, insert disk 1 and run SETUP from the run box or file manager. When instructed insert disk 2 and answer any questions. An additional file BOOK3.EXE contains code examples in a compressed format and is on disk 2. Copy this file into your PIC working directory and run the file to extract the programs.

Starting MPLAB

Double click on the MPLAB icon. The first thing to do is t o select the correct device from the PIC range to simulate. Move the cursor on to OPTIONS and press the left hand button. This will open the usual Windows pull down menu. Choose DEVELOPMENT MODE. Clicking on this option will give a small window in the middle of the screen. If the check diamond for MPLAB- SIM is not dotted then move the cursor in to the diamond and select it now. Select a controller by hitting the down arrow at the right hand side of the processor box. From the list presented select the appropriate controller, the up and down arrows will offer you more options. Select the PlCl6C54 from this l is t and press the RESET box. Wait a few seconds for the software to load the appropriate defaults.

Debug S o h a r e & rlaroware A BEGINNERS GUIDE TO THE MICROCHIP PIC

Controller setup E

Click on the OPTIONS button again, then on the PROCESSOR SETUP option, then HARDWARE. This will open up a window that allows selection of options that are available to the designer when devices are being programmed. These options include the assignment of I10 functions, clock source and whether we have the watchdog active or not. For the moment lets select NONE from the WDT box. Click on OK to accept the setup.

Beneath this line is a tool bar. This tool bar gives access to the commonly used functions with out having to go through the menus. The button on the extreme left toggles through the four tool bars available to us. Toggle through the l ists until a short tool bar with green icons appears. This is the build and make tool bar and allows us to compile or assemble our code. If we hit the left hand button again we see a mixed button offering some editing utilities and some debug functions. Move round again to the edit tool bar and again to the debug tool bar.

Code Writing

Select FILE from the top line then NEW SOURCE. This will open up a blank screen called UNTITLEDI. Now cycle through the tool bars until you get to the edit tool bar. ( two clicks round from the green short tool bar )

Some assembler issues

The assembler is by default, case sensitive, so 'LOOP-1' is different to 'loop-1'. The instructions can be in upper or lower case but you must be consistent with labels and names. Comments are preceded with a semicolon ';' and can start anywhere on a line. Anything after a semicolon is ignored. Use lots of comments as it will make the code easier to follow when you have to change it in years to come.

........................... I

;*** DEMO CODE 1 ........................... I

; LAST MODiFlCATiON DDIMMIW ; AUTHOR GORDON MACNEE

Page 43: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICROCHIP PIC

LIST P= l6C54, F=INHX8M

INADD EQU RTCC EQU PC EQU STATUS EQU FSR EQU PORTA EQU PORTB EQU

#DEFINE Z #DEFINE C #DEFINE DATA #DEFINE CLK

; RAM registers COUNT EQU SFT-REG EQU

OOH ;Indirect A DDress register 01 H ;RTCC 02H ;Program Counter 03H ;STATUS register 04H ;File Select Register 05H ;Port A 110 register 06H ;Port B 110 register

STATUS,2 ;Zero flag - b i t 2 o f STATUS reg STATUS,O ;Carry flag - b i t 0 o f STATUS reg PORTA,O PORTA, 1

07H ;general purpose RAM 08H ;general purpose RAM

ORG 00

;set up the 110 pins

COLDSTART ; labels must start in the first column ; instructions must NOT start in the first column

CLRF PORTA MOVLW B1OO1lllOO' TRlS PO R TA

;load COUNT with the number o f bits to shift out MOVLW 08H MOWVF COUNT

LABEL-1 BCF CLK ; clear clock line BCF DATA ; clear data line RLF SFT-REGIF; rotate contents o f register to place msb in carry BTFSC C ; test carry b i t BSF DATA ; is set then set data line BSF CLK ; set clock line high

DECFSZ COUN7;F ; count down bits to be sent GOT0 LABEL-1 ; go again unti l all sent

;when we get here we have shifted out 8 bits o f data and ;can move on to the next operation

GOT0 COLDSTART

;the last thing we do is tell the assembler that we are finished ;NOTE: all assembler directives must be tabed in

END

ORG 1 FFH GOT0 COLDSTART

Now that we have typed all this in lets save it. Go to FILE on the top line and select SAVE AS from the list. Lets call this file EXAMPLE1.ASM and make sure that you remember which directory you are in. The file extension of .ASM is what the assembler will look for as a default.

Defining the project

This operation will tell MPLAB which files we wish to work with under a project name. Select PROJECT on the top line and click on NEW PROJECT from the options offered. This opens a window that offers a number of default names and settings. Check that you are happy where the system is saving files on your hard drive and edit the boxes if you are not. Then click on OK to move on to the next window, which prompts you for the files being used in any given project. We only want EXAMPLE1 .ASM so click on this file and add it to our list of project files. Then select OK again.

To see what is happening within the PIC, go to the WINDOW option on the top line and click on it. This will give us a pull down menu. Now click on the following items, the menu will disappear with every selection so just reopen it by clicking on WINDOW again. Open :- Program Memory Window Special Function Register Window

Page 44: A1 A Beginners Guide to the Microchip PIC

File Register Window Stopwatch

Already the screen is beginning to look cluttered so to tidy things up by resizing the open windows. Click within the Special Function Register Window and then move the cursor to the vertical edge of the box and when the cursor changes to a horizontal double arrow head press and hold down the left mouse button and move the edge in until you are happy with i t s size. This procedure can be repeated for the horizontal edge and then repeated for the other windows as well. To move a window click on the top bar and with the button still pressed drag it to a more convenient area of the screen. For those already well versed in Windows this is second nature.

The Program Memory Window shows the instruction list that we expect the controller to execute. Currently this is all OFFFH with is the unprogrammed state of a device. This looks like an XORLW OFFH instruction to the controller. This display will change when we enter some code. The Special Function Register Window displays the registers that are not general RAM, so we can see the Working register, status register, the tris register and I10 pins in this window along with other registers that will be of interest. The File Register Window displays all of the registers available including the general RAM locations. The Stopwatch gives timing information based on the frequency we are running our application. The system will work out from the number of steps taken how long blocks of code take to execute.

Select PROJECT on the top line again, and this time lets SAVE our project. This means that we can load in this setup when ever we have had to leave MPLAB.

Now lets present our work to the assembler. We do this by leaving the editor tool bar and looking for the make tool bar. So step through the tool bars until we get to the short green one and step through each key until you get to the button for BUILD ALL. Click on this one and we will present our file to the assembler. Hopefully the assembler came back with a green bar and a message saying 'success, no errors'. If it did not then click on OK and a message box will appear. Now click on any message that starts 'Error . . . I and this will take you to the line that is causing the problem. Correct the problem and resubmit the file. It will be automatically saved before it is assembled. The other boxes offer options to control and

manage other aspects of typically larger projects and are fully described in the help files.

Starting to Simulate

So we now have a .ASM file and a .HEX file. So lets try out the code. Cycle through the tool bar until you get to the debug tool bar, ( the one before the short green bar ) and click on the RESET PROCESSOR button ( remember that the software tells you what the button does down in the left hand side of the screen ). This simulates a power up situation or a reset from some other source. This will highlight the line that will be executed next. In this case the instruction a t COLDSTART. To move through the code one step at a time we can hit the button that has two shoes on it ( 4th button in ). As we do this we will see the highlight moving through our code and any registers that are modified by the instructions will change colour and reflect the operation of the instruction. Thus we can slowly move through our code seeing what the controller will eventually do.

The other buttons have functions of - the green light is the go button and will start execution of code until we halt it or it encounters a breakpoint - discussed later, the red light is the stop button and will stop the simulation and update all the registers. The 5th button will perform a single step unless the step is a subroutine. If it is a subroutine then it will run throuqh the subroutine and stop on the next instruction after the call. Next we have the reset button. One other of immediate interest is the 9th button that will create a new watch window. We have seen how to display all the RAM registers in the PIC and how to show the special function registers, but what about those registers that you have named and are of particular interest now. Lets click on the 9th button -this will open two new windows. Ignore the one in the background as this will look after itself. The one in the foreground is prompting us to enter those registers that are of special interest. Click on COUNT the on ADD and notice that COUNT has been added to the window in the background. Now scroll the l is t down and click on SHIFT-REG and add it to the background as well. We can return and add more values to this watch window or open more watch windows, which ever makes more sense. Click on OK and move the watch window to a convenient area of the screen. This is where most of us are looking through the magazines for a 21" monitor. If we step through the code as is then we will notice that we do not load SHIFT-REG with any data. This

Page 45: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICROCHIP PIC DeDug Software & hardware Debug Sohare & Hardware , A BEGINNERS GUIDE To THE MICROCHIP PIC^ would normally be done by the application preceding this code segment, but we can modify any of the registers whilst in simulation by double clicking the lefthand mouse button when pointing to the register in one of the watch windows.

Lets load SHIFT-REG with some data. Double click on SHIFT-REG in the WATCH-1 window. Then in the DATNOP CODE section of the box that opens type 33. Then click on WRITE. This has loaded SHIFT-REG with 33 hex. Now we can see the effect on the I10 pins A0 and A1 as we step through our code. This feature also allows us to skip over long delay routines by seeing that they work once then loading the registers used with much smaller delay values. We can also use this box to modify code but there are nicer ways of doing this. We can see how long this will take by resetting the timer at the start of the shift and at the end. This is where breakpoints can be used. If we want to run the simulation as fast as we can up to a given point and then halt we set a BREAKPOINT at the instruction we want to stop at. To do this click on the line of code that you want to stop at. Now click the righthand mouse button and a small menu presents itself. The two of use are the RUN TO HERE button and the BREAKPOINT button. If we click on the breakpoint option then we are rewarded with a line of code that turns red. RESET the controller and hit the green button on the button bar. The controller will simulate the code until it encounters this breakpoint at which point it will halt and update the display. This allows us to whiz through code we are happy with and concentrate on blocks that are causing problems. As and when we encounter code that needs changed, the most secure way is to edit the .ASM file on screen then flick through to the green button bar and reassemble the code. This means that whatever modifications you have made to the code to get it working are safely stored in the assembler file.

We have now seen how to inspect the PIC internals and we can see what is happening on the I10 pins, but how do we simulate a user pressing a button? There are four ways of introducing external stimuli. The most useful of which is Asynchronous Stimulus. Go up to the pull down menu line of the MPLAB window and select DEBUG, then select Simulator Stimulus and from the menu that that presents, select Asynchronous Stimulus. This will open up a dialog box with 12 buttons. We must now assign a box to a pin and function. Click the lefthand mouse button on one of the buttons, and a message will appear. This message, in the way of all error messages,

gives no information and is best ignored. Click on OK. This will leave the chosen button highlighted. We can now press the righthand mouse button and for the l i s t that appears select ASSIGN PIN. We can select any pin from the l is t that is offered. Repeat the steps above to get back to that menu and select the function that best simulates the hardware you will be using. The most useful is normally Toggle.

Now when we are running code or single stepping through we can click on this button and the selected I10 pin will toggle. Other options for presenting stimuli i s to use a stimulus file that will change the state of I10 pins at specified times or steps. This is most useful for testing such code as software UARTS or any other serial bit streams. We can also present a similar file that specifies a value to be loaded into a file at a specified time of step count. Great for simulating N D conversions and the like. More details of how to present these files is covered in the simulator help files and manual. Altogether offering a cost effective software test suite.

The above is a GET YOU STARTED introduction to the simulator. Many other features are explained in the online help and in the manual. Happy debugging - Gordon McNee.

PIC Project Boards

A range of Project Boards are available to show how the PIC works and how to interface to the outside world. Designed for students and engineers to form the core of a training course or they can be used as a quick hardware development facility for code development. Use as part of a training program or structured course it is best accompanied by a PIC START Plus or similar programmer. The user will need some reprogrammable versions of the PIC for development purposes or an ICE.

Contact your Distributor for details on these and other products available from Bluebird Electronics. A full product l i s t is given in the back of the book.

Page 46: A1 A Beginners Guide to the Microchip PIC

Program the PIC

Programming I

At last, the product is designed, debugged and ready to be fully tested. This is an important part of the development process as you will now see the product working on i t s own - similar to a baby walking without assistance for the first time.

We will cover programming the PIC, code protection, serialisation and use of windowed PIC'S.

Programming the PIC

Having written your source code, successfully compiled it and tested it with a simulator or ICE, the next stage is to program a PIC and test your theory.

A number of programmers are available on the market - some dedicated, others general purpose.

Of the dedicated models, the easiest to work with is the PICSTART Plus from Microchip.

The universal programmer from Microchip - PROMATE CE - is a standalone unit with some intelligence built in. Object files can be downloaded to the programmer, stored, edited and taken to your customer should onsite software upgrades be required. Serialisation can also be undertaken on bulk programming.

The programming process is simple enough

Power up programmer Load programmer software Set defaults Load .OBJ or .HEX file Check it's the correct product Check it's blank

Page 47: A1 A Beginners Guide to the Microchip PIC

c Program the PIC

Program Verify Test.

From within MPLAB, select PICSTART PLUS on the top line to enable the programmer. Ensure the PIC indicated matches the one the code has been developed for. Select PROGRAM and wait until informed OK. Remove the PIC and test in your board.

Code Protgction

Within the PIC, there are a number of special registers not accessible by your program. The registers hold information on the oscillator configuration, an identification number, if watchdog timer is active and whether code protection is enabled. The' memory locations are programmed by a PICSTART PLUS or similar programmer. The default setting for code protection is disabled.

If code protection is enabled, a 0 is programmed in the CP memory location which inhibits the program code from being read. All memory locations above 040H are also protected from reprogramming. Memory locations 0 to 3FH can still be programmed together with the ID and configuration fuses.

ID and Configuration fuses can st i l l be read after code protection has been activated.

There are two ways to check the contents of a PIC after programming if Code Protection is required.

1 Program a PIC as normal, verify and then program the CP bit. This ensures full verification to the programming process but adds an extra stage.

2 Program a 'Master' PIC, verify and program the CP bit. Read back the contents of the PIC and this gives you a checksum per byte.

eg 008 <-the last character for each memory location

Program me PIC sA /3EGINNEFS GUIDE TO .TN MIGWCHIP PIC

Program the PIC'S with CP enabled and then verify against the 'Master' , device.

If not using a Microchip programmer, check there is no code corruption when CP is enabled. Some third party programmers had an occasional problem with this.

Serialisation

The PIC can be programmed with a random or sequential identification number which can be used by the software.

By allowing a 'hole' in the software (in the form of retlw Offh) for each of the number locations to be used up to a maximum of 8. The PRO MATE software has the ability to firstly create the required file and then use that file to insert the numbers into the 'hole' during the programming phase.

This feature is of great benefit for programming alarm or transmitter based products where each unit has i t s own unique serial number or code. Another application could be where a serial number is required for traceability and is outputted by the product upon request.

The retlw Offh 'holes' can be placed anywhere in the lower 256 words of any program page and be in a continuous block. The following example shows the use in a 16C54 device.

num I num2 num3

in it

main

org 0

retlw Offh ; first number retlw Offh ; second number retlw Offh ; third number

; initialisation

call numl ; returns with the contents in w ; to be used in the program

rest o f program

Page 48: A1 A Beginners Guide to the Microchip PIC

Program the PIC

Org Iffh ; reset vector goto init ; starts program after reserved block end

Windowed Device Development

Caution must be observed when developing with windowed devices.

Semiconductor devices are basically light sensitive and depending on initial conditions set within the PIC, predictability or randomness can result. The standby current of a PIC in the sleep mode will also increase if light gets at the chip.

A semiconductor memory can initialise into one of two states - 1 or 0. Light falling on the silicon can cause a bias towards on'e of these conditions and only in the absence of light does the randomness show up.

Some of the final product problems can be resolved by:-

1 Always cover the package window except when erasing.

2 Always initialise I10 ports in a known state before configuring them as inputs or outputs. This will eliminate glitches on I10 pins configured as outputs.

3 lnitialise registers into a known state.

4 If the above points work, then only program a few devices and test well.

This will reduce the likely-hood of having a product called an OPTO-PIC!

This example caused a product to work now and again.

INIT MOVLW OOH ;load W with 00 . TRlS PORTA ; make port a all outputs MOVLW OFFH ; load W with OFFh TRlS PORT6 ; make port b all inputs MOVL W B1OOOOO1 1 1' ; set up option register OPTION ; do it

The addition of two lines cured the problem and the product is now in full production with no bugs.

- INIT CLRF PORTA ; clear port a CLRF PORT6 ; clear port b MOVLW OOH ; load W with 00 TRlS PORTA ; make port a all outputs MOVLW OFFH ; load W with OFFh TRIS PORT6 ; make port b all inputs MOVL W 6'000001 1 1 ' ; set up option register OPTION ; do it

Hint You can build your own EPROM eraser for a fraction of the cost of commercial units by purchasing a replacement UV tube, starter and ballast. Ensure the box used to house the eraser is light proof and has a mains interlock switch fitted to the door as exposure to UV will cause eye damage. A conductive foam tray will prevent static damage to the PICs.

Warning Do not code protect windowed PIC'S during development. Some of the mid to high range devices have the code protection fuse buried in the silicon where the UV light from an eraser can't reach. Failure to do this will result in a £35 OTP device! This is part of the overall protection scheme to prevent your product being reverse engineered.

On windowed l2Cxxx devices, UV erasure removes the 4MHz oscillator calibration value. Read this value and write it on the underside of the PIC so it's there for the next time you program,

Why programs won't run

There are four main reasons why a program written, assembled, simulated and programmed successfully will not run.

1) The oscillator configuration chosen during programming does not match the hardware. i.e. Crystal on PCB, RC Oscillator programmed in PIC - result nothing.

2) The watchdog bit was programmed into the PIC but the program has no CLRWDT instructions - result program never runs for more than 18mS before it's reset.

Page 49: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICROCHIP PIC Program the PIC

3) On the 16C5x devices, the RTCC pin is left floating. This places the PIC in a test mode. Tie the pin high or low if not used or via 10k is it is used.

4) Reset pin left floating - tie high or via reset circuit.

Inspect Board

Check Continuity

Verify Schematics

Understand Components

Know the Software

Take a Break

Get Help L

DEBUG FLOWCHART

PIC Proiens -gi- , PIC Projects PIC Applications In this selection of application examples, I have tried to bias the designs to the 16C84. The reason behind this is simple - the PICSTART Plus is supplied with a C84 and newcomers to the PIC are drawn to the device as they don't need to spend time or money on an EPROM erasure unit. I have therefore included some examples from previous versions of the Beginners Guides which have been converted across to the 16C84. All the programs have been tested on Rev 3.30 of MPLAB.

Example - multiple wakeup period - WDT-54.ASM

This could be used on battery powered equipment or portable alarms where a visual indication is required but battery power needs to be conserved. On reset, the power down bit is tested to check for a cold start. If so, the initialisation routine is implemented. If a warm reset is detected, the state of the LED is tested. If off, it's turned on and the watchdog timer is set to 72mS and the PIC placed in a sleep state. If on, the LED is turned off and the watchdog timer is set up for 1.155 prior to entering the sleep state. When programming the PIC, ensure the Watchdog fuse is set. The user program can be called from the points indicated to do whatever function is required.

erg 0 ; reset vector btfss status, 4 ; test power down bit goto main ; warm reset

init clrf portb ; clear port bits pagel movlw b'11111100' ; make bO output for led movwf trisb page0

; * * * * * * * * * * MAIN PROGRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

main btfsc led1 ; test led status

Page 50: A1 A Beginners Guide to the Microchip PIC

PIC Pro,ects

got0 off bs f led1 ; turn led on as it was off ; insert your program here via a call pagel movlw b'10001010' ; 72ms on time movwf optreg page0 sleep

off bc f led1 ; led is on so turn it off ; insert your program here via a call pagel movlw b'10001110' ; 1.15 sec off time movwf optreg page0 sleep

Example - Timer functions

Even though various software examples exist for the PIC, a number of enquiries still come in for basic timer functions. This collection is included to assist those starting out. Try the spreadsheet file RTCC.XLS which enables experimentation with the values for timer 0 (RTCC) without resorting to scopes and stopclocks.

TIMEI-54.ASM - Basic time delay using I S tick to toggle an LED for l6C5x

The timer uses a prescaller set to I16 to create a basic 16uS input into the tmrO register. The line:-

osl movlw .1 ;load/reload offset

sets up an offset into tmr0. This is nescesarry as tmrO is checked to see if it has rolled over from Offh to OOh and in the absence of interrupts, the only other way would be to test a bit in tmrO to determine how far the counter has progressed. By manipulating both the prescale and offset values, various time periods or delays can be created. I

one-sec movlw .245 ; 1s = 16uS * 255 * 245 movwf time1 ; save 1 second value

movlw movwf movfw btf ss got0 decfsz got0 retlw

.1 I

tmr 0 I

tmr 0 I

- z I

$-2 I

time1,f ; osl I

0 I

load/reload offset into tmrO load tmrO value test for zero loop count down loop re turn

TIME2-84.ASM - Basic time delay using I S tick to toggle an LED for 16Cxx - no interrupts I

This example is identical to the previous example with the exception of register setup for timer 0. This provides an example on how to convert programs from one PIC to another.

one-sec movlw movwf

osl movlw movwf movfw btf ss got0 decf sz got0 retlw

.245 I

timel ;

.1 I

tmr 0 , tmr 0 I

- z I

$-2 I

timel, f ; 0s 1 I

0 I

1s = 16uS * 255 * 245 save 1 second value

load/reload offset into tmrO load tmrO value test for zero loop count down loop Eeturn

TIME4-84.ASM - I S timer running under interrupt control toggling LED

The time period for this example uses a 50mS tick via the interrupt. When timer 0 rolls over, an interrupt is generated. This causes the program to vector to 04h where the interrupt handler resides. After determining that the interrupt is valid, the 1 second counter is decremented and tested for zero. If the result is a zero, the LED is toggled, otherwise the timer is re- loaded with the offset for 50mS (60).

erg OOh ; reset vector goto init ; bypass interrupt vector

org 04h ; interrupt vector

Page 51: A1 A Beginners Guide to the Microchip PIC

btfss intcon,tOif ; test for tmrO interrupt goto end-int ; exit interrupt TMRO decf sz timel, f ; count down 50mS periods goto end-t0int

to1 btf ss portb, 0 ; test led status goto setl bc f portb, 0 ; if on then turn off goto $+2 ; jump to reload

set1 bsf portb, 0 ; if off then turn on movlw one-sec ; reload 1s timer - .20 movwf timel

end-t Oint movlw .60 ; reload tmrO with offset movwf tmrO ; for 50mS tick bc f intcon,tOif ; clear interrupt flag

end-int retfie ; return from interrupt

. ****************** initalisation . . . . . . . . . . . . . . . . . . . . init page1 ; macro

movlw b'10000111' ; /256 no pullup int osc movwf optreg clrf trisb ; make outputs page0 ; macro movlw b'10100000' ; gie on and tmrO int on movwf intcon movlw one-sec ; load 1s timer - .20 movwf timel movlw .60 ; load tmrO with 50mS movwf tmrO

main goto main ; loop here

Example - Interfacing a 16x1 line display to a 12C508 - LCD-508.ASM

As the 12C508 has only 5 110 and 1 input lines, a normal interface to an LCD display module is out of the question as they require a minimum of 6 inputs ( outputs from the PIC). Additional output lines can be created with the use of a 74HC595 latch and this provides the DATA and RS line for the

9 LCD module plus 3 additional spare lines. The 74HC595 uses 3 lines from the PIC (data, clock and latch) to operate. The LCD module requires one additional control line - Enable - to finish off the interface and this is provided directly from the PIC. With all these interface connections from 1 the PIC to the latch, there are st i l l 2 spare lines available. In this code example, one has been used as an input from a push button. Following initialisation of ports etc. the LCD is set up in a 4 bit mode. To accomplish this, the value to be sent via the 74HC595 is first loaded into the w register. Subroutine clklcd is called which sends 8 bits of data out. This includes the 4 bits of DATA information for the LCD module plus the RS line status. At the end of this routine, the Enable line is toggled.

The main program sends out a sequence of messages to the display and upon receiving a button press, sends a specific message.

As the 12C508 has a 2 level stack, a software stack has been implemented to enable a 3 level call to operate. This can be seen in the following section of code.

movlw $+4 ; saves return point movwf stack ; on stack movlw mesl ; load message number call dostr ; send string movlw 40h ; prog will return here

dostr movwf chpt ; load character pointer / / see listing for full code

I

eos movfw stack ; restore software stack movwf pcl ; by loading pc retlw 0 ; with return point

The program has been successfully used on a 20x4 line display with minimal modifications to the code.

Example - Battery Monitor - VOLT-508.ASM

The PIC12C508 is an ideal device for use in low cost and space critical circuits. A simple battery monitor could be used for both portable and fixed applications. One such area could be mains / battery door and

Page 52: A1 A Beginners Guide to the Microchip PIC

BEGINNERS GUIDE TO THE MICRDCHIP PIC PC Projects

window openers where the user needs to be notified if the battery voltage is falling to a low level - mains failure or power switched off on charger.

The monitor first discharges the capacitor C3 and then allows it to charge up to the logic threshold of the PIC. If the time taken for the threshold to be reached is too long or never reached, an alarm is activated. This example could be merged with the multiple wakeup period example (above) to provide a low current consumption monitor.

Example - Digital Lock I Access Control - ALARM-84.ASM

This lock uses a 4x4 keypad to let the user enter a preset code. The current program has a factory set 6 digit number which the user has to enter within 5 seconds. If valid, a door or lock could be released otherwise an alarm output is enabled for 5 seconds. Each key depression is announced by a tone output which can be fed to a speaker or sounder. Expansion of this code could enable user codes to be stored in the E2 area, a delayed lockout for multiple false entry codes or even interfacing to either a swipe reader or Dallas touch tag for greater security.

Example - Christmas tree light flasher - XMAS-54.ASM

The basic time delays used in TIME1-54.ASM are expanded to create 8 independent time intervals. The lights all start at the same time, but then appear to be completely random - even though the individual times remain constant. By choosing prime numbers as the seed for the delays, the delays should never revert to the start pattern - I may be wrong!. The output from the PIC can either drive a transistor to provide greater current I voltage handling or control Triacs with proper isolation and zero crossing I EMC protection.

Reworked Examples

OHPl-84.ASM Shutter 1 door control using stepper motor drive. INDI-84.ASM Vehicle turn and hazard indicator module CABLE-84.ASM Cable identifier TRAF1-84.ASM Traffic light sequencer

W A K E U P

Page 53: A1 A Beginners Guide to the Microchip PIC

BBEGINNERS GUIDE TO THE MICROCHIP PC PIC Projecrs

Voltage to be monrtored C2 100nF

INPUT

LOW READ TIMER VALUE

>

TURN ON I

DELAY 1 DELAY 1

FLOWCHART FOR VOLT-508.ASM

Page 54: A1 A Beginners Guide to the Microchip PIC

KEYPAD

WEAKER R4 IWR

CIRCUIT FOR ALARM84.ASM

PIC Prolens . A BEGINNERS GUIDE TO THE MlGROCHlP PIC

PORTB INTERRUPT

SLEEP e3 STORE el

MATCH r - 0 POINTER

FLOW CHART FOR ALARM84.ASM

Page 55: A1 A Beginners Guide to the Microchip PIC

Contact Numbers

Bluebird Electronics Contact - Nigel Gardner Tel: 01 380 7251 10 Fax: 01 380 729556 email: [email protected] web http://www.bluebird-electronics.co.uk

Microchip Approved PIC Training Workshops, Hardware Starter Kits, Technical Authorship, Consultancy.

Microchip web http://www.microchip.com

Further Reading

PIC Cookbook Vol 1 PIC wakeup using a Piezo disk, PWM generation on a 16C71, Traffic light sequencer, DTMF signal source, RS232 routines for 16C73/74, Rockwell GPS t o PIC interface, Software hysteresis for analogue input on a digital port pin,'Ram extension using external ram chip, Triac control of ac load power, Magnetic swipe card reader and Software protection dongle. Source code for the projects is supplied on a 3.5" disk. rrp f 19.95

PIC Cookbook Vol2 Square wave I pulse generator, Non volatile 'hours run' recorder, Modem for data comms at 1200 baud, parity error detection, Keyboard scanner, NMEA level I data converter 1 display, Auto baud rate detection, 4 * 16 LED Bargraph , Greenhouse Watering, Four Channel DVM with RS232, Maxim MAX186 12bit a/d, Lookup Tables for Non Linear Sensors, Trailer Alarm, Program conversion between l6C5x and 16Cxx devices, TSL214 - Opto sensor, Electronic Quiz Master, PIC PLC. rrp f 19.95

Greatest Little PIC Book The Greatest Little PIC covers the new 8 pin PIC12C50x family from Microchip. This device is ideal for those applications requiring a few I10

lines. ,The book has been written to guide the potential user through the architecture, software modes and benifits derived from using this device. The book also covers development tools and is supplied with MPLAB (editor, assembler and simulator) to enable development under Windows. The book is rounded off with a number of worked examples including timers, sound generators, water descaler, data logger and light / motor control. Supplied withsource code examples and MPLAB on 2 disks rrp f 19.95

Contact your distributor for order codes or look at the Bluebird Electronics Web Page.

Page 56: A1 A Beginners Guide to the Microchip PIC

Part Numbers for Development Tools ~3 The Author

Microchip Development Tools

PICSTART Plus (includes MPLAB) ICEPIC5x

PRO MATE II

16Cxx, 17Cxx, 14000, 12C50x

16C54, 55, 56, 57, 58 add on board for 12C508,9 l6C620, 621,622 16C62,63, 64,65 16C72,73,74 16C71, 61, 710, 711 16C84, F83, F84

Most 16Cxx and 17Cxx

See DS30177 for socket modules

Contact your distributor for the system to meet your requirements as the PICMASTER is available with or without the PRO MATE II programmer

N igel Gardner is an Electronic Engineer of some 20 years industrial experience in various fields. He owns Bluebird Electronics specialising in PIC Support Products and Microchip Training Workshops. This is his

f ifth book, the fourth on the PIC Microcontroller, his other book is A Practical Introduction to Electronics (from bits to chips) co written with Max Horsey.

Nigel is a member of the Microchip Consultants Group.

Page 57: A1 A Beginners Guide to the Microchip PIC

PIC Pinout

A2lAN2 WAN3Nref

A4iTOCKI MCLWVpp

vss BOIINT

BI 82 B3

TOCKl OSCIICLKIN

Vss Vdd BO 87

T%i !ghKFElN OSCZ'CLKOUT

vss C7 NC C6 A0 C5 A1 22 C4 A2 21 C3

MCLWVpp AOIANO AlIANI AZ1AN2

A3ANWref A4TTOCKI

ASIANSISS VSS

OSClICLKlN OSCHCLKOUT

CMlOSOTTICKI Cl/T10~I/CCP2

CZ'CCPI C3ISCWSCL

MCLWVpp AWANO AIIANI A21AN2

A3IAN3Nref A4TTOCKI

A5IANSISS EOIRDIANS EllWWAN6 WCSlAN7

Vdd VSS

OSClICLKIN OSCHCLKOUT

CMlOSOITICKI c 1 m OSIICCPZ

C2lCCP1 C3ISCWSCL

WPSPO DlIPSPl

87 86 B5 64 83 BZ B1 BOIINT Vdd vss D7lPSP7 D61PSP6 D51PSP5 D41PSP4 C7lRWDT CWTWCK CVSDO CUSDIISDA DWPSP3 DZ'PSP2

Page 58: A1 A Beginners Guide to the Microchip PIC

Pmduct Tlnvf i ICSP " Other Features mn I I Equivalent

Ye5 25mA source/smk per I/O, internal oscillator - .-

8P RSM 8JW

Yes 25mA source/smk per 1/0 fnternal oscillator - 8P 8SM. 8JW

Yes 25mA source/s~nk per 1/0 Internal osc~llator - 8P 8SM. 8JW

Yes 25mA source/slnk per I/O lnternal oscillator - 8P 8SM. 8JW

Yes 125mA source/slnk per I/O, Internal osclllator I -

Yes 125mA source/s~nk per I/O, lnternal oscillator I - 18P, 8SM. 8JW I Yes 125mA source/slnk per i/O, internal osclllator I - 18P. 8SM, 8JW I Yes 125mA source/sink per I/O, internal oscillator - 18P. 8SM, 8JW

Yes 25mA source/smk per 110, lnternal oscillator - 8P. 8JW

Yes 25mA source/slnk per I/O, internal osctllator - 8P, 8JW

- I 20mA source and 25mA smk per 1/O. 2 5V I PIC16CR54A I l 8 P , 18JW. 18SO. 20SS 1 - 20mA source and 25mA sink per I/O, 2.OV - 18P, 18JW, 18SO. 20SS

- 20mA source and 25mA smk per 1/0 PIC16CR54B 18P, 18JW, 18SO. 20SS

- 20mA source and 25mA slnk per I/O, 2.5'4 - 28P, 28JW. 28SP. 28SO. 28SS - 20mA source and 25mA slnk per I/O. 2.5V - 18P. 18JW. 18SO. 2055

- 120mA source and 25mA slnk per 1/0 I PIC16CR56A I18P. 18JW, 18SO. 20SS - 120mA source and 25mA sink oer I/O. 2.5V -- 128P. 28JW. 28SP. 28SO. 28SS

- 120mA source and 25mA sink per I/O. 2.5V I PIC16CR578 I28P. 28JW, 28SP. 28SO. 28SS 1 I I I - 120mA source and 25mA slnk per I/O, 2.OV I PIC16CR58A I18P. 18JW, 18SO. 20SS

120mA source and 25mA slnk per I/O I PIC16CR58B I 18P. 18JW. 18SO. 20SS

Yes 25mA reference, source/slnk, ~nternal osc~llator temperature sensor, bandgap voltage - 28SP, 28SO,28SS. 28JW

Yes 125mA source/slnk per I/O, 2.5V - 18P. 18S0.2OSS. 18JW

Yes 1 25mA source/sink per 1/0 I - 1l8P, 18SO. 20SS. 18JW I Yes 1 25mA source/sink per 1/0 1l8P. 18SO,2OSS. 18JW

Yes 125mA source/sink ~ e r I/O. 2.5V - 118P. 18S0.20SS. IRJW

tbiiZ%~I 3584 i 2048x14 i 128 i 20 i 1 3 i - / I I 1 I

- - - - - l l Wlll Yes I 25mA source/smk per 1/0 I - 118P. 18SO. 20SS.18-

I ! Wlll

I ~ W O I

l lWDl

l tWl

t ~ w n l

l lWUl

l lWUl

I I Wlll

I I Wllt

5

Yes 20mA source and 25mA slnk per 1/0 - 1 18P. 18SO,18JW I

Yes 1 25mA source/smk per I/O, Ca~ture/Compare/PWM I PIC16CR62 128SP. 28S0.28SS. 28JW

Yes I 25mA source/slnk per I/O, Capture/Compare/PWM I PICl6CR63 I 28SP, 28S0,28JW I Yes 25mA source/slnk per I/O. Parallel Slave Port.

Capture/Compare/PWM PIC16CR64 40P, 40JW. 44L,

Yes 25mA source/slnk per i/O, Parallel Slave Port, 2 Caoture/Comoare/PWM PIC16CR65 40P, 40JW. 44L, 44PQ. 44PT

I I I I I I I I I 1 . 1

pK16C66 14336 8192x14 368 2 0 22 - USART/ - 12C/SPI Yes -

. , . . I I

Yes 25mA source/slnk per I/O. Capture/Compare/PWM - 28SP. 28SO. 28JW I 1 I I I I I I I I I

pIC16C67 14336 8192x14 368 2 0 3 3 - USART/ - 12C/SPI Yes -

I I I

Yes 25rnA source/sink per I/O, Capture/Compare/PWM. Parallel Slave Port

- 40P. 40JW. 44L. U P Q , 44PT I I

PIC16C620 896 512x14 80 20 13 1 - - - - Yes 2 - - p1c16~620A* 896 512x14 80 2 0 1 3 1 - - - - Yes 2

*Contact Mlcrochlp Technology for ava~lab~ltty date.

I I I

Yes I25mA source/sink per I/O, pro~rammable VREF. 2.5V I - 118P, 18SO. 20SS. 18JW - I

Y1.s 25mA source/stnk per I/O, programmable VREF - 118P, 18SO. 20SS, 18JW

Page 59: A1 A Beginners Guide to the Microchip PIC

PIC16CE623* 896 512x14 (12TE,) 20 13 - - - - Yes 2 1+WDT Yes 25mA source/smk per I/O, programmable VREF, 2.5V - 18P. laso, 2 0 s . 18Jw

- PICl6CE624' 1792 1024x14 (12TE1, 20 13 - - - - Yes 2 1+WDT Yes 25mA source/s~nk per I/O, programmable VREF, 2.5V i W , 1850.2OSS. 18JW

PIC16CE625* 3584 2048x14 ,,%%, 20 13 - - - - Yes 2 1+WDT Yes 25mA source/s~nk per I/O, programmable VREF, 2.5V - 18P. 18so. 2 0 s . 18Jw "ti

( ILO C, J PIC16C641* 3584 2048x14 128 20 22 - - - - Yes 2 l+WDT Yes 25mA source/sink per I/O, programmable VREF - 28s'. 28s0, 28JW

PIC16C642 7168 4096x14 176 20 22 - - - - Yes 2 l+WDT Yes 25mA source/smk per I/O, programmable VREF - 28s'. 28s0, 28JW

PIC16C661* 3584 2048x14 128 20 33 - - - - Yes 25mA source/s~nk per I/O, programmable VREF. 2 1+WDT yes 0,,,11,1 .I, on, - 40P. 40JW. 44L. 44PQ. 44f'T

12 II5AHT Yes - 4+WDT - 20mA source and 35mA slnk per I/O. 2 1/O wtth 60mA

I , I I " smk, 4 Capture, externally expandable, 1 cycle 8x8 mumply

- 64SP. W L , 681 64PT

I) II'sAlfl

- I 20mA source and 35mA slnk per 1/O, 2 1/O wtth 60mA

- Yes - ski, vd;k~I

- 4+WDT - - s~nk, 4 Capture, externally expandable, 1 cycle 8x8 muttlply 64SP. 68U. 68L 64PT

I *Contact Mlcrochlp Tachnology for a~nllalllll\y tl.1.. I Anoilofl lo 1)lfllInl CIIIWU~~U? IIAC - I I1 l l d IIIAII~IIU Ciwt~rter

CAP - (:~~(rlurn k ' - I I~VII,M ( I l n ~ w rn~t~~nable) S E z tm&. up to 16 bits CCP - ~:n~nurn/(:ort~paru/IWM la( 1 1 1 1 8 4 I~!lc&lalwl !Ira t11I Bus Recewer/Transm~tter SMB = System Management Bus - ---

I L =

Page 60: A1 A Beginners Guide to the Microchip PIC

Key to PIC16 Family : X I HEXADECIMAL TO DECIMAL

I CONVERSION Instruction sets

0 1 2 3 4 5 6 7 8 9 A B C D E F - Usir nun

b Bit address within an 8 bit file register

Th~s Table For each Hex d~ait.

A

C D E F c find the

d Destrnation select; d = 0 Store result In W (fOA).

d = 1 Store result In f ~ l e reglster f

Default IS d = 1. -

f Register file address (0x00 to OxFF)

k Literal field, constant data or label 1 ; 13 14 15

ial value. Add the

W Working register (accumulator)

x Don't care location

Pin Diagram I

., . assoc rrs together. For example, Hex A38F converts to 41871 as follows:

Hex 1000's Digit Hex 100's Digit Hex 103 Digit Hex 1's Digit Result

I I I 40960 + 7 6 8 + 128 + 15 + 4 1 8 7 1

I I I 1 Decimal

I ASCII Character Set

Page 61: A1 A Beginners Guide to the Microchip PIC

PIC1 6C5X & PIC12C50X INSTRUCTION SET The PIC16C5X, Microchip's base-line 8-bit microcontroller family, uses a 12-bit wide instruction set. All instructions execute in a single instruction cycle unless otherwise noted. Any unused opcode is executed as a NOP. The instruction set is grouped into the following catagories:

PIC16C5X LITERAL AND CONTROL OPERATIONS

I I. I , ANDLW k AND hteral and W k AND W ' -

9kk 1 CALL k Call subroutme PC t 1 -' TOS, k - , P C 004 / CLRWDT Clear watchdog tlmer 0 -t WDT (and prescaler

i f assigned) Goto address k + PC ( 9 bits) (k IS nlne b~ts)

I rats sort f oscillator W + 110 contro l reg f

Fkk XORLW Exclus~ve OR hteral and W k .XOR. w + w

PIC16CSX BYTE ORIENTED FlLE REGISTER OPERATIONS

1 C f I ADDWF f, d Add W and f / W t f + d 14f ANDWF f , d l A N D W a n d f I w .AND. f + d 0 6 f l C L R F f Icka; f 0 4 0 C L L Clear W 24f COMF f , d C O ~ lement f .NOT. f + d 0cf DECF f , d Decrement f f - l + d 2Cf DECFSZ f , d Decrement f, skip if zero f - 1 + d,

sk lu i f zero 28f 1 INCF f , d / increment f f + l + d 3cf INCFSZ i , d Increment f, skip f zero I i t I + d,

sk ip i f zero 10f / IORWF f , d I Inclusive OR W and f I w .OR. f -t d 20fIMOVF f , d M o v e f I f + d 02f I MOVWF f Move W to f I w + £ 0 0 0 1 NOP 1 No operation ~ ~ ~ I R L F f , d I ~ o t a t e l e f t f - , - reglsrer i

ylClel1. . . . . .Oh 30f RRF f , d Rotate right f renster f

q 4 7 . . . . . .Oh 08f SUBWE f , d Subtract W from f f - w + d 38f SWAPF f , d Swap halves f f ( 0 : 3 ) t+ f ( 4 : 7 ) + d 18f XORWF f , d Exclusive OR W and f w .xoR f -t d

PIC16C5X BIT ORIENTED FlLE REGISTER OPERATIONS

4bf 1 BCF f , b / Blt clear t - 5bf BSF f , b Bit set f 1 + f ( b ) 6bf BTFSC f , b Bit test, skip if clear sk ip i f f ( b ) = 0 8bf BTFSS f , b Bit test, skip if set sk ip i f f (b) = 1

PIC1 6CXX INSTRUCTION SET The PICIGCXX, Microchip's mid-range 8-bit microcontroller family, uses a 14-bit wide instruction set. The PlCl6CXX instruction set consists of 36 instructions, each a single 14-bit wide word. Most instructions operate on a file register, f, and the working register, w (accumulator). The result can be directed either to the file register or the W register or to both in the case of some instructions. A few instructions operate solely on a file register (BSF for example). The instruction set is grouped into the following catagories:

PlCl6CXX LITERAL AND CONTROL OPERATIONS

39kk ANDLW k AND literal and W k .AND. w + W 2kkk CALL k Call subroutine PC t 1 + TOS,k +PC 0064 CLRWDT T Clear watchdog timer 0 + WDT (and prescaler

i f asslgned) + PC ( 9 b l t s )

(k IS nine b~ts)

1 o s c i l l a t o r 3Ckk 1 SlJBLW k 1 Subtract W from literal I K - w + w ~~ ~ . -... -.. ~~ .. .. .. 006f 1 TR IS f I~Tristate port f 1 W + I10 con t ro l reg f 3Akk I XORLW K 1 Exclusive OR literal and W I k .XOR. w + w

PIC16CXX BYTE ORIENTED FlLE REGISTER OPERATIONS

b- - 9 I - . . 07f f / ADDWF f , d Add Wand f W t f ' d 0 5 f f I A N ~ w ~ f , d / A N D W a n d f I W .AND. f + d 0 1 8 f CLRF f Clearf o + f 0100 CLRW Clear W O + W 09 f f COMF f , d C~mplementf .NOT. f + d o 3 f f DECF f , d Decrement f f - 1 - d OBff DECFSZ f , d Decrement f, skip if zero f - 1 + d, s k i p i f 0 O ~ f f INCF- f , d Increment f f + l ' d OFff INCFSZ f , d Increment f, skip if zero f t 1 -t d, s k i p i f 0 04f f IORWF f , d Inclusive OR Wand f w .OR. f -+ d 0 8 f f MOVF f , d Movef f ' d 0 0 8 f MOW f M o v e W t o f w ' f 0000 NOP No operation O D f f RLF f , d Rotate left f register F 4~47 . . . . . .Oh

PIC16CXX BIT ORIENTED FlLE REGISTER OPERATIONS

l b f f BCF f,b Bit clear f O + f ( b ) l b f f BSF f , b Bit set f 1 + f (b) lbf f BTFSC f , b Bit test, skip if clear s k i p i f f (b) = 0 lbf f BTFSS f, b Bit test, skip if set s k i p i f f (b) = 1

PlCl6CXX SPECIAL INSTRUCTION MNEMONICS

ADDCF f , d Add Carry to ~ i l e

I

ADDDCF f , d I ~ d d Digit Carry t o File

Branch Branch on Carry

Branch on Digit Carry

I

BNC k Branch on No Carry

BNM) k Branch on No Digit Carry

Clear Carry Clear Digit Car Clear Zero Move File t o W

SETC Set Carry SETDC Set Digit Carry SETZ Set Zero SKPC Skip on Carry SKPNC Sklp on No Carry SKPDC Skip on Digit Carry SKPNDC Skip on No Digit Carry SKPZ Sklp on Zero SKPNZ Sklp on Non Zero SWCF f ,d Subtract Carry from File

"I": GOT0 __ -

BTFSC 3.0 GOT0 BTFSC 3,l

GOT0 BTFSC GOT0 BCF BCF

MOVF 5 3 E BSF

BTFSS BTFSC 3.0 BTFSS BTFSC 3.1 -

BTFSC DECF MOVF f,l