You are on page 1of 61

A BEGINNERS GUIDE

TO THE MICROCHIP PIC

Microchip products are available from:

1
COMPONENTS
. -. . .- .. Com~onents
Farnell - r -
-
Ltd.
Sales, Marketing a1i d Administration Centre,
Canal Road, Leeds, LS12 2TU I S B N 1-899013-01-6
1- I
COMPONENTS
SALES: Tel: 0113 2636311 (24 Hrs)
Fax: 0113 2633411 (24 Hrs)
TECHNICAL SUPPORT: Tel: 0113 2799123
DATALINE: Tel: 0113 2310160 (24 Hrs)
(Data Sheets Only) 9
B Y NlGEL GARDNER
a.) 9
h- 3
I
I A - A BEGINNERS GUIDE
OL- 9
I
4Pi 9
TO THE MICROCHIP PIC I

*; 3 REVISION 3

BY NlGEL GARDNER
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 t o 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
.
T
Preface
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
publication may be reproduced or distributed in any form or by any means, pin PIC'S.
or stored in a database or retrieval system, without the prior written
permission of Bluebird Technical Press Limited, with the exception of the This book is dedicated to my wife June and my daughter Emma who now
program listings which may be entered, stored, and executed in a computer borrows my flashing led's, strippers, screwdrivers etc!
system, but may not be reproduced for publication.
Nigel C Gardner
May 1998
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.

ITECHNICAL
PRESS LTD

Published 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
Email: sirnon@character.u-net.com
m Contents (cont~n~ea) a BEGINNU;IS GUIDE m WEMICROCHIPR
F i 9
Lookup tables 40
Contents Subroutine placement 41
Long calls and long goto's 42
Pulse width detection 42
Preface ill Inputs/outputs 43
Product Development vi Multiplexed inputs 46
The Idea vi Ram resetting and clear 48
Basics 2 Reset vectors 49
Microprocessor 4 Bit test from the RETLW 50
Microcontrollers 5 TMRO interrupt uses - 16Cxx only 50
Why use the PIC? 5 RTCC 50
Hardware Design 8 Watch dog timer 52
Inside the PIC 8 The stack 56
Pin configuration 10 Interrupts 57
Which PIC to choose? 10 Software or polled interrupts 58
Hardware requirements 11 Interrupt driven software 59
.Reset circuitry 12 Page boundaries 62
Oscillators 13 16Cxx CALLSt o data tables 63
Pic part numbering 14 AID conversion block I 63
I10 circuit 15 16C84 the E2 based PIC 66
Mains Interfacing 17 Other periferals in the PIC family 68
Analog Inputs 18 Assemble Software 69
Software design 20 Assembling programs 69
Logic truth tables 20 Debug Software & Hardware 72
Binary addition and subtraction 21 Development & debug ,. 72
Hexadecimal notation - 21 Development tools and systems 72
ASCII conversion table 23 MPLAB 74
Source code writing 24 PIC project boards 81
Program structure 25 Program the PIC 83
Universal header 26 Code protection 84
Assembler directives 28 Serialisation 85
Macros 30 Windowed device development 86
Program development 30 PIC projects 89
The PIC instruction set 31 Contact numbers 100
B i t operations 31 Part numbers for development tools 102
Byte operations 32 The author 103
Byte operations specifying a destination 34 PIC pinout 104
Internal registers 38
Status register 38
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. NO ICE A :
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. 1 YES YES
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. PIC DEVELOPMENT FLOWCHART
Before the design process starts, the basic terminology needs to be ICE In Circuit Emulator - (ICE PIC or PIC MASTER) - a very
understood - like learning a new language. So in the case of useful piece of equipment connected between your PC and the socket
microcontroller designs based on the PIC, the PIC language (instruction set, where the microcontroller will reside. It enables the software to be run on
terms and development kit) need to be thoroughly understood before the the PC but looks like a microcontroller at the circuit board end. The ICE
design can commence. allows you to step through a program, watch what happens within the
micro and how it communicates with the outside world.
Now lets get started with the general terms, some facts about the PIC and
the difference between Microprocessor and Microcontroller based systems. 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.
Basics
They come in all shapes and sizes and costs vary. Both the PICSTART PLUS
Lets start with some basic terminology used. and PROMATE CE from Microchip connect to the serial port.

Microcontroller A lump of plastic, metal and purified sand which Source File A program written in a language the assember and
without any software does nothing. When software controls a you understand. The source file has t o be assembled before the
microcontroller, it has almost unlimited applications. microcontroller will understand it.

110 A connection pin from the microcontroller to the Assembler A software package which converts the Source file
outside world which can be configured as input or output. 110 is needed in into an Object file. Error checking is built in, a heavily used feature in
most cases to allow the microcontroller to either communicate, control or debugging a program as errors are flagged up during the assembly process.
read information MPASM is the latest assembler from Microchip handling all the PIC family.

Software The information that the microcontroller needs to Object File This is a file produced by the Assembler and is in a
operate or run. This needs to be free of bugs and errors for a successful form which the programmer, simulator or ICE understands to enable it to
application or product. Software can be written in a variety of languages perform its function. File extension is .OBJ or HEX depending on the
like C, Pascal or Assembler (one level up from writing your software in assembler directive.
binary).
List File This is a file created by the Assembler and contains all
Hardware The microcontroller, memory, interface components, the instructions from the Source file, with their hexadecimal values along
power supplies, signal conditioning circuits and all the components side and comments you have written. This is the most useful file to examine
connected to it to make it work and interface to the outside world. Another when trying to debug the program as you have a greater chance of
way of looking at (especially when it does not work) is that you can kick following what is happening within the software than the Source listing.
hardware. The file extension is .LST

Simulator The MPLAB development environment has it's own Other Files The error file (.ERR) contains a list of the error but does
inbuilt simulator which allows you access to some of the internal operation not give any indication as to their origin. The COD file is used by the
of the PIC. This is a good way of testing your designs if you know when emulator.
events occur. If an event occurs 'somewhere about there1, you might find
the simulator restrictive. Full trace, step and debug facilities are however Bugs Errors created unknowingly by you. These range from
available simpel typin errus to incorrect use of the software language. Most of these
bugs will be found by the compiler and shown up in a .LST file, others will nv-

have to be sought by trial and error.


vo
DIGITAL
Microprocessor PWM
ANALOG
A microprocessor or digital computer is made up of three basic sections - US232
12C 4
CPU, I10 and Memory - with the addition of some support circuitry. i

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.
TYPICAL MICROPROCESSOR SYSTEM
The memory can be RAM, ROM, EPROM, EEPROM or any combination of Microcontrollers
these and is used to store the program and data.
The PIC on the other hand is a microcontroller and has all the CPU, memory,
An oscillator is required to drive the microprocessor. Its function is to clock oscillator, watchdog and I10 incorporated within the same chip. This saves
data and instructions into the CPU, compute the results and then output space, design time and external peripheral timing and compatibility
the information. The oscillator can be made from either discrete problems, but in some circumstances, can limit the design to a set memory
components or be a ready made module. size and I10 capabilities.
Other circuitry found associated with the microprocessor are the watch dog The PIC family of microcontrollers offer a wide range of 110, memory and
timer - to help prevent system latchup, buffering for address and data special functions to meet most requirements of the development engineer.
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 You will find many general books on library shelves exploring the design of
one of a number of circuits connected on the same bus. microcontrollers, microprocessors and computers, so the subject will not be
expanded or duplicated here other than to explain the basic differences.
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 Why use the PIC?
'separate chips and require a Data Bus, Address Bus and Address Decoding
t o enable correct operation. 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
simultaneous access to both data and program memory. Conventional Versatility The PIC is a versatile micro and in volume is a low cost
microcontrollers tend to have one internal bus handling both data and solution to replace even a few logic gates - where space is at a premium.
program. This slows operation down by at least a factor of 2 when
compared to the PIC 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
Safety All the instructions fit into a 12 or 14 bit program contents of the program memory cannot be read out in a way that the
memory word. There is no likelyhood of the software jumping into the program code can be reconstructed.
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. Development The PIC is available in windowed form for
development and OTP (one time programmable) for production. The tools
Instruction Set There are 33 instructions to be learnt in order to write for development are readily available and are very affordable even for the
software for the 12C50x116C5x family and 35 for the 16Cxx devices. All the home enthusiast.
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
t o 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
1OOmA.

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.
n order to design any system, both hardware and softwarrerrsed trl he

I 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 2-g, ez s
& %
$; %,E $g g
Z F on: ::
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. BAUC PIC BLOCK DIAGRAM
The STACK is allocated to the PROGRAM COUNTER to enablc d progrrtrr tn Hardware Requirements
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 The minimum hardware requirement to run the PIC is an oscillator. This can
increased to 8 deep. 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
Separate busses for program instructions and data are used It) internal circuitry will handle resetting the PIC in normal operating
microcontrollers based on Harvard Architecture t o speed up dab1 conditions.
throughput and improve software safety. This architecture allows
simultaneous access to both data and program memory.

Pin Configuration
-- I

see card in back of book .) XI I)


4 -
MCLR >
A
A1
~
1
+

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

l5
OSCI

OSC2
A3

~2
-
2

8
Ib RTCC 82
\ PICIGCXX 83
84 10
Which PIC to choose? C 3Cl
B5 -
In
C 3 IOONF 9 f
87 fi$
The I10 requirements should be known at the start and this will determine
A
YI

the product chosen during development. \ - I1

When you start t o write the code, don't worry which memory size t o -
-
choose. It is easier to look at the requirements as you go along.
MINIMUM HARDWARE REQUIREMENTS
If simple analog interfacing is required i.e. measuring resistance, the 16C5x
family may well suffice, however, if AID converters and interrupt functions The new PIC12C50819 (8 pin devices) have the option to use either an
are needed, the 16C7x family will fit the bill or if non-volatile data storage external oscillator or it's own internal 4MHz oscillator - saving 2 pins for 110.
is needed, then the 16C84 is the logical choice.
The next stage is to provide external reset components or brown out reset
A comprehensive list of products is given in the back of the book, but it is protection if required. Some of the 16Cxx family have brown out detection
advisable to consult the Microchip data sheets or web site for the latest as part of the internal circuitry with an additional testable bit in the PCON
product information. 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.
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.
(m A decoupling capacitor of 100nF should be connected across
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.
TO THE MICROCHIP PIC Hardware Des,gn A BEGINNERS GUIDE TO THE MMlCROCHlP PIC
I
Reset Circuitry 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
Reset circuitry is important within a microprocessor/microcontrollersystem if the supply voltage falls below a pre-set value, ensuring an accurate
for the following reasons:- protection against brown out.

To ensure that a known state exists for certain registers i.e. program Oscillators
counter, I10 and control registers.
To allow the clock sufficient time to settle at the correct frequency. The PIC will accept crystal and RC oscillators in a number of options.
To ensure that if there is a dip in the supply voltage that the micro restarts
16C5x PIC suffix
properly.
-XT Crystal or Ceramic Resonator - general purpose - 4MHz max
The PIC has built in Power On Reset circuitry. If the power supply to the PIC -RC ResistorICapacitor time constant - low cost - 4MHz max
rises at a rate greater than 0.05VlmS i.e. < IOOmS OV to 5V, then the internal -HS Crystal or Ceramic Resonator - high speed - 2OMHz max
reset circuitry will cope. -LP Crystal or Ceramic Resonator - minimum current - 40kHz max

Some low frequency crystal oscillators need greater than 18mS to start up. Windowed devices can be programmed to any of the above configurations
In this case, and in those cases where the power supply takes longer than for development purposes, suffix -JW.
IOOmS to rise, an external RC reset circuit may be required In applications
The latest version of the 16C5x family now have an A suffix following a
where there is a likely hood that the supply rail may dip or brown out (not
number and package type. The main difference with the A suffix devices is
a complete loss of power), extra reset circuitry needs to be added to ensure
that the oscillator type is chosen at the programming stage as opposed t o
a clean reset following a brown out.
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.

T' ' y R 4 1 h MCLR AI


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
-
L I and resistance of R may also effect the frequency stability.
BASIC RESET CIRCUIT RESET WITH BROWNOUT DETECT
Selection graphs and tables are shown in the data sheets to assist in the
choice of components.
If you are using an RC oscillator, a clocW4 will be avdlnt~leo ~ \1 1 . deg C. so a 4MHz 16C54 in plastic would be PIC16C54-XTP and a 10MHz
OSCZICLKOUT pin. This could be used within your circuitry to drlvs A/ 16C84 in SO industrial temp would be PIC16C84-1011SO.
converters, LCD driver chips etc.
110 Circuit

PORT A 16C5X

OUTPUTS \

PORTA 1
10 PINS

INPUTS

TRlS PORTA

Ckck from A2
16
External System OSCl A3
PORT A 16CXX

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
7 DATA BUS

PORTA

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 16C7X ONLY I
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
LABEGINNERS GUIDE TO ThE MICfjKHp PC. -kid . I 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 t o the


( l mains should always be carried out w i t h an isolation
transformer and earth leakage protection. And
preferably with someone else around t o pick up the pieces if it all
ONLY
goes wrong.

An electric shock of :-
TERRUPT
5mA will cause a muscle spasm which could result in you catching
a hand on a protruding object or throw you backwards off a chair
t
GIE
t
INTE
t
RBlE
lOmA will cause severe pain
30mA will cause respiration t o cease
PORT B CONTROL AND INTERRUPTS 75mA stops the heart.

The basic 110 circuitry needed to interface to a PIC can be a push button and Skin resistance varies from 5k if wet with salt water t o 100k if dry
a LED. This is all that is required for one of the first examples to try with a -
and lightly making contact ohms law will teli you the rest.
PIC - press button, turn on LED.
lnterfacing to the mains can be achieved in one of two ways:-
The PIC can drive LED'Sdirectly and can sink 25mA or source 2OmA on a pin
-see data sheets for maximum port and device limits. This current capability a) an opt0 isolator
enables the PIC to drive a wide range of devices from LCD and logic b) 2 x 2.4M resistors in series with the mains input.
products to direct drive of triacs connected t o the mains. Both methods have their advantages and disadvantages.

On the 16Cxx family, there is a the facility to turn on a weak pull up on The opt0 gives safety, especially when the end user has access to the
PORT B. This is set in the OPTION register and eliminates the need for a circuitry so applications are completely isolated from the user.
resistor pack when PORT B is used for inputs.
On the other hand, lamp dimmers can happily run directly from the mains
h
hardware Des~gn

with capacitive power supplies and a resistor fed into one of the portr 1t1 On the other hand, if the sensor is boosted to 5V or the A/D reference is
provide zero crossing detection. 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
A2
potential divider providing they don't load the source.
A3 OSCl

BOJINT OSC2 Calculation of resistance is made by straight ratios as the current drawn by
MAINS 8
7 B2 AWMRO 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 t o
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.
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 t". TO PIC

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
IOR (Inclusive OR) XOR (Exclusive OR)
Software Design
Input A B Output Input A B Output
0 0 0 0 0 0
SOFTWARE DESIGN 6 3 0 1 1 . 0 1 1
I
1 0 1 1 0 1
Having understood the hardware and how to connect the PIC to the real 1 1 1 1 1 0
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 AND Compliment (invert)
following information may be familiar.
Input A B Output Input A Output
The software design comprises -
d3 0
0
0
1
0
0
0
1
1
0
an understanding of logical functions 1 0 0
hexadecimal notation . 1 1 1
source code writing
use of assembler directives Binary Addition and Subtraction
macros to save time writing code
program development This also needs to be understood when working with the PIC or other logic
the instruction set based systems.
internal registers
subroutines Addition 0 + 0 = 0 Subtraction 0 - 0 = 0
lookup tables 0+1=1 1-0=1
I10 port setup 1+0=1 1-1=0
reset vectors 1 + 1 = 1 plus 1 carried , 0 - 1 = 1 plus 1 borrowed
TMRO (RTCC) to next column from next column
WDT e.g. 0110 (6) e.g. 0110 (6)
interrupts 001 1 + (3) 0011 - (3)
the stack 1001 = (9) 0011 = (3)
AID conversion
E2 based PIC3 Hexadecimal Notation
Logic Truth Tables A microcontroller uses binary internally to operate. If a program is written
in binary it is unwieldy and difficult to debug.
When working with any logic based product, be it CMOS logic or a
microcontroller, it is important to understand how an Inclusive OR differs e.g. the value 11010100 in binary converts to D4 in hex, when added to an
from an Exclusive OR. As the PIC uses logical processes for data instruction such a ADDLW, the result becomes 11111011010100. It therefore
manipulation, the following truth tables are shown to add clarity to the becomes easier to write:
terms found later in the PIC instruction set.
BEGINNERS GUIDE TO THE MICRDCHIP PIC Software Des~gn Software Design A BEGINNEE GUIDE TO THE MICROCHIP PIC

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 II 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

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 0100 EOT DC4 $
5 0101 ENQ NAK %
6 01 10 ACK SYN &
7 01 11 BEL ETB '
8 1000 BS CAN (
9 1001 HT EM )
A 1010 LF SUB *
B 101 1 VT ESC +
C 1100 FF FS I

For larger numbers, use the following hex to decimal conversion table. D 1101
E 1110
-F 1111 I
BA WINNERS GUIDE TO M MICROCHIP PC Software Des~gn

This table will be used extensively for applications using serial what you want the software to do and show where you need to interface
communications and sending characters to intelligent displays such as 16 with the real world (110).
characters by 2 line.
't
Program Structure
The ASCII symbols in the above table are:
Start off at the top of your program with the header information. Things
NUL - Null DLE - Data Link Escape like who wrote it, when, what revision, which PCB the program ties up with
SOH - Start Of Heading DC - Device Control etc. This enables those reading the program to know how it stands in
STX - Start Of Text

3:
EXT - End Of Text relation to the rest of the design.
EOT - End Of Transmission ENQ - Enquiry
NAK - Negative Acknowledg ACK - Acknowledge Next place the equates, #define's, list p=16m etc. to enable the assembler
SYN - Synchronous Idle BEL - Bell t o do it's work. Then start the program with it's origin or 0RG statement.
ETB - End Transmission Block BS - Backspace
CAN - Cancel HT - ~orizontalTab An equate or EQU is a way of telling the assembler that where it finds a
EM - End of Medium LF - Line Feed name, to replace that name with the value it's equated to e.g. porta equ 5.
SUB - Substitute VT -VerticalTab
ESC - Escape FF - Form Feed Wherever the assembler finds the word porta within your program, it will
FS - File Separator CR - Carriage Return substitute the value 5 in it's place.
GS - Group Separator SO -Shift Out
RS - Record Separator
1 6 3
US - Unit Separator
51 - Shift In
DEL - Delete !
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
SP - Space (blank) DC1 -Xon
DC3 - Xoff d $ Wherever the assembler finds the word led, it substitutes 6.4 (or portb.4) in
Source Code Writing
dI 3 it's place.

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


' 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 t o
1 Always comment your software - you or someone else will inevitably portc.6 - the assembler does the rest ( but don't forget to change the port
need to come back t o the program at a later stage and without comments, I direction register if required ).
what made sense at the time will be garbage later. 1s:9 Labels are used as a marker to point the assembler to a specific line in the
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
(tlI 3 program i.e. goto test1 or caN convert

t o remember. An number of examples are found in the programs on disk. 69 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
3 Put all your subroutines in one area. With the 16C5x this should be at assembler commands should be indented. Comments are preceded by a

-
the top of each memory page (OO-FFh) - I will explain why later. 1
(ti 3
semicolon and are ignored by the assembler.

4 Prepare a flowchart or some form of drawing to help you remember


&! 4
Il)r --I A - d h -m
J BEGINNERS GUIDE TO THE MICROCHIP PIC Software Deslgn
I

e.g. ;CODE PROTECTION ONIO FF


;this is a comment ;SOFTWARE FUNCTION (describe what the code is actually for or what it
porta equ 5 is doing)
#define , led portaf3
org 0 LIST put the list o f assembler directives here - see below for further
start goto start details
end
;********GENERAL EQUATES *****
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. TMRO
PCL
EQU 1
EQU 2
,;;PROGRAM
COUNTER
COUNTER
TEMP EQU 5 ;sets the value 5 to TEMP STATUS EQU 3 ;STATUS REGISTER

ADDLW TEMP ;correct operation using TEMP ;add in additional equates for other registers and bits where required i.e.
other pic's
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 t o 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 ORG OOH ;change address depending on pic type see
loop around for ever, but it must not just stop in mid air. A program falling ,-reset vector section
off the end will continue to cycle and fails to make sense to anyone trying GOT0 INIT ;this is where you want the program to start
t o fault find - even though it may work sometimes!

Universal Header
INIT ;the program starts here
;WRITTEN BY ;YOUR PROGRAM
;DATE REV
;FILE SAVED AS xxx.ASM
;FOR PIC I6Cxx END ;and ends here - this must appear on the last line o f the
;RESONATOR 4MHz ;program so the assembler knows where to stop.
;WATCHDOG ENABLEDIDISABLED
The equates for registers can be saved as 16Cxx.H for example and be called temp 1 equ Och
up from within the source code by means of an INCLUDE "16Cxx.H" temp2 equ Odh
statement. The 110 equates can be omitted from P1C.H as their use will vary count equ Oeh
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. This can be replaced with :-

Sample headers are available via the Microchip web site and are also org Och
supplied with the MPLAB. temp 1 res 1
temp2 res 1 \
\\
Assembler Directives count res 1
this then allows additional labels to be inserted into the list of registers j
In addition to all the instructions used for writing code (ADDLW, MOWVF without re-assigning the registers.
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 IF ELSE ENDlF
control, direct or save time when assembling and has no effect on the
operation of the software. The result of incorporating assembler directives This directive allows customisation of a program at the assembly stage. An
will be seen in the .LST file after assembly. Some of these mentioned example of this could be to select the reset vector for a PIC based on the
already include #define and org. A full list is given in the MPASM assembler part number or in data comms where the number of bits, stop bit and
users guide, but some of the more useful ones are described here: parity could be selected when the program is assembled. This then allows
unused code to be left out - reducing the overall program size.
PAGE forces a page eject to allow sections of program to be printed
individually. 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
LINES sets the number of lines t o be printed per page. Useful when completely different. If however the IF ELSE ENDiF commands are used, at
printing to non-standard sheets of paper. each occurrence of a test for MSB being a 1 or 0, the appropriate code
would be inserted into the assembled program.
C specifies the column width for printing. C=80 is used for narrow
A4 size pages, C=132 for wide printers or condensed printing. e.g. IF MSB
rrf xmit-reg, f ;if MSB = true or 1 then this line will
INCLUDE pulls in external files into the program. A use for this is where ;be compiled
you have a file set up with pre-defined macros, a file with all the general ELSE
equates and register definitions for the processor t o a file containing a rlf xmit-reg, f ;otherwise this one will
large lookup table (thermistor voltage to temperature conversion). END IF

i t s use would be include "P1CREG.H" ORG specifies the origin for code following the statement. it is used to
or include "c:\picbnacros.asm " specify where the program starts, where a section of code begins (interrupt
vector for example) or where a block of memory will start.
RES reserves memory locations for use within a program. One way t o
define the register equates at the start of a program is LIST used to pass information t o the assembler regarding the
processor being used, lines per page, column width and format the Start off with at least 5 EPROM or an EEPROM version as you will soon
program has been written in (radix). become impatient waiting 10 to 20 minutes for erasure of a PIC.
As the devices get larger, so the erase time increases.
e.g. list C=80, n=55, p=16c84; r=hex In the case of 16C84 development, there is no EPROM version

Macros
( - the device is electrically erased when re-programmed.

If you are developing without an ICE, create a simple routine which can
Macros are a way of saving code writing by calling up commonly used flash a led on a spare pin. The call to this routine can then be moved within
routines from a library (via the include command). This saves the re-typing the program to determine where the program has reached or not as the
information time and time again and allows consistency in program case may be. If the LED flashes, the previous code was executed - if it didn't,
writing. A macro library could include bit testing, led flashing, ald then move the call further back in the program.
conversion routines, port setups, E2 routines etc. and can be called with just
one line of programming. The PIC Instruction Set
e.g. set-A0 macro ;this defines the start o f the macro The instructions can be split into 3 groups - Bit, Byte and Literal I Control
bcf adcon0,O operations.
bcf adcon0, 1
endm ;and this the end 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
would enable the following t o take place:- 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
set-A0 ;selects channel instruction cycles.
call conv ;call to a convert subroutine Lets start with the simplest -

This saves remembering which bits need t o be set or cleared for a particular Bit operations a

ald channel and when assembled, looks like this in the .LST file:
Instruction Status Affected Meaning
bcf adcon0,O
bcf adcon0, 1 BSF f,b none set the bit b in file f
call conv e.g. BSF PORTABITO ;turns bit 0 on on port a

Program Development BCF f,b none clear the bit b in file f


e.g. BCF STATU5,ZERO ;clears zero bit
There are three basic routes to software development. Using an ICE, using
a programmer and a handful of EPROM based PIC'Sor using the simulator. GOT0 k none the program jumps to label i address k
Even when you have an ICE, you will need a few re-programmable devices An example using these three instructions is
t o allow testing of the final product.
SQ BSF PORTA,BlTO ;set port a bit 0 pin high
g Software Des~gn

BCF PORTABITO ;set port a bit 0 pin low e.g. MOVLW OFH
GOT0 SQ ;goto SQ and do it all again OPTION ;loads OPTION
;register with OFH
This program generates a pulsing output on the Port A, Bit0 pin.
SLEEP T0,PD the PIC is placed in a sleep or
BTFSS f,b none test bit b in file f and if it is set i.e. standby condition. The register
logic 1, then skip the next contents are frozen and the PIC
instruction if it is logic 0 then do draws a fraction of the operating
the next instruction current On a wakeup from sleep, the
e.g. BTFSS STATUS,CARRY 16C5x family will jump to the reset
vector, whereas the 16Cxx family
BTFSC f,b none test bit b in file f and if it is clear i.e. continue on the next line of code. i
logic 0, then skip the next
instruction if it is logic 1 then do CLRWDT TO, PD the watchdog timer register is set
the next instruction to zero
e.g. BTFSC SWITCH1
TRlS f none the contents of W are placed in the
(16C5x, 12C50x only) port control register f, where f=5,
Byte operations
6 or 7
NOP none do nothing e.g. MOVLW B1llllOOOO'
e.g. NOP TRlS PORTB ;makes portb
;upper 4 bits inputs and
NOP ;wastes 2 clock cycles
;lower 4 bits as outputs
use this instruction to create short delays or allow ports and external
peripherals to settle between write and read operations. CALL k none a call is made to a subroutine
labelled k. the contents of the W
CLRW z clear or reset the contents of the register will be transferred for use
W register to zero within the subroutine if required
e.g. CALL TEMP-CONVERT
CLRF f z clear or reset the contents of file f
to zero RETLW n none return from a call or subroutine with a
value n in the W register
MOWVF f none copy the contents of the W e.g. RETLW 2OH ;returns to calling address + 1 with 20H in
register into the file f ;the W register
e.g. MOVWF TEMP
MOVLW n none the value n is moved into W
Literal 1 Control Operations e.g. MOVLW 36H

OPTION none copy the contents of W into


d i, IORLW n Z the value n is inclusive ORed to W
(16C5x, 12C50x only) the-option register ,.' I
(5. $ e.g. IORLW OC4H

siI 9
)BEGINNERS GUIDE TO THE MICRKHIP PIC Software Des~gn Software Des~gn s
ANDLW n Z the value n is ANDed to W in the W register leaving the contents
e.g. ANDL W 8'0000011' ;will mask off all but the lower 2 bits of the file TEMP alone

XORLW n Z the value n is exclusive ORed to W XORWF f, d Z ' exclusive OR the contents of W with
file f and place the result in
This example tests for equality between the contents of register TEST and a I destination d
number VALUE in the W register.
ADDWF f, d C,DC,Z add the contents of W with file f and
MOVF TES7;W ;store contents in W place the result in destination d
XORLW VALUE ;exclusive or the contents o f W e.g. ADDWFDAT-IN, W
;with VALUE
B TFSS -Z ;test Zero bit in Status register SUBWF f, d C,DC,Z subtract the contents of the W register
;ifcontents are the same, Zero bit from file f and place the result in
;is set destination d.
GOT0 NOT SAME ;not equal '
GOT0 SAME ;both are equal COMF f, d z compliment the contents of file f and
place the result in destination d
Byte operations specifying a destination
MOVF f, d Z movelcopy the contents of file f and
If the result destination is not specified in instructions like place the result in destination dl where
( IORWF, ADDWF etc., the default destination is the file - not d is either a file or W
the W register. If an operation on a file is t o be carried out
and the file contents are not intended t o change, ensure that W is specified z increment or add 1 to the contents of
as the destination. Alternatively specify the destination for ALL instructions file f and place the result in
which use a destination. The W register can not be specified as the file in destination d
INCF W for example nor another register such as INCF TEMeCOUNT. e.g.:
DECF f, d z Decrement or subtract 1 from file f and
ADDWF TEMP,W ;stores result in W register leaving place the result in destination d
;TEMP intact
ADDWF TEMR F ;stores result back in TEMP INCFSZ f, d none increment the file f and store the
;overwriting previous value result in destination d. if the result is
zero, skip the next instruction
IORWF f, d Z inclusive OR the contents of W with file e.g. INCFSZ TEMR W
f and place the result in destination d GOT0 LOOP
e.g. IORWF COUNTF places the result of the OR function GOT0 END-LOOP
back in the file COUNT
ANDWF f,d z AND the contents of W with file f and DECFSZ f, d none decrement file f and if the answer is
place the result in destination d zero, skip the next instruction. store
e.g. ANDWF TEMRW places the result of the AND function the result in destination d
RRF f, d C rotate or move all the bits one place t o BC k Branch on Carry BTFSC Status, Carry
the right. bit 0 ends up as the Carry bit GOT0 k
and the Carry bit becomes bit 7. the BDC k Branch on Digit Carry BTFSC Status, Digit Carry
I
result is put in destination d GOT0 k
BNC k Branch on No Carry BTFSS Status, Carry
RLF f, d C rotate or move all the bits one place t o
the left. bit 7 becomes the Carry bit GOT0 k
and the Carry bit becomes bit 0. the BNDC k Branch on No Digit Carry BTFSS Status, Digit Carry
result is put in destination d GOT0 k
BZ k Branch on Zero BTFSC Status, Zero
SWAPF f, d none the upper and lower nibbles are
GOT0 k
swapped over. the result is places in
destination d BNZ k Branch on No Zero BTFSS Status, Zero
GOT0 k
ADDLW n C,DC,Z the value n is ADDed t o W CLRC Clear Carry BCF Status, Carry -
CLRDC Clear Digit Carry BCF Status, Digit Carry -
SUBLW n C,DC,Z the value W is subtracted from n and
the result placed in W - NOT SUBTRACT CLRZ Clear Zero BCF Status, Zero
LITERAL FROM W as it is written! MOWF f Move File to W MOVF f,w z
NEGF f,d Negate File COMF f,f
RETURN none return from a subroutine leaving the INCF f,d z
contents of the W register as they were.
SET0 Set Carry BSF Status, Carry
RETFIE none return from an interrupt SETDC Set Digit Carry BSF Status, Digit Carry -
SETZ Set Zero BSF Status, Zero
OPTION and TRIS are only used with the 16C5x and 12C50x families and SKPC Skip on Carry BTFSS Status, Carry -
though they are accepted by the assembler, are not recommended for the Status, Carry -
SKPNC Skip on No Carry BTFSC
16Cxx family.
SKPDC Skip on Digit Carry BTFSS Status, Digit Carry -
PIC16CXX SPECIAL INSTRUCTION MNEMONICS SKPNDC Skip on No Digit Carry BTFSC Status, Digit Carry -
SKPZ Skip on Zero BTFSS Status, Zero
These instructions are recognised by the Assembler and substituted in the SKPNZ Skip on Non Zero BTFSC Status, Zero
program listing. They are a form of shorthand similar t o Macros.
SUBCF f,d Subtract Carry from File BTFSC Status, Carry
ADDCF f,d Add Carry to File BTFSC Status, Carry
DECF f, d z
INCF f,d Z
SUBDCF f,d Subtract Digit Carry from File BTFSC Status, Digit Carry
ADDCF f,d Add Digit Carry to File BTFSC Status, Digit Carry
DECF f, d z
INCF f,d Z
TSTF f Test File MOVF f,f z
B k Branch GOT0 k
To modify software t o run on a 16Cxx in place of a 16C5x1the code needs -
Register STATUS
t o be changed from:
Register address 03H - bits are Readwrite with the exception of TO & PD
'MOVLW OFH ;sets port a direction to upper nibble
TRlS PORTA ;outputs lower nibble inputs bit 7
MOVLW 07H ;sets rtcc 1256 internal clock 16C5x PA2
OPTION 16Cxx IRP RP1 RPO

-
to BSF RPO ;sets up page 1 o f registers
MOVLW OFH
MOWF TRlSA
MOVLW 07H
MOWF OPTREG Zero bit
BCF RPO ;restores page 0 o f registers 1 if result in w = zero
Internal Registers - Power Down bit
set to 1 by power up or
Even though some of the registers are common to each PIC, their position
CLRWDT set t o 0 by SLEEP
in the register map may vary. This is also true of the spare registers whose
Time Out bit
beginning and end addresses change from product to product.
set to 1 by power up SLEEP or I

See programmers card in back of this book or Microchip Data Book for details. CLRWDT set 0 by WDT timeout

Status Register Program page for C5x family


Register page selection on Cxx
This register contains all the arithmetic status of the ALU, the Reset status , Spare bits on C54 & C55
and the Page select bits. The contents of the Status register are updated
after certain instructions which modify the W register.
( Program Address Area) (Data Register Page)
Some instructions do not update the Status register (SWAPF = Page 0 (000H - 1FFH) (OOH - 7FH)
( DECFSZ, NOP etc.) - see full list in programmers card. = Page 1 (200H - 3FFH) (80H - FFH)
= Page 2 (400H - 5FFH)
When examining the Status register, use BTFSS and BTFSC commands t o 1 = Page 3 (600H - 7FFH)
look at individual bits as these commands don't effect the Status register.
Spare readlwrite on C5x series,
When writing to the register, use the BSF, BCF and MOWVF commands. e.g.
Indirect address bank select bit
MOVLW VALUE ;load VALUE into W on Cxx
SUBWF TEMeF ;subtract VALUE from TEMPstore result in TEMP 0 = Bank 0,1 (00 - 7Fh)
BTFSS -Z ;test status Zero to check if result is 0 1 = Bank 2,3 (100h - 1FFh)
GOT0 NOTZERO ;resulto0
GOT0 ZERO ;result = 0
5 Software Des gn Software Des~gn ,A BEGINNERS GUIDE TO THE WIICFIOCHP PC
A Carry occurs when bit 7 overflows (in an addition) or bit 0 is borrowed (in The following shows the use of a lookup table for BCD to 7 Segment
a subtraction) e.g. 1 subtracted from 00000000 gives 11111111 and the conversion. The value to be outputted is held in register OUTDAT and the
Carry bit cleared. A Digit Carry occurs when the a borrow or carry occurs display is attached to Port B. The output data is in the format x a b c d e f
between bit 3 and bit 4 in the W register. g for common anode LED displays, where x is an unused bit.
e.g. adding 1 to 00001111 gives 00010000 and the DC bit set.
MOVF OUTDA7; W ;load OUTDAT into W
Lookup Tables CALL CONVERT ;call conversion routine
MOVWF . PORTB ;send it to the display
A lookup table is an extremely useful method for data conversion and
CONVERT ADDWF PC ;add contents o f W to the program
reference, implementation with the PIC is very easy to perform.
;counter
RETLW 8'0 1000000' ;comp of 0 in 7 segment
This program converts temperature in Celsius to Fahrenheit. The Celsius
RETLW B'01001111' ;1
value is placed in the W register prior t o a CALL CONVERT, and returns with
RETLW BO
' OO 10010' ;2
the Fahrenheit equivalent in the W register.
RETLW B'00000110' ;3
RETLW B'01001 100' ;4
CONVERT ADDWF PC,F ;adds the contents o f the W register
RETLW B'00700100' ;5
;to the Program Counter and places
RETLW 8'0 1100000' ;6
;the result in the Program Counter
RETLW B'00007111' ;7
RETLW .32 ;lineOreturns32Fif W=O
RETLW B'00000000' ;8
RETLW -34 ;line 7 o f table
RETLW B'0000 1100' ;9
RETLW -36 ;line 2 o f table
conversion table Subroutine Placement

RETLW .81 ;line 28 o f table Subroutines should be placed at the top of pages. The reason being:-
RETLW .82 ;line 29 o f table
;the. in front o f the value signifies a decimal PROGRAM COUNTER
;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. These bits are
set by instruction
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. changed by GOTO,
forced to 0 by CALL
When returning from a CALL, the value in the W register
( will not effect the Status bits. If you need t o test for a 0 in PA0 (STATUS register)
a RETLW 0, add an IORLW 0 after the CALL statement to
allow an update of the Status bits. PA1 (STATUS register)
Software Des~gn .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 TIMES register gets incremented for each time slice that the Dl pin is
the destination) subroutines must reside in the lower half (first 256 words) low. When the pin finally goes high, the timing routine is exited and a
of a program page as this is the section automatically returned. If the comparison is made to determine if the pulse detected was a reset pulse. In
subroutine is placed in the upper half of a page, the CALL will result in the this case only the reset pulse was of interest.
program jumping to the called address less 256, in other words it crashes! .***************TIME MEASURE****X**********XXX*X**XX
I

Long Calls and Long Goto's TIM-CNV ADDWF PC,F ;add W to program counter
RETLW. 0
Long calls to subroutines or programs in other pages can be achieved by RETLW 0 ;this area is noise
setting the respective page bits first. 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****************

I I MAlN BTFSS PORTA,DI ;LOOK FOR START OF DATA


GOT0 MAIN ;LOOP FOR START OF DATA
Page 0 Page 1 Page 2 Page 3 CLRF TIMES
The long call can be used where space is at a premium for subroutines at TIME1 INCF TIMES, F ;MEASURE DELAY LENGTH
the top of a page. In the above diagram, the CALL loads the PC into the CALL DELAY ;CALL TO TIME PERIOD SLICE
STACK - the GOT0 does not effect the STACK, but modifies the PC. The BTFSS PORTAID/ ;LOOKFORSTATUS
RETLW reloads the PC with the original contents of the STACK and hence GOT0 TlMEl
returns to the base page. MOVF TIMESIW ;LOAD TIMES FOR LOOKUP TABLE
CALL TIM-CNV ;CONVERT PULSE WIDTH
Pulse Width Detection IORLW 0 ;UPDATE STATUS REGISTER
BTFSC STATUSIZ ;TEST FOR ZERO RETURNED
This code example uses the RETLW in a lookup table to determine if a reset ;FROM TABLE
pulse has been sent in amongst a series of other pulses. The routine GOT0 MAlN
TIM-CNV converts the result of how long a signal was present on the Dl line the rest of the program continues here
t o the type of pulse detected. This method of pulse width testing can be Inputs I Outputs
expanded to look for logic 1,O or noise.
Before any I10 can be undertaken, the port control registers must be set up.
In the MAlN routine, the Dl bit is tested for active low and when this occurs, These determine whether the port is an input or output, or in the case of

4
1
BEGINNERS GUIDE TO THE MICROCHIP PIC Sofrware Des~gn Software Des~gn ;A BEGINNERS GUIDE TO THE MlCR@€dilPPIC a

the 16C7x analog or digital. This register has only 2 bits 0&1 (3 bits for the 16C7314) and is at address 88H
(Page 1).
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 It is very important to set up this register on the C7x as the default
1=INPUT, O=OUTPUT is analog inputs on reset and therefore requires modification for
digital 110 port operation.
e.g. code for a 16C5x
To set up PORT A as digital inputs, the following code can be used in the
CLRF PORTB ;ENSURE PORT IS CLEAR initialisation section:
MOVLW OOH ;MAKE PORT OUTPUT
TRlS PORTB ;DO IT CLRF PORTA ;CLEAR PORT BITS
BSF RPO ;CHANGE TO PAGE 1 OF REGISTERS
To establish a port for mixed input and output on a 16Cxx, the result could MOVLW B'00000011' ;SET UP DIGITAL BlTS
be: MOVWF ADCON1 ;DO IT
MOVLW B'0001 1111' ;SET UP AO-A4 AS INPUTS
CLRF PORTB ;ENSURE PORT IS CLEAR MOWIIF TRISA ;DO IT
BSF RPO ;REGISTER BANK 1 BCF RPO ;BACK TO PAGE 0 OF REGISTERS
MOVLW OFH ;MAKE BITS 0-3 INPUT AND 4-7 OUTPUT
MOWF TRlSB ;TRANSFER TO PORT DIRECTION REGISTER Lets start with a simple task - press a button and turn on a LED. The push
BCF RPO ;REGISTER BANK 0 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.
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. READ1 BTFSS SWITCH ;TESTFORSWITCHCLOSURE
GOT0 $-1 ;IF OPEN LOOP AND RETEST
Output ports are latched and written to by a M O W F PORTx. BSF LED ;IF CLOSED, TURN ON LED
BTFSC SWITCH ;TEST FOR SWITCH TO OPEN
Individual port bits can be modified with a BSF and BCF command and read GOT0 $-1 ;IF CLOSED LOOP AND RETEST
with a BTFSS or BTFSC command. BCF LED ;TURN OFF LED
GOT0 READ1 ;GO BACK TO START
Bi-directional ports need special attention when writing
code. Instructions like BCF and BSF read the whole port into The $ in the GOT0 is used in place of a label and means this
the ALU, execute the bit operation and then write the whole line, 0-1 refers to the previous line and a Q+2 means two lines
of the ALU back to the port. Care must be observed in such circumstances further on.
t o 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 A modification to the above program enables a toggle action to take place.
would still be present in the port output register. The ON button is attached to PORTA,BITO and the OFF button to
PORTA,BITl. The LED is on PORTB,BITO.
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 Design f
READ1 BTFSS SWITCH1 ;TEST FOR SWITCH CLOSURE
GOT0 $-I ;IF OPEN,LOOP AND RETEST
BSF LED1 ;IF CLOSED, TURN ON LED MOVLW OFH ;enable OUT4 & OUT8
I BTFSS SWITCH2 ;TEST FOR SWITCH CLOSURE ;inputs are active low, outputs
GOT0 $-I ;IF OPEN,LOOP AND RETEST ;are active high
BCF LED1 ;TURN OFF LED MOWF PORTA ;doit
GOT0 READ1 ;GO BACK TO START CLRF PORTB ;clear PORT B and latch outputs
MOVLW 03H ;set all I10 inactive
If the software makes use of successive operations t o the I10 ports, it must MOVWF PORTA ;do it
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 I10 EXPANSION USING EXTERNAL CHIPS
(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 The following example has been used to measure the phase angle, and
were required to interface to a PLC 6 relays, a stepper motor and 3 opt0 hence the output power of a light dimmer with respect to a mains
isolated mains feeds - all connected t o a 16C55!. 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
Interfacing is relatively simple. With Port A connected as the control to the 64H) output measurement of power and will be determined by the clock
74HC devices, Port B can be used as Inputs and Port C as Outputs. speed.

Alternatively all the lines from the buffers andlor latches could be ;***********PHASEANGLE MEASURMENT******************
connected to Port B with the software controlling both the latcheslbuffer ;RETURN VALUE IN HEX IN REGISTER 'POWER' IN RANGE.0 TO 64H
selection and the port direction control register. This method of I10 ;CALLS DELAY - a time intervals to give 100 steps in half a mains cycle this
expansion could be used with the 16C54 where the I10 is expanded to 32. ;delay will be dependant on the clock speed of the PIC
ANGLE CLRF POWER ;PRELOAD 100 PERCENT Reset Vectors
MAlN BTFSS PORTB,REF ;HOLD AND WAIT FOR
;REFERENCE VIA OPTO After a reset has occurred, the PIC sets the Program Counter to a pre-set
' GOT0 MAIN ;CLEAN EDGE value. This is needed to ensure you have a known program start point.

MA2 BTFSC PORTB, REF ,-TEST FOR BIT The Program Counter reset addresses are :-
GOT0 MA2 ;LOOP
6TFSS PORTB, TEST ;TEST FOR DIMMER OIP PIC Reset Vector
;VIA OPTO
INCF POWER, F ;INCREMENT DIMMER REG 16C54, 16C55, 12C508 1FFH
CALL DELAY ;W A I T A WHILE 16C56, 12C509 3FFH ?I

BTFSS PORTB, REF ;CHECK FOR END OF CYCLE 16C57 7FFH


GOT0 MA2 ;LOOP 16C58 7FFH
RETLW 0 16Cxx, 12C67x OOOH

RAM resetting and clear 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
The following program clears file registers 08H to 1FH i.e. all the spare and what to do.
registers. The program uses the File Select Register and the Indirect
Addressing Register For the 16C5x family, use this as the reset routine:-

MOVLW 8 ;move literal 8 into W


M O W F FSR ;move the value 8 into
;the file select register (4) ORG lFFH ;change this value for PIC used
LOOP CLRF INDADD ;clear the contents o f the GOT0 INIT ;specifies where to start program
;file pointed to by the file select register starts here***************
INCFSZ FSR, F ,-increment the FSR and store the I

ORG 0 ;The program memory start address


;result back into the FSR
INIT ;the actual start of the program.
GOT0 LOOP ;repeat until all files are cleared

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


the program continues here **

This addition t o the start of a program is highly


recommended for new programmers. If using an ICE, the old ORG 0 ;the reset point
register values may still be displayed - this does not give a INIT ;the actual start o f the program.
true picture as a program is stepped through.
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.
c
b BEGINNERSGUIDE To ME MICROCHIPPIC &
I
7
A BE GUDE TO THE MCFIOCHIP PIC

Bit Test from the RETLW 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 RETLW command does not affect the status register, so in order to The Option Register has 6 control bits associated with the TMRO and are
determine if the value passed from the subroutine is a 1 or 0 for example, best shown:-
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 bit 6 5 4 3 2 1 0 PRESCALER
Status register. register RBPU RTS RTE PSA PS2 PSI PSO RATE
0 0 0 2
-
TMRO Interrupt uses 16Cxx only 0 0 1 4
0 1 0 8
The TMRO interrupt can be useful when handling pulse strings coming in 0 1 1 16
from outside sources - motor speed controllers for example. The interrupt 1 0 0 32
occurs when the TMRO overflows from OFFh to OOH. By preloading the 1 0 1 64
TMRO, the time interval before the overflow occurs can be varied. This can 1 1 0 128
be especially useful in applications requiring precise timing intervals where 1 1 1 256
the internal clock can be used as the TMRO source (TIME4.ASM). Prescaler Assignment
0.. TMRO
An application using the TMRO interrupt could be a watering system where 1.. WDT
a flow sensor feeds i t s pulses into the TMRO input, via the prescaler to TMRO Signal Edge Increment
average the flow, and into the RTCC register. If a 16C71 is used, then an 0.. Low - High on TMRO Pin
input from a potentiometer can be used to change the preload value to the 1 .. High - Low on TMRO Pin
TMRO and hence varying the metering factor for a water valve - see PIC TMRO Signal Source
Cookbook Vol 2 for full circuit and software. 0.. lnternal from CLKOUT
1 .. Externallon TMRO Pin
RTCC (Real Time Clock Counter) - TMRO Port B pull-up - 16Cxx only
0.. enabled
The TMRO is clocked by either an internal or external signal. External signals 1.. disabled
are buffered by a schmidt to reduce the likely-hood of false counts. For
applications such as speed control, rate indicators or frequency counters, The TMRO allows accurate timing or event counting to be carried out while
use the TMRO with an external clock feed. The internal clock feed to the programs are running.
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. 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
The TMRO can be configured with a pre-scalar to average or slow the of the bit test on the TMRO at label LONG2 will change the length of the
inputted signal to a more acceptable rate for the software to handle. delay loop as will changing the TMRO prescaler.

Resetting the TMRO t o zero is accomplished with a CLRF TMRO instruction,


the pre-scalar will also be cleared. The pre-scalar is also cleared with a
M O W F TMRO or BSF TMRO, 2.
INIT MOVLW 8'1 00001 11' ;TMRO PRESCALER I256
OPTION ;256uS PER COUNT
GOT0 MAIN
A4lTOCKI

;******* LONG DELAY I6mS * VALUE IN W REGISTER [Xt TOCS PSA TMRO

A
LONG CLRF TM RO ;CLEAR TO START WDT ENABLE INTERRUPT

MOWVF COUNT ;USE THIS REGISTER TEMPORARILY

1
O N OVERFLOW
(1 6Cxx)
LONG2 BTFSC TMRO, 5 ;TEST RTCC BITS 64*256uS = l6mS I I

GOT0 B- 1 lwA;;pGtjpsAH~l PRESCALER


(pso-psz) NOTE
CLRF TMRO ;YES, SO CLEAR RTCC
BlTS PSA. TOCS AND PSO-2
DECFSZ COUNTF ;DECREMENT UNTIL ZERO ARE I N THE STATUS REGISTER
?
GOT0 LONG2
RETLW 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 WATCH D O G
TIMEOUT
TMRO under software control.

MO VLW B'xxOxOm' ;1 SELECT INT CLOCK AND PRESCALER


Ft-3
I
TIMER 0 AND WATCHDOG TIMER

OPTION ;2 IF NEW PRESCALER VALUE IS 000 OR errors in the software or external electrical spikes. The WDT provides a type

CLRF TMRO
;3 001 THEN SELECT ANY OTHER
;4 VALUE AS TEMPORARY
;5 CLEAR TMRO AND PRESCALER
4.9 of heartbeat to the PIC in that if you don't clear the WDT register a t regular
intervals, it forces the PIC to reset.

This is an excellent feature and comes into its own for applications such as
MO VLW B'xxxxlxxx' ;6 SELECT WDT BUT NOT PRESCALER
OPTION ;7DOIT security systems where you can't afford a lock up on the main control panel.
CLRWDT ;8 CLEAR WDT AND PRESCALER
MOVLW B'xxxxlm' ;9 SELECT NEW PRESCALER VALUE &
I
Products that have to conserve power and only need to be turned on
periodically also benefit from the WDT for example a pocket pager might
Lines 1 & 2 are only required if an external TMRO source is used. Lines 7 & only require a 10% on time to successfully operate.
8 are necessary only if the desired prescaler value is 000 or 001. ei
Configuration of the WDT is via the OPTION instruction on the 16C5x and
This method of changing between TMRO and WDT avoids a RESET I9 12C50x family and by writing directly to the Option Register (81 h) on the
16Cxx. The Option Register has 4 control bits associated with the WDT and
condition.
are best shown:-
Watch Dog Timer (WDT)

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
I

bit 3 2 1 0 PRESCALER TO PD Reset caused by I

register PSA PS2 PSI PSO RATE TIMES (APPROX)


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


-Prescaler Assignment * GOT0 SCAN ;NOT SET SO WATCHDOG TIME-OUT -t
0.. TMRO ;ELSE FIRST TlME POWER UP
1.. WDT
MOVLW B1OOOO11 1 1' ;SETUP PORTA
The remaining bits in the Option Register are associated with the TMRO TRlS PORTA ;ALL INPUTS
(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 It is important to ensure applications which do not use the
5V or the temperature is anything other than 25C, then the time will vary. ( WDT but are put in a SLEEP mode, do not have the WDT bit
See the data sheet for guidance of time versus temperature and voltage. By set during device programming. It is easy to forget when
use of the pre-scaler bits in the Option Register, the time-out period can be programming a number of associated products like a transmitter and
extended up to 2.35. The WDT is cleared or reset with a SLEEP or CLRWDT receiver, that the receiver needs a WDT to prevent lockup but the
command. The software therefore has t o issue either of these commands to transmitter needs only to be activated by a button press. In this case if the
prevent the WDT from causing a Reset. transmitter has i t s WDT bit programmed, the program just loops and never
e.g. manages to transmit.
MOVLW B1OOOOO11 1' ;TMRO PRE-SCALER 1256 e.g. ORG OOH
OPTION ;WDT NO PRE-SCALER
MAIN CLRWDT ;CLEARS WATCHDOG EACH TIME START CALL INIT
;PROGRAM PASSES THIS POINT 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
For secure or safety critical code include only one CLRWDT instruction in the BCF PORTA,LED
main loop, as the more CLRWDT instructions there are, the less effective it SLEEP
will be.
In noisy environments it is advisable to update the OPTION
When a reset is generated, two bits in the Status Register indicate what ( and TRlS registers at regular intervals.
caused the reset. These bits are TO and PD (Time Out 81 Power Down).
~BEGINNWSGUIDE TO THE MICROCHIPPIC Software Design :
ME A BEGINNERS GUIDE TO MICROCHIP PIC
I

CALL

12C50x
16C5X

RESET
I; I (MAKE THIS
A NO,,
PC R E T L W xx STACK 1

STACK 2 + >2 C A L L S
CRASHES
PROGRAM

INTERRUPT INTERRUPT
EXECUTED

PROGRAM
RESETS JUMPS TO

R E T L W xx
RETURN
+
f CALL
or I N T E R R U P T
\

I PROGRAM
CONTINUES k HANDLE
INTERRUPT I STACK 2

STACK 3
The Stack
STACK 4
On the 16C5x and 12C50x family there is a 2 level stack. When a CALL is
STACK 5
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. STACK 6

If another CALL is made without a return, the value of STACK 1 is STACK 7


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 Substitute anything available to hand in place of Blue-Tack.
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 The 16Cxx and 12C67x families are provided with an 8 level stack so there
not picked up by the Assembler and can lead to no end of development should be no problems in program crashing due to stack overflow unless
problems. The ICE or simulator can detect a stack overflow or underflow. 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
A method I have adopted to overcome this is to use lumps of BlueTack. you out.
Besides giving me something to take my frustration out on, I move a lump
lnterrupts
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 lnterrupts are used t o alter the normal flow of a program to perform some
RETLW statement do I move the lump back from right t o left. other function e.g. to pause data transmission when a message is received
on a data comms system.

All
lnterrupts take the form of two distinctive types - software and hardware. MAlN BTFSS PORTAO ;Test input and if low then
The software interrupt is used in circumstances where the microcontroller GOT0 INPUT-1 ;branch to label INPUT 1
has no inbuilt interrupt capability - this is called polled software. On the BTFSS PO RTA,I
other hand, the hardware interrupt has all the hooks and control GOT0 INPUT-2
mechanism built into the microcontroller. BTFSS PORTA,2
GOT0 INPUT2
A polled interrupt has an advantage over hardware interrupts in that you BTFSS PORTA,3
know the status of all the registers etc. when an interrupt occurs, however, GOT0 INPUT-3
the interrupt will only be accessible to the outside world when you poll the GOT0 MAIN ;none o f the above so look again
port. On the other hand, the hardware interrupt acts instantly.
Interrupt Driven Software
Software or Polled lnterrupts
The 16Cxx devices have inbuilt interrupts but can also use the polled
The PIC16C5x family do not have a hardware interrupt capability and will technique if required. lnterrupts are a very useful feature for
need to use polled software. 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.

FUNCTION
1

INTERRUPT PROGRAM
SOURCES

FUNCTION

4
POLLED SOFTWARE INTERRUPTS INTERRUPT DRIVEN SOFTWARE

The following example is used to monitor a change on a port set up as an The priority of interrupts is determined by the order in which
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 interrupt flags are read in the interrupt handler.

The port is initially read and the contents stored in a register. When the The hardware interrupt can be configured to cause the program to jump to
POLL routine is called, the current port status is compared with the previous another section of code when either an internal or external event occurs. In
value and if a change has occurred, a lookup table determines where the the case of the 16C71, interrupts can be selected from 4 sources:-
program will branch to.
completion of an AID conversion POP swapf S-Save ,W ;Restore Status reg
I
an external interrupt from PORT B bit 0 mowvf status ;without changing any bits
a change in state on PORT B bits 4 t o 7 swapf W-Save ;Restore W reg without I
TMRO overflow from FFH to OOH swapf W-Save ,W ;changing the status bits
retfie ;Return from interrupt
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 Upon entering an interrupt handler, it is important to check if the interrupt
program is waiting for the E2 write to be completed. 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
Any of the above will cause an interrupt to the main software flow. Only INTCON and other registers and acting accordingly.
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 Before an interrupt can occur, the respective 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
( enable bits need to be set together with the Global lnterrupt
Enable (GIE) bit in the INTCON register - see data sheet for
and before issuing the RETFIE command. If any changes have occurred, the full information.
software can be looped back to the interrupt entry point where the type of
interrupt is determined.
INTERRUPT

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 ADDRESS

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 ALL FLAGS
CLEARED
located in its place. INTERRUPT
FLAGS

ORG 04h ;Interrupt Vector


PUSH movwf W-Sa ve ;Preserve w reg
swapf status, W ;Preserve zero flag DO R O U T I N E S
IN I N T E R R U P T
mowvf S-Sa ve ;Save the status register & CLEAR FLAGS

;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 INTERRUPT OPERATION ON 16CXX
Page boundaries in Program Memory and how to cross them - If the program calls a subroutine in another page - as above - the current
16C5x family 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
The 16C56, 16C5718 have a program memory of 1024 and 2048 words be modified prior t o any further CALL or GOT0 statements required by the
respectively each 12 bits wide - equally divided into pages of 512 words. To current page. Failure to do so will take you to the previous page.
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 Look closely at the way you write the code and location of subroutines as
of the address can be used the 3 remaining bits form the instruction. each CALL to another page adds at least 4 instructions t o the program.
The extra 2 bits required are found in the status register - bits 5&6. These 16Cxx CALLs to data tables.
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 - Great care should be taken with CALLs to data tables outside program
7FFH. memory 00 to OFFh.
To access code in another page, first set the correct page select bits in the
Take the case of a lookup table starting at 120h which is called from say
status register, then use a CALL or GOT0 instruction to execute the move.
address 1IOh, upon execution of the RETLW xx statement, the program will
The 9 bits following a GOT0 plus the 2 page select bits form the full 11
jump back to address 11 h.
bits which is loaded into the program counter. The program then continues
t o execute from this point. (note: the subroutines must still reside in the
In order to ensure the program will return to the correct point in the
lower half of each page.)
software ( I IIh), a page selection needs to occur, as with the 16C5x series,
Any subsequent CALL or GOT0 instructions will keep the program running but this time the bits are held in the PCLATH register. PCLATH holds the
in that page. upper address bits for the program counter and is not automatically
updated by certain instructions. In order to get over the problem of
An example of such a program covering multiple pages is:- programs skipping back to the base page, the correct page selection should
be made within the PCLATH registers. I
ORG OOH ;start o f the program this is page 1
The above call then becomes:
BSF STATUS,BITS ;set up the page select
BSF STATUS,BIT6 ;bits for page 3 BSF PCLATH, BIT0 ;indicating page 1 (100h to 1FFh)
CALL PAGE-3 ;call the subroutine CALL CONVERT

BCF STATUS,BITS ;reset the page select bits at which point the RETLW xx will restore the program to address 111 h.
BCF STATUS,BIT6 ;to the first page Remember to set the bits in PCLATH back to the correct page following the
# CALL to prevent further confusion.
;continue with program here
AID Conversion Block
ORG 0600H ;Page 3
PAGE3 ;the subroutine The A/D converter block on the 16C7x is made up of a number of registers
RETLW 0 ;return back t o select and control the various options. As the A/D input is fed via Port A
1
Software Des~gn

(and Port E on the 16C74), there is an added requirement t o select between - -


Register - ADCON 1 Port A Control address 88H bits 0&1 are - I
analog and digital. Readwrite bits 2-7 not used - power on reset value OOH

The default port configuration for the 16C7x family is bit 1 0 AO,Al A2 A3 Vref
( ANALOG not digital - so ensure you set up ADCON 1 correctly. 0 0 Analog Analog Analog Vdd
0 1 Analog Analog Ref Input A3
The registers associated with the whole AID and Port A block are:- 1 0 Analog Digital Digital Vdd
1 I Digital Digital Digital
ADCONO channel select, conversion clock, AID onloff, interrupt flag
and startlend conversion The following example illustrates the AID converting a voltage from a
ADCONI input selection for analog or digital multiturn potentiometer connected between OV and Vcc. The voltage is fed
ADRES result of AID conversion into A0 and the binary result is displayed on Leds attached to Port B. This is
TRlSA input 1 output select for digital selected bits only a section of a program - the full program ADC1.ASM is on the
PORTA input 1 output read 1 write register for digital selected bits accompanying disk.
INTCON AID interrupt enable
MOVLW 8'1 1000001' ;SETAID INTERNAL RC CLOCK
Below are the registers and their bit usage for the 16C71 - see data sheet ;CHANNEL 0, AID RUNNING
for other 16C7x devices. M O W F ADCONO ;DO IT

- - -
Register ADCON 0 Control and Status address 08H - all bits are
Readwrite power on reset value = OOH
MAIN MOVLW .10 ;LOAD DELAY TIMER ,
<
bit 7 6 5 4 3 2 1 0 MOVWF TEMP
ADCSI ADCSO spare CHSl CHSO GOIDONE ADlF ADON DECFSZ TEMe F ;WAIT A WHILE FOR
GOT0 $-I ;SAMPLE & HOLD
AID switch . ;TO SETlLE BEFORE
1= on 0= off ;CONVERSION
AID Interrupt BSF ADCON0,GO ;START CONVERSION
flag I = complete BTFSC ADCON0,GO ;TEST FOR END OF
GOT0 5-1 ;CONVERSION
Conversion StartIEnd
I = Go O= Done MOVF ADRES, W ;LOAD AID RESULT INTO W
M O W F PORTB ;DISPLAY IT
AID Channel Select GOT0 MAlN
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
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
1 I GOT0 $-I.
BCF RPO ;Return to page 0 registers
TRlSA MUX ;Data is now in EEDATA register
85H CONTROL

Writing data to the E2 has to follow an exact sequence otherwise no write


takes place. Non interrupt driven example

- PORTA
7
ADCS1
6
ADCSO
5
CHSZ
4
CHSI
3
CHSO
2
GOIDONE
1
ADIF
0
AWN
WRITE MOVF W TEMP1 ;Temp 1 holds the address
;o f ram to write
I OSH
I ADCONO
MOVWF EEADR ;Move the value into
;address register
AID CONVERSION BLOCK - 16C7~ MOVFW TEMP2 ;Temp2 holds data to
-
16C84 The EZbased PIC
MOWF EEDATA
;be stored
;Move the value into
The 16C84 has E2 (electrically erasable) memory for both program and data ;the data register
storage areas. The data storage area is a non-volatile storage and is in BSF RPO ;Page 1 registers
addition to the static ram data registers. In all other respects, the 16C84 BSF EECON1, WREN; Enable the write
behaves as any other device in the family. The advantage of the E2 over the MOVLW 55H ;Must use these next 4 lines
windowed devices for development is in cost -there is no windowed 16C84. MOWF EECON2 ;in this exact
An ideal application is in alarm systems which either modify their own code MOVLW AAH ;sequence in order for
or learn codes from the users - no external non-volatile memory is required MOWF EECON2 ;the data to be written
t o maintain data when power is removed. BSF EECON1, WR ;Write the data
BTFSC EECON1, WR ;Wait for write to finish
Programming of the data E2 takes approximately 10mS per byte and must GOT0 $-1
follow a set procedure in order to work to minimise the chances of spurious BCF RPO ;Return to page 0 registers
writes. Data read takes only 3 clock cycles. RETURN

The following block diagram illustrates the structure of the registers It is advisable to separate the read and write routines in case of program
associated with the E2 block. errors.
4

To read data from the E2 During programming, both program and data E2 can be written using a
READ MOVFW TEMP ;Temp holds the address PICSTART Plus programmer.
;o f ram location to read
Assemble Software s
9 I 9 EElF WRERR WREN WR RD 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 t o 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.
EEADR
But before we can assemble a program, we need one written.
09H
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.
16C84 DATA E2 DATA BLOCK
Other Periferals in the PIC family. 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
*3 condition, set or clear the output accordingly.
We have covered some of the many periferals available across the range of I
PIC3 available from Microchip. Setting up RS232 communications, PWM,
SPI and 16 bit Counters are relatively easy once you have mastered the The flowchart for this follows with the program written along side for
basics of register setup and manipulation. Examples covering the use of clarity.
these periferals can be found in PIC Cookbook 1 & 2 as well as Microchip
Application notes. Three versions of the program are included on the disk to show the
differences between various processors. The files are:-
LEDI-54.ASM - 16C54 version When assembled, the .HEX file used t o program the PIC looks like this:-
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 Attempting t o debug a program by examining the .OBJ or HEX file is
0000 OCOF 0024 INIT MOVLW OFH ;set up port a as inputs guaranteed t o get you committed.
0001 0005 0025 TRlS PORTA ;do it
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
000B 0406
OOOC OA06
0036
0037
0038
0039
0040
GOT0
BCF
GOT0

ORG
OFF
LED
;not so loop until released
;button released - turn off led
MAIN ;loop back to start

1FFH ;reset vector for 16C54


FlTURN O N

01FF OAOO 0041 GOT0 INIT


0042
0043 END ;the end of the program

Comment field
Instruction

Line Number
Actual Code
Memory Location
v OFF LED
,P BEGINNERSGUIDE TO THE MICROCHIPPIC at
ioftware
DP~LP i a r a 3 r 3
TO THE M~CROCMIP
PIC
I
PROMATE CE The PROMATE CE is a universal programmer which can
Debug Software & Hardware 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
Development and Debug software. Approx £250

Once the product has been designed and software written, the product PICMASTER CE This is the Windows based In Circuit Emulator with real
needs to be debugged to eliminate all the potential problems and to fine time trace, hardware breakpoints, program step, code modify and external
tune the design to ensure it meets the original specification. This section of trigger inputs together with source level debug and on line help - uses
the product design can sometimes take the longest. either an internal card for standard PC's or PCMCIA adapter for laptops.
Approx £ 1500
A number of tools are available to meet engineering as well as financial
requirements. ICE PIC This is the Windows based In Circuit Emulator with
hardware breakpoints, program step, code modify and external trigger
In this section we will cover: 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
development tools , also available with real time trace. Approx £550
software simulator /

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

Development Tools and Systems MPASM The universal assembler for all the 16C and 17C
devices. Various Intel HEX formats are available as well as an output for
Development tools fall into various degrees of function and price. The PRO MATE, PICSTART Plus, ICE PIC and PICMASTER tools. Supplied as part
simplest development kit comprises a PC, programmer and UV eraser (not of MPLAB.
needed for the 16C84). This allows basic development using the program -
try modify loop. 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
If code trace, breakpoint and single stepping are required or a faster is provided. The DOS version needs a stimulus file to run. Supports all 16Cxx
development time is called for, then an ICE is needed. The ICE comes with and 17Cxx devices.
various levels of function and priced accordingly from those not running at
full speed to the ICEPIC and PICMASTER running under Windows. f uzzyTECH Fuzzy logic development tool running under
Windows. Full simulation and integration of code into existing products.
PICSTART Plus This is a Windows based development environment Two versions are available - explorer and full (dongle protected). Both
(MPLAB) with built in assembler, simulator and serial port programmer. It versions come with a development board and tutorial.
can be used to develop and program any of the PIC devices from 8 to 40
pin. Approx £ I20 Bulletin Board Microchip BBS accessed via local telephone numbers to
obtain all the latest product information, application notes, development
Debug S o h a r e & rlaroware A BEGINNERS GUIDE TO THE MICROCHIP PIC

software, silicon release notes and special interest groups to discuss your Controller setup
problems with other users or Microchip engineers. There are also some E

Internet mailboxes running Microchip product discussion groups. Click on the OPTIONS button again, then on the PROCESSOR SETUP option,
then HARDWARE. This will open up a window that allows selection of
SEEVAL Serial EEPROM development board which performs E2 options that are available to the designer when devices are being
read and write functions for test and development. This is ideal for solving programmed. These options include the assignment of I10 functions, clock
those awkward problems with EEPROM applications. 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.
Total Endurance Serial EEPROM endurance modelling. The software is
supplied in both DOS and Windows formats to help predict life expectancy Beneath this line is a tool bar. This tool bar gives access t o the commonly
for products incorporating E2 technology. The calculations are based on user used functions with out having to go through the menus. The button on
defined parameters and outputs the results in PPM or FITS. the extreme left toggles through the four tool bars available to us. Toggle
through the lists until a short tool bar with green icons appears. This is the
A full list of Microchip order codes is given at the back of the book. 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
MPLAB editing utilities and some debug functions. Move round again to the edit
tool bar and again to the debug tool bar.
Instalation of MPLAB.
Code Writing
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 Select FILE from the top line then NEW SOURCE. This will open up a blank
additional file BOOK3.EXE contains code examples in a compressed format screen called UNTITLEDI. Now cycle through the tool bars until you get t o
and is on disk 2. Copy this file into your PIC working directory and run the the edit tool bar. ( two clicks round from the green short tool bar )
file to extract the programs.
Some assembler issues
Starting MPLAB
The assembler is by default, case sensitive, so 'LOOP-1' is different t o
Double click on the MPLAB icon. The first thing to do is t o select the correct 'loop-1'. The instructions can be in upper or lower case but you must be
device from the PIC range to simulate. Move the cursor on to OPTIONS and consistent with labels and names. Comments are preceded with a semicolon
press the left hand button. This will open the usual Windows pull down ';' and can start anywhere on a line. Anything after a semicolon is ignored.
menu. Choose DEVELOPMENT MODE. Clicking on this option will give a Use lots of comments as it will make the code easier t o follow when you
small window in the middle of the screen. If the check diamond for MPLAB- have to change it in years to come.
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 I
...........................
processor box. From the list presented select the appropriate controller, the ;*** DEMO CODE 1
up and down arrows will offer you more options. Select the PlCl6C54 from I
...........................
this list and press the RESET box. Wait a few seconds for the software t o ; LAST MODiFlCATiON DDIMMIW
load the appropriate defaults. ; AUTHOR GORDON MACNEE
BEGINNERS GUIDE TO THE MICROCHIP PIC

LIST P= l6C54, F=INHX8M DECFSZ COUN7;F ;count down bits to be sent


GOT0 LABEL-1 ;go again until all sent
INADD EQU OOH ;Indirect A DDress register
RTCC EQU 01H ;RTCC ;when we get here we have shifted out 8 bits o f data and
PC EQU 02H ;Program Counter ;can move on to the next operation
STATUS EQU 03H ;STATUS register
FSR EQU 04H ;File Select Register GOT0 COLDSTART
PORTA EQU 05H ;Port A 110 register
PORTB EQU 06H ;Port B 110 register ;the last thing we do is tell the assembler that we are finished
;NOTE: all assembler directives must be tabed in
#DEFINE Z STATUS,2 ;Zero flag - bit 2 o f STATUS reg
#DEFINE C STATUS,O ;Carry flag - bit 0 o f STATUS reg END
#DEFINE DATA PORTA,O
#DEFINE CLK PORTA, 1 ORG 1FFH
GOT0 COLDSTART
;RAM registers
COUNT EQU 07H ;general purpose RAM Now that we have typed all this in lets save it. Go t o FILE on the top line
SFT-REG EQU 08H ;general purpose RAM 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
ORG 00 .ASM is what the assembler will look for as a default.

;set up the 110 pins Defining the project

COLDSTART ;labels must start in the first column This operation will tell MPLAB which files we wish t o work with under a
;instructions must NOT start in the first column project name. Select PROJECT on the top line and click on NEW PROJECT
CLRF PORTA from the options offered. This opens a window that offers a number of
MOVLW B1OO1lllOO' default names and settings. Check that you are happy where the system is
TRlS PORTA saving files on your hard drive and edit the boxes if you are not. Then click
on OK t o move on t o the next window, which prompts you for the files
;load COUNT with the number o f bits to shift out being used in any given project. We only want EXAMPLE1.ASM so click on
MOVLW 08H this file and add it t o our list of project files. Then select OK again.
MOWVF COUNT
LABEL-1 To see what is happening within the PIC, go t o the WINDOW option on the
BCF CLK ;clear clock line top line and click on it. This will give us a pull down menu. Now click on the
BCF DATA ;clear data line following items, the menu will disappear with every selection so just
RLF SFT-REGIF; rotate contents o f register to place msb in carry reopen it by clicking on WINDOW again.
BTFSC C ;test carry b i t Open :-
BSF DATA ;is set then set data line Program Memory Window
BSF CLK ;set clock line high Special Function Register Window
File Register Window manage other aspects of typically larger projects and are fully described in
Stopwatch the help files.

Already the screen is beginning to look cluttered so to tidy things up by Starting to Simulate
resizing the open windows. Click within the Special Function Register
Window and then move the cursor to the vertical edge of the box and So we now have a .ASM file and a .HEX file. So lets try out the code. Cycle
when the cursor changes to a horizontal double arrow head press and hold through the tool bar until you get to the debug tool bar, ( the one before
down the left mouse button and move the edge in until you are happy with the short green bar ) and click on the RESET PROCESSOR button ( remember
i t s size. This procedure can be repeated for the horizontal edge and then that the software tells you what the button does down in the left hand side
repeated for the other windows as well. To move a window click on the top of the screen ). This simulates a power up situation or a reset from some
bar and with the button still pressed drag it to a more convenient area of other source. This will highlight the line that will be executed next. In this
the screen. For those already well versed in Windows this is second nature. 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
The Program Memory Window shows the instruction list that we expect the we do this we will see the highlight moving through our code and any
controller to execute. Currently this is all OFFFH with is the unprogrammed registers that are modified by the instructions will change colour and
state of a device. This looks like an XORLW OFFH instruction to the reflect the operation of the instruction. Thus we can slowly move through
controller. This display will change when we enter some code. The Special our code seeing what the controller will eventually do.
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 The other buttons have functions of - the green light is the go button and
pins in this window along with other registers that will be of interest. The will start execution of code until we halt it or it encounters a breakpoint -
File Register Window displays all of the registers available including the discussed later, the red light is the stop button and will stop the simulation
general RAM locations. The Stopwatch gives timing information based on and update all the registers. The 5th button will perform a single step
the frequency we are running our application. The system will work out unless the step is a subroutine. If it is a subroutine then it will run throuqh
from the number of steps taken how long blocks of code take to execute. 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
Select PROJECT on the top line again, and this time lets SAVE our project. will create a new watch window. We have seen how to display all the RAM
This means that we can load in this setup when ever we have had to leave registers in the PIC and how to show the special function registers, but what
MPLAB. 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
Now lets present our work to the assembler. We do this by leaving the the one in the background as this will look after itself. The one in the
editor tool bar and looking for the make tool bar. So step through the tool foreground is prompting us to enter those registers that are of special
bars until we get to the short green one and step through each key until interest. Click on COUNT the on ADD and notice that COUNT has been
you get to the button for BUILD ALL. Click on this one and we will present added to the window in the background. Now scroll the list down and click
our file to the assembler. Hopefully the assembler came back with a green on SHIFT-REG and add it to the background as well. We can return and
bar and a message saying 'success, no errors'. If it did not then click on OK add more values to this watch window or open more watch windows,
and a message box will appear. Now click on any message that starts which ever makes more sense. Click on OK and move the watch window to
'Error and this will take you to the line that is causing the problem.
...I a convenient area of the screen. This is where most of us are looking
Correct the problem and resubmit the file. It will be automatically saved through the magazines for a 21" monitor. If we step through the code as
before it is assembled. The other boxes offer options to control and is then we will notice that we do not load SHIFT-REG with any data. This
BEGINNERS GUIDE TO THE MICROCHIP PIC DeDug Software & hardware Debug Sohare & Hardware ,A BEGINNERSGUIDE To THE MICROCHIPPIC^
would normally be done by the application preceding this code segment, gives no information and is best ignored. Click on OK. This will leave the
but we can modify any of the registers whilst in simulation by double chosen button highlighted. We can now press the righthand mouse button
clicking the lefthand mouse button when pointing to the register in one of and for the list that appears select ASSIGN PIN. We can select any pin from
the watch windows. the list 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.
Lets load SHIFT-REG with some data. Double click on SHIFT-REG in the The most useful is normally Toggle.
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 when we are running code or single stepping through we can click on
Now we can see the effect on the I10 pins A0 and A1 as we step through this button and the selected I10 pin will toggle. Other options for
our code. This feature also allows us to skip over long delay routines by presenting stimuli i s to use a stimulus file that will change the state of I10
seeing that they work once then loading the registers used with much pins at specified times or steps. This is most useful for testing such code as
smaller delay values. We can also use this box to modify code but there are software UARTS or any other serial bit streams. We can also present a
nicer ways of doing this. We can see how long this will take by resetting the similar file that specifies a value to be loaded into a file at a specified time
timer at the start of the shift and at the end. This is where breakpoints can of step count. Great for simulating N D conversions and the like. More
be used. If we want to run the simulation as fast as we can up to a given details of how to present these files is covered in the simulator help files
point and then halt we set a BREAKPOINT at the instruction we want to and manual. Altogether offering a cost effective software test suite.
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 The above is a GET YOU STARTED introduction to the simulator. Many other
of use are the RUN TO HERE button and the BREAKPOINT button. If we features are explained in the online help and in the manual. Happy
click on the breakpoint option then we are rewarded with a line of code debugging - Gordon McNee.
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 PIC Project Boards
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 A range of Project Boards are available to show how the PIC works and how
are causing problems. As and when we encounter code that needs t o interface to the outside world. Designed for students and engineers to
changed, the most secure way is to edit the .ASM file on screen then flick form the core of a training course or they can be used as a quick hardware
through to the green button bar and reassemble the code. This means that development facility for code development. Use as part of a training
whatever modifications you have made to the code to get it working are program or structured course it is best accompanied by a PIC START Plus or
safely stored in the assembler file. similar programmer. The user will need some reprogrammable versions of
the PIC for development purposes or an ICE.
We have now seen how to inspect the PIC internals and we can see what is Contact your Distributor for details on these and other products available
happening on the I10 pins, but how do we simulate a user pressing a from Bluebird Electronics. A full product list is given in the back of the
button? There are four ways of introducing external stimuli. The most book.
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,
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 t o 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
c Program the PIC Program me PIC sA/3EGINNEFS GUIDE TO .TNMIGWCHIP PIC
Program Program the PIC'S with CP enabled and then verify against the 'Master'
device.
,
Verify
Test.
If not using a Microchip programmer, check there is no code
From within MPLAB, select PICSTART PLUS on the top line to enable the corruption when CP is enabled. Some third party
programmer. Ensure the PIC indicated matches the one the code has been programmers had an occasional problem with this.
developed for. Select PROGRAM and wait until informed OK. Remove the
PIC and test in your board. Serialisation

Code Protgction The PIC can be programmed with a random or sequential identification
number which can be used by the software.
Within the PIC, there are a number of special registers not accessible by
your program. The registers hold information on the oscillator By allowing a 'hole' in the software (in the form of retlw Offh) for each of
configuration, an identification number, if watchdog timer is active and the number locations to be used up to a maximum of 8. The PRO MATE
whether code protection is enabled. The' memory locations are software has the ability to firstly create the required file and then use that
programmed by a PICSTART PLUS or similar programmer. The default file to insert the numbers into the 'hole' during the programming phase.
setting for code protection is disabled.
This feature is of great benefit for programming alarm or transmitter based
If code protection is enabled, a 0 is programmed in the CP memory location products where each unit has i t s own unique serial number or code.
which inhibits the program code from being read. All memory locations Another application could be where a serial number is required for
above 040H are also protected from reprogramming. Memory locations 0 traceability and is outputted by the product upon request.
t o 3FH can still be programmed together with the ID and configuration
fuses. 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
ID and Configuration fuses can still be read after code protection has been shows the use in a 16C54 device.
activated.
org 0
There are two ways to check the contents of a PIC after programming if
Code Protection is required. numI retlw Offh ;first number
num2 retlw Offh ;second number
1 Program a PIC as normal, verify and then program the CP bit. This num3 retlw Offh ;third number
ensures full verification to the programming process but adds an extra
stage. init ;initialisation

2 Program a 'Master' PIC, verify and program the CP bit. Read back the main call numl ;returns with the contents in w
contents of the PIC and this gives you a checksum per byte. ;to be used in the program
rest o f program
eg 008 <-the last character for each memory location
Program the PIC

The addition of two lines cured the problem and the product is now in full
Org Iffh ;reset vector
goto init ;starts program after reserved block production with no bugs.
end
- INIT CLRF PORTA ;clear port a
Windowed Device Development CLRF PORT6 ;clear port b
MOVLW OOH ;load W with 00
Caution must be observed when developing with windowed devices. TRlS PORTA ;make port a all outputs
MOVLW OFFH ;load W with OFFh
Semiconductor devices are basically light sensitive and depending on initial TRIS PORT6 ;make port b all inputs
conditions set within the PIC, predictability or randomness can result. The MOVL W 6'000001 1 1 ' ;set up option register
standby current of a PIC in the sleep mode will also increase if light gets at OPTION ;do it
the chip.
Hint You can build your own EPROM eraser for a fraction of the cost
A semiconductor memory can initialise into one of two states - 1 or 0. Light of commercial units by purchasing a replacement UV tube, starter and
falling on the silicon can cause a bias towards on'e of these conditions and ballast. Ensure the box used to house the eraser is light proof and has a
only in the absence of light does the randomness show up. 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.
Some of the final product problems can be resolved by:-
Warning Do not code protect windowed PIC'Sduring development. Some
1 Always cover the package window except when erasing. 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
2 Always initialise I10 ports in a known state before configuring will result in a £35 OTP device! This is part of the overall protection scheme
them as inputs or outputs. This will eliminate glitches on I10 t o prevent your product being reverse engineered.
pins configured as outputs.
On windowed l2Cxxx devices, UV erasure removes the 4MHz oscillator
3 lnitialise registers into a known state. calibration value. Read this value and write it on the underside of the PIC
so it's there for the next time you program,
4 If the above points work, then only program a few devices and
test well. Why programs won't run
This will reduce the likely-hood of having a product called an OPTO-PIC! There are four main reasons why a program written, assembled, simulated
and programmed successfully will not run.
This example caused a product to work now and again.

INIT MOVLW OOH ;load W with 00 . 1) The oscillator configuration chosen during programming does not
TRlS PORTA ;make port a all outputs match the hardware. i.e. Crystal on PCB, RC Oscillator programmed in
MOVLW OFFH ;load W with OFFh PIC - result nothing.
TRlS PORT6 ;make port b all inputs 2) The watchdog bit was programmed into the PIC but the program has no
MOVL W B1OOOOO111' ;set up option register CLRWDT instructions - result program never runs for more than 18mS
OPTION ;do it before it's reset.
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. ,
PIC Proiens

PIC Projects
PIC Applications
-g
i-

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
Inspect Know the which have been converted across to the 16C84. All the programs have
Board Software 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


Check where a visual indication is required but battery power needs to be
Continuity 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
Verify state. When programming the PIC, ensure the Watchdog fuse is set. The
Take a
Schematics user program can be called from the points indicated to do whatever
Break
function is required.

erg 0 ; reset vector


btfss status,4 ; test power down bit
goto main ; warm reset
Understand

L
Components Get Help

init clrf portb ; clear port bits


pagel
movlw b'11111100' ; make bO output for led
movwf trisb
page0
;********** MAIN PROGRAM ..............................
DEBUG FLOWCHART main btfsc led1 ; test led status
PIC Pro,ects

got0 off movlw .1 I load/reload offset


bs f led1 ; turn led on as it was off movwf tmr0 I into tmrO
; insert your program here via a call movfw tmr0 I load tmrO value
pagel btf ss -z I test for zero
movlw b'10001010' ; 72ms on time got0 $-2 I loop
movwf optreg decfsz time1,f ; count down
page0 got0 osl I loop
sleep retlw 0 I return
off bc f led1 ; led is on so turn it off
; insert your program here via a call
TIME2-84.ASM - Basic time delay using I S tick to toggle an LED for
16Cxx - no interrupts I
pagel
movlw b'10001110' ; 1.15 sec off time
movwf optreg This example is identical to the previous example with the exception of
page0 register setup for timer 0. This provides an example on how to convert
sleep programs from one PIC to another.

-
Example Timer functions one-sec movlw
movwf
.245
timel
I

;
1s = 16uS * 255 * 245
save 1 second value
Even though various software examples exist for the PIC, a number of
osl movlw .1 load/reload offset
enquiries still come in for basic timer functions. This collection is included I

movwf tmr0 , into tmrO


t o assist those starting out. Try the spreadsheet file RTCC.XLS which enables movfw tmr0 load tmrO value
I

experimentation with the values for timer 0 (RTCC) without resorting t o btf ss -z test for zero
I

scopes and stopclocks. got0 $-2 loop


I

decfsz timel,f ; count down


TIMEI-54.ASM - Basic time delay using I S tick to toggle an LED for got0 0s1 loop
I

l6C5x retlw 0 Eeturn


I

The timer uses a prescaller set to I16 t o create a basic 16uS input into the TIME4-84.ASM - I S timer running under interrupt control toggling
tmrO register. The line:- LED

osl movlw .1 ;load/reload offset 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
sets up an offset into tmr0. This is nescesarry as tmrO is checked to see if it vector to 04h where the interrupt handler resides. After determining that
has rolled over from Offh to OOh and in the absence of interrupts, the only the interrupt is valid, the 1 second counter is decremented and tested for
other way would be t o test a bit in tmrO to determine how far the counter zero. If the result is a zero, the LED is toggled, otherwise the timer is re-
has progressed. By manipulating both the prescale and offset values, loaded with the offset for 50mS (60).
various time periods or delays can be created. I
erg OOh ; reset vector
goto init ; bypass interrupt vector
one-sec movlw .245 ; 1s = 16uS * 255 * 245
movwf time1 ; save 1 second value org 04h ; interrupt vector
9
btfss intcon,tOif ; test for tmrO interrupt LCD module plus 3 additional spare lines. The 74HC595 uses 3 lines from
goto end-int ; exit interrupt TMRO
the PIC (data, clock and latch) to operate. The LCD module requires one
decfsz timel,f ; count down 50mS periods
additional control line - Enable - to finish off the interface and this is
goto end-t0int
provided directly from the PIC. With all these interface connections from
1
to1 btfss portb,0 ; test led status the PIC to the latch, there are still 2 spare lines available. In this code
goto setl example, one has been used as an input from a push button. Following
bc f portb,0 ; if on then turn off initialisation of ports etc. the LCD is set up in a 4 bit mode. To accomplish
goto $+2 ; jump to reload 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
set1 bsf portb,0 ; if off then turn on 4 bits of DATA information for the LCD module plus the RS line status. At
movlw one-sec ; reload 1s timer - .20 the end of this routine, the Enable line is toggled.
movwf timel

end-t Oint The main program sends out a sequence of messages to the display and
movlw .60 ; reload tmrO with offset upon receiving a button press, sends a specific message.
movwf tmrO ; for 50mS tick
bc f intcon,tOif ; clear interrupt flag As the 12C508 has a 2 level stack, a software stack has been implemented
t o enable a 3 level call to operate. This can be seen in the following section
end-int retfie ; return from interrupt of code.
. * * * * * * * * * * * * * * * * * * initalisation . . . . . . . . . . . . . . . . . . . . movlw $+4 ; saves return point
init page1 ; macro movwf stack ; on stack
movlw b'10000111' ; /256 no pullup int osc movlw mesl ; load message number
movwf optreg call dostr ; send string
clrf trisb ; make outputs movlw 40h ; prog will return here
page0 ; macro
movlw b'10100000' ; gie on and tmrO int on dostr movwf chpt ; load character pointer
I
movwf intcon / / see listing for full code
movlw one-sec ; load 1s timer - .20 eos movfw stack ; restore software stack
movwf timel movwf pcl ; by loading pc
movlw .60 ; load tmrO with 50mS retlw 0 ; with return point
movwf tmrO

main goto main ; loop here The program has been successfully used on a 20x4 line display with minimal
modifications to the code.
-
Example Interfacinga 16x1 line display to a 12C508 LCD-508.ASM - - -
Example Battery Monitor VOLT-508.ASM
As the 12C508 has only 5 110 and 1 input lines, a normal interface to an LCD
The PIC12C508 is an ideal device for use in low cost and space critical
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 circuits. A simple battery monitor could be used for both portable and
fixed applications. One such area could be mains / battery door and
the use of a 74HC595 latch and this provides the DATA and RS line for the
BEGINNERS
GUIDE TO THE MICRDCHIPPIC 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 WAKEUP
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
BBEGINNERS
GUIDE TO THE MICROCHIPPC PIC Projecrs

INPUT

LOW READ T I M E R
VALUE

>

T U R N ON I

Voltage to be monrtored
C2
100nF
1 DELAY

1 DELAY

FLOWCHART FOR VOLT-508.ASM


PIC Prolens . A BEGINNERS GUIDE TO THE MlGROCHlP PIC

PORTB
INTERRUPT

KEYPAD

e3SLEEP

el
WEAKER R4
IWR

STORE

r-0 MATCH

POINTER

CIRCUIT FOR ALARM84.ASM FLOW CHART FOR ALARM84.ASM


lines. ,The book has been written to guide the potential user through the
Contact Numbers architecture, software modes and benifits derived from using this device.
The book also covers development tools and is supplied with MPLAB
Bluebird Electronics (editor, assembler and simulator) to enable development under Windows.
Contact - Nigel Gardner The book is rounded off with a number of worked examples including
Tel: 01380 7251 10 timers, sound generators, water descaler, data logger and light / motor
Fax: 01380 729556 control. Supplied withsource code examples and MPLAB on 2 disks rrp
email: info@bluebird-electronics.co.uk f 19.95
web http://www.bluebird-electronics.co.uk
Contact your distributor for order codes or look at the Bluebird Electronics
Microchip Approved PIC Training Workshops, Hardware Starter Kits, Web Page.
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
Part Numbers for Development Tools ~3 The Author

igel Gardner is an Electronic Engineer of some 20 years industrial


Microchip Development Tools

PICSTART Plus
(includes MPLAB)
16Cxx, 17Cxx, 14000, 12C50x
N experience in various fields. He owns Bluebird Electronics specialising
in PIC Support Products and Microchip Training Workshops. This is his
fifth book, the fourth on the PIC Microcontroller, his other book is A
ICEPIC5x Practical Introduction to Electronics (from bits to chips) co written with Max
16C54, 55, 56, 57, 58
Horsey.
add on board for 12C508,9
l6C620, 621,622
Nigel is a member of the Microchip Consultants Group.
16C62,63, 64,65
16C72,73,74
16C71, 61, 710, 711
16C84, F83, F84

Most 16Cxx and 17Cxx

PRO MATE II 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
PIC Pinout

MCLWVpp
AOIANO
AlIANI
AZ1AN2
A3ANWref
A4TTOCKI
ASIANSISS
VSS
A2lAN2 OSClICLKlN
WAN3Nref OSCHCLKOUT
A4iTOCKI CMlOSOTTICKI
MCLWVpp Cl/T10~I/CCP2
vss CZ'CCPI
BOIINT C3ISCWSCL
BI
82
B3

MCLWVpp 87
AWANO 86
AIIANI B5
A21AN2 64
A3IAN3Nref 83
A4TTOCKI BZ
TOCKl OSCIICLKIN A5IANSISS B1
EOIRDIANS BOIINT
Vss Vdd EllWWAN6 Vdd
BO 87 WCSlAN7 vss
Vdd D7lPSP7
VSS D61PSP6
OSClICLKIN D51PSP5
OSCHCLKOUT D41PSP4
CMlOSOITICKI C7lRWDT
c 1 m OSIICCPZ CWTWCK
C2lCCP1 CVSDO

T%i
C3ISCWSCL CUSDIISDA
WPSPO DWPSP3
!ghKFElN DlIPSPl DZ'PSP2
OSCZ'CLKOUT
vss C7
NC C6
A0 C5
A1 22 C4
A2 21 C3
Pmduct Tlnvfi ICSP " Other Features I mn
Equivalent
I
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~nkper 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~nkper 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
I
I
PIC16CR578 I28P. 28JW, 28SP. 28SO. 28SS
I
1
- 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,
~nternalosc~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 I/O.
r 2.5V - 118P. 18S0.20SS. IRJW
tbiiZ%~I i i i i i /
I I 1 I

3584 2048x14 128 20 13 - - - - - - l l Wlll Yes I 25mA source/smk per 1/0 I - 118P. 18SO. 20SS.18-
I ! Wlll Yes 20mA source and 25mA slnk per 1/0 - 1 18P. 18SO,18JW I

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

llWDl Yes I 25mA source/slnk per I/O, Capture/Compare/PWM I PICl6CR63 I 28SP, 28S0,28JW I
lt
Wl Yes 25mA source/slnk per I/O. Parallel Slave Port.
Capture/Compare/PWM PIC16CR64 40P, 40JW. 44L,

t~wnl Yes 25mA source/slnk per i/O, Parallel Slave Port,


I I I I I I 1 . 1 I I I . , . .
2 Caoture/Comoare/PWM I
PIC16CR65 I
40P, 40JW. 44L, 44PQ. 44PT

pK16C66 14336 8192x14 368 20 22 - USART/


12C/SPI
- Yes - llWUl Yes 25mA source/slnk per I/O. Capture/Compare/PWM - 28SP. 28SO. 28JW
I 1 I I I I I I I I I I I I
- USART/ - Yes - llWUl Yes 25rnA source/sink per I/O, Capture/Compare/PWM. - 40P. 40JW. 44L. U P Q , 44PT
pIC16C67 14336 8192x14 368 20 33 12C/SPI Parallel Slave Port
I I I I I
PIC16C620 896 512x14 80 20 13 1 - - - - Yes 2
-- I I Wlll Yes -
I25mA source/sink per I/O, pro~rammable
VREF.2.5V I - 118P, 18SO. 20SS. 18JW
I

p1c16~620A* 896 512x14 80 20 13 1 - - - - Yes 2 I I Wllt Y1.s 25mA source/stnk per I/O, programmable VREF - 118P, 18SO. 20SS, 18JW
*Contact Mlcrochlp Technology for ava~lab~ltty
date.
5
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'

PIC16CE625*
1792

3584
1024x14 (12TE1,

2048x14 ,,%%,
( I L O C,
20

20
13

13 - - - -
Yes

Yes
2

2
1+WDT

1+WDT
Yes

Yes
25mA source/s~nkper I/O, programmable VREF,2.5V

25mA source/s~nkper I/O, programmableVREF,2.5V


-
-
i W , 1850.2OSS. 18JW

18P. 18so. 2 0 s . 18Jw


J
"t
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 2 1+WDT yes


25mA source/s~nkper I/O, programmable VREF.
11,,,0
, ,I. on, - 40P.40JW. 44L. 44PQ. 44f'T

ski,
12

I)
,
II5AHT
II
II'sAlfl
vd;k~I
"
-
Yes

Yes
-

-
4+WDT

4+WDT
-

-
20mA source and 35mA slnk per I/O. 2 1/O wtth 60mA
smk, 4 Capture, externally expandable, 1cycle 8x8 mumply

20mA source and 35mA slnk per 1/O, 2 1/O wtth 60mA
s~nk,4 Capture, externally expandable, 1cycle 8x8 muttlply
-
-
64SP. W L , 681 64PT

64SP. 68U.68L 64PT


-
-
I
I *Contact Mlcrochlp Tachnology for a~nllalllll\ytl.1..
I
CAP -- Anoilofl lo 1)lfllInl CIIIWU~~U?
(:~~(rlurn
IIAC - I1
I l l d IIIAII~IIU Ciwt~rter
k ' - I I~VII,M
( I l n ~ wrn~t~~nable) SEz tm&. up to 1 6 bits
CCP
-
~:n~nurn/(:ort~paru/IWM la( 111184 I~!lc&lalwl
!Ira
--- t11I Bus Recewer/Transm~tter SMB = System Management Bus
I L =
:
I HEXADECIMAL TO DECIMAL

c
Key to PIC16 Family X

I CONVERSION Instruction sets

0 b Bit address within an 8 bit file register


1
d Destrnation select; d = 0 Store result In W (fOA).
2
3 d = 1 Store result In f ~ l ereglster f
4
5 Default IS d = 1.

1;
6 -

7 f Register file address (0x00 t o OxFF)


8
9 k Literal field, constant data or label
A A
B W Working register (accumulator)
C C
x Don't care location
D D 13
E E 14
F F 15
-
Usir Th~sTable For each Hex d~ait.
., .
find the
assoc ial value. Add the
Pin Diagram I

nun 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 + 768 + 128 + 15 + 41871
I I I 1 Decimal

I ASCII Character Set


PIC1 6C5X & PIC12C50X INSTRUCTION SET PIC16CXX BIT ORIENTED FlLE REGISTER OPERATIONS
PIC16CXX INSTRUCTION SET
The PIC16C5X, Microchip's base-line 8-bit microcontroller family, uses a 12-bit The PICIGCXX, Microchip's mid-range 8-bit microcontroller family, uses a
wide instruction set. All instructions execute in a single instruction cycle unless 14-bit wide instruction set. The PlCl6CXX instruction set consists of 36 lbff BCF f,b Bit clear f O+f(b)
otherwise noted. Any unused opcode is executed as a NOP. The instruction set instructions, each a single 14-bit wide word. Most instructions operate on a l b f f BSF f ,b Bit set f 1 + f (b)
is grouped into the following catagories: file register, f, and the working register, w (accumulator). The result can be lbf f BTFSC f ,b Bit test, skip if clear s k i p i f f (b) = 0
directed either to the file register or the W register or to both in the case of l b f f BTFSS f, b Bit test, skip if set s k i p i f f (b) = 1

"I":
PIC16C5X LITERAL AND CONTROL OPERATIONS
some instructions. A few instructions operate solely on a file register (BSFfor
I I. ANDLW
I
9kk 1 CALL
, k
k
AND hteral and W
Call subroutme
k
PC
AND
t
W '
1-' TOS, k-,PC
-
example). The instruction set is grouped into the following catagories:
PlCl6CXX LITERAL AND CONTROL OPERATIONS
PlCl6CXX SPECIAL INSTRUCTION MNEMONICS

004 / CLRWDT Clear watchdog tlmer 0 -t WDT (and prescaler


i f assigned) ADDCF f ,d Add Carry to ~ i l e
Goto address k + PC ( 9 bits) 39kk ANDLW k AND literal and W k .AND. w +W
(k IS nlne b~ts) 2kkk CALL
0064 CLRWDT
k
T
Call subroutine
Clear watchdog timer
PC t 1 + TOS,k +PC
0 + WDT (and prescaler
ADDDCF f ,d I
I

~ d Digit
d Carry t o File
i f asslgned)
+ PC ( 9 b l t s ) Branch GOT0 __
-
(k IS nine b~ts) Branch on Carry BTFSC 3.0
GOT0

I
oscillator
Branch on Digit Carry BTFSC 3,l
rats sort f W110 control reg f
+
Fkk XORLW Exclus~veOR hteral and W k .XOR. w + w I
BNC k Branch on No Carry
PIC16CSX BYTE ORIENTED FlLE REGISTER OPERATIONS

1 C f I ADDWF BNM) k Branch on No Digit Carry


f ,d Add W and f / W t f + d 1 oscillator
f,dlANDWandf
14f A N D W F I w .AND. f + d 3Ckk 1 SlJBLW
~~ ~ k. 1 Subtract
-...-..W from literal
~~
I .K. - w.. + w.. GOT0
06flCLRF fIcka;f 006f 1 T R I S f I~Tristateport f 1 W + I 1 0 c o n t r o l reg f BTFSC
040 C L L Clear W 3Akk I XORLW K 1 ExclusiveOR literal and W I k .XOR. w + w GOT0
24f COMF f , d C O lement ~ f .NOT. f + d
Clear Carry BCF
0cf DECF f , d Decrement f f - l + d
2Cf DECFSZ f , d Decrement f, skip if zero f - 1 + d, Clear Digit Car BCF

28f INCF 1f , d / increment f


3cf INCFSZ i ,
s k l u i f zero

I
f + l + d
d Increment f, skip f zero i t I + d,
b- -
07f f / ADDWF
9 I-
f , d Add Wand f
..
PIC16CXX BYTE ORIENTED FlLE REGISTER OPERATIONS

W t f ' d
Clear Zero
Move File t o W 5 3 E
MOVF

skip i f zero 05ffIAN~w~ f,d/ANDWandf I W .AND. f + d


10f / IORWF f , d I Inclusive OR W and f I w .OR. f -t d 0 1 8 f CLRF f Clearf o + f
20fIMOVF f,dMovef I f +d 0100 CLRW Clear W O + W SETC Set Carry BSF
02f I MOVWF f Move W to f I w + £ 0 9 f f COMF f , d C~mplementf .NOT. f + d SETDC Set Digit Carry
0 0 0 1 NOP 1 No operation o 3 f f DECF f ,d Decrement f f - 1 - d
~ ~ ~ I R L fF, d I ~ o t a t e l e f t f ,- -
reglsrer i
ylClel1. . . . . .Oh
OBff DECFSZ f , d Decrement f, skip if zero
O ~ f f INCF- f , d Increment f
f - 1 + d, s k i p i f 0
f + l ' d
SETZ
SKPC
Set Zero
Skip on Carry BTFSS
30f RRF f , d Rotate right f renster f OFff INCFSZ f , d Increment f, skip if zero f t 1 -t d, s k i p i f 0 SKPNC Sklp on No Carry BTFSC 3.0
q47.. . . . .Oh 0 4 f f IORWF f , d Inclusive OR Wand f w .OR. f -+ d SKPDC Skip on Digit Carry BTFSS
08f SUBWE f , d Subtract W from f f - w + d 0 8 f f MOVF f , d Movef f'd SKPNDC Skip on No Digit Carry BTFSC 3.1 -
38f SWAPF f , d Swap halves f f ( 0 : 3 ) t+ f ( 4 : 7 ) d 0 0 8 f MOW f MoveWtof w'f
+ SKPZ Sklp on Zero
18f XORWF f , d Exclusive OR W and f w .xoR f -t d 0000 NOP No operation
O D f f RLF f , d Rotate left f register F SKPNZ Sklp on Non Zero
PIC16C5X BIT ORIENTED FlLE REGISTER OPERATIONS 4 ~ 4 7 .. . . . .Oh SWCF f ,d Subtract Carry from File

4bf 1 BCF f , b / Blt clear t - BTFSC


5bf BSF f , b Bit set f 1 + f(b)
6bf BTFSC f , b Bit test, skip if clear skip i f f (b) = 0 DECF
8bf BTFSS f , b Bit test, skip if set s k i p i f f (b) = 1 MOVF f,l

You might also like