pic-mds training manual - carleton universitynagui/appnotes/microchip/pic/pic-mds... isbn...

384
PIC Microcontroller Development System Training Manual PIC-MDS

Upload: phungdung

Post on 21-May-2018

226 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PIC Microcontroller Development System Training Manual

PIC-MDS

Page 2: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

Copyright © 1996, 1998 Sirius microSystems. All rights reserved.

Second Printing.

Parallax is a Trademark of Parallax, Inc.PICmicro™ is a Registered Trademark of Microchip Technology Inc. in the U.S.A. and other countries.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by anymeans, mechanical, electronic, photocopying, or recording, or otherwise, without the prior written permissionof Sirius microSystems.

Sirius microSystems has taken care to trace ownership of copyright material contained in this text. However,Sirius microSystems will gladly accept any information that enables them to rectify any reference or credit insubsequent editions.

For conditions, permissions and other rights under this copyright, contact Sirius microSystems:

Sirius microSystems172 Harvard RoadWaterloo, ON N2J 3V3Canadatel.: 519.886.4462fax: 519.886.4253http://www.siriusmicro.com

ISBN 0-9681220-0-0 (Training Manual)ISBN 0-9681220-1-9 (Teacher’s Reference)

Disclaimer of Liability

This manual and the program subroutines included herein are written for the Sirius microSystems PICmicro™Development System and are provided on an “as is” basis, without any warranty, either expressed or implied.These materials are provided for educational use only, and Sirius microSystems does not assume any liability fordamages, either incidental or consequential, arising out of the application, use, or misuse of any of its softwareor hardware products. Sirius microSystems reserves the right, without further notice, to make changes to any ofits training materials, software or hardware referred to in this manual in order to improve its function, design orreliability.

Printed in Canada.

Page 3: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

3©1998 Sirius microSystems

10Table of Contents

1 What are Microcontrollers?......................................9Microcontroller Features .................................................................. 10Input/Output Ports ........................................................................... 10Input Devices ................................................................................... 11Output Devices ................................................................................ 12Memory ............................................................................................ 12Clock Circuit ..................................................................................... 15Processing Unit ................................................................................ 15Watch-Dog Timer ............................................................................. 15Chapter Summary............................................................................ 16Questions ......................................................................................... 17Assignments .................................................................................... 17

2 How do Microcontrollers Work? ............................19Processing Unit ................................................................................ 19Memory ............................................................................................ 20The Outside World Connection ....................................................... 20How do Programs get into the Microcontroller? .............................. 20Chapter Summary............................................................................ 21Questions ......................................................................................... 22

3 The Microchip PIC family of Microcontrollers ......23The PICmicro™ Product Range ...................................................... 23The 18-pin PIC16CXX Product Line ............................................... 24The PIC16F84 ................................................................................. 25Program EEPROM .......................................................................... 25Data EEPROM ................................................................................. 25RAM ................................................................................................. 26Input/Output Ports ........................................................................... 26TMR0 ............................................................................................... 26Watchdog Timer (WDT) ................................................................... 27Power-Up Reset Timer (PWRT) ...................................................... 27Oscillator .......................................................................................... 27RAM Register Files .......................................................................... 28STATUS ........................................................................................... 28PCL & PCLATH ............................................................................... 28IND0 & FSR ..................................................................................... 28INTCON ........................................................................................... 28Option .............................................................................................. 28EEDATA & EEADR .......................................................................... 28EECON1 & EECON2 ....................................................................... 28The PIC16C711 ............................................................................... 29Program EPROM ............................................................................. 29Analog-to-Digital Converter ............................................................. 29Chapter Summary............................................................................ 30Questions ......................................................................................... 31Assignment ...................................................................................... 31

Page 4: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

4 ©1998 Sirius microSystems

Table of Contents

4 Features of the PIC-MDS Development System ...33Power Supply Circuit ....................................................................... 35J1 ..................................................................................................... 35VR1 .................................................................................................. 35JU1 ................................................................................................... 35JU2 ................................................................................................... 36External I/O Connectors .................................................................. 36CON1 ............................................................................................... 36PICBUS............................................................................................ 37Microcontroller Related Circuits ....................................................... 37Microcontroller Socket ..................................................................... 37H2 .................................................................................................... 37Reset Button .................................................................................... 38Y1 ..................................................................................................... 38JU3 ................................................................................................... 38JU6 ................................................................................................... 39VR3 & VR4 ...................................................................................... 39Matrix Keypad .................................................................................. 39LED Output Indicator Bar Graph ..................................................... 40Intelligent LCD Display .................................................................... 40VR2 .................................................................................................. 40RS-232 Serial Port ........................................................................... 40JU5 ................................................................................................... 40H3 .................................................................................................... 41Serial EEPROM ............................................................................... 41JU4 ................................................................................................... 41PIC-MDS Default Jumper Locations................................................ 41Questions ......................................................................................... 42

5 Writing a Simple Program ......................................43Examining Source Code—Microchip Code ..................................... 44Source Code Conventions .............................................................. 45Some Other Common Source Code Conventions .......................... 46Examining the Program ................................................................... 47The Maclib Directive ........................................................................ 47The Device and ID Directives .......................................................... 47The ORG Directive .......................................................................... 47Program Code ................................................................................. 48Ending the Editing Process ............................................................. 49Chapter Summary............................................................................ 49Questions ......................................................................................... 50Assignment ...................................................................................... 50

6 Assembling a Program ...........................................51Assembling the Program ................................................................. 51Object Code ..................................................................................... 54Chapter Summary............................................................................ 54Questions ......................................................................................... 55Assignment ...................................................................................... 55

Page 5: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

5©1998 Sirius microSystems

7 Downloading a Program .........................................57Which Microcontroller Should I Program? ....................................... 57Programming ................................................................................... 57Downloading the Object Code......................................................... 59Running the Program ...................................................................... 60Reprogramming PIC Microcontrollers.............................................. 60Chapter Summary............................................................................ 60Questions ......................................................................................... 61Assignment ...................................................................................... 61

8 Looping ....................................................................63Infinite loops..................................................................................... 63Finite Loops ..................................................................................... 65Nested Loops................................................................................... 66Calculating Execution Times ........................................................... 68Chapter Summary............................................................................ 70Questions ......................................................................................... 71Assignment ...................................................................................... 72

9 Switch Input Programming ....................................73Interfacing to Switches .................................................................... 73Counting Switch Activations ............................................................ 76Switch Debouncing .......................................................................... 78Interfacing to Matrix Keypads .......................................................... 80Chapter Summary............................................................................ 84Questions ......................................................................................... 85Assignment ...................................................................................... 86

10 Calls and Includes...................................................87Include, CALL and RETURN ........................................................... 87Reading ROM Data Tables using Calls ........................................... 91Chapter Summary............................................................................ 96Questions ......................................................................................... 97Assignment ...................................................................................... 98

11 Interrupts .................................................................99Interrupt Registers and Flags ........................................................ 100TMR0 Interrupt ............................................................................... 100INT Interrupt ................................................................................... 101Port B Change Interrupt................................................................. 101EEPROM Interrupt ......................................................................... 101A/D Converter Interrupt ................................................................. 102Interrupt Service Routines ............................................................. 102Using Interrupts to Wake-up on Key Press ................................... 103Managing Multiple Tasks using the TMR0 Interrupt ...................... 106Chapter Summary...........................................................................111Questions ....................................................................................... 112Assignment .................................................................................... 112

Page 6: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

6 ©1998 Sirius microSystems

Table of Contents

12 Using the LCD Display .......................................... 113The LCD Interface ......................................................................... 113LCD Enable ................................................................................... 115LCD Register Select ...................................................................... 115LCD Read/Write ............................................................................ 115LCD Commands ............................................................................ 115LCD Initialization ............................................................................ 116LCD Display Addressing ................................................................ 117Absolute Addressing...................................................................... 118Relative Addressing ....................................................................... 118Displaying LCD Characters ........................................................... 118Creating Custom Characters ......................................................... 125CGRAM .......................................................................................... 125Chapter Summary.......................................................................... 129Questions ....................................................................................... 130Assignment .................................................................................... 130

13 Using the PIC16F84 Data EEPROM .....................131Using the PIC16F84 Data EEPROM .. 131Reading From and WritingTo the Data EEPROM .................................................................... 132Chapter Summary.......................................................................... 137Questions ....................................................................................... 138Assignment .................................................................................... 138

14 Troubleshooting ....................................................139Identifying and Isolating Faults ...................................................... 139Validating Your Hardware .............................................................. 139I/O Requirements ........................................................................... 139Shared I/O Lines ............................................................................ 140“Playing” the Computer .................................................................. 140Displaying Intermediate Values ..................................................... 141External Triggers............................................................................ 141Commenting Out Code .................................................................. 141Isolating Faults within Subroutines ................................................ 142Taking Breaks and New Approaches ............................................ 142Memory Page Boundaries ............................................................. 142A/D Converter Troubleshooting ..................................................... 144Simulators and Emulators ............................................................. 144Programming for Easy Troubleshooting ........................................ 144Plan, Plan, and Plan ...................................................................... 144Code and Debug Individual Program Tasks .................................. 144Modularize Your Code ................................................................... 145Comments...................................................................................... 145Chapter Summary.......................................................................... 145Questions ....................................................................................... 146Assignment .................................................................................... 146

Page 7: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

7©1998 Sirius microSystems

15 RS-232 Serial Communication .............................147RS-232 Basics ............................................................................... 147Receiving RS-232 Data ................................................................. 149Transmitting RS-232 Data ............................................................. 154Chapter Summary.......................................................................... 158Questions ....................................................................................... 159Assignment .................................................................................... 159

16 A/D Conversion .....................................................161The PIC16C711 A/D Converter ..................................................... 161ADCON0 Register ......................................................................... 162ADCON1 Register ......................................................................... 163Measuring Voltage using the A/D Converter ................................. 163Chapter Summary.......................................................................... 170Questions ....................................................................................... 171Assignment .................................................................................... 172

17 Interfacing to a Serial EEPROM ...........................173The 93LC56 Serial EEPROM ........................................................ 173The Serial EEPROM Data Frame.................................................. 174Serial EEPROM Instructions.......................................................... 174Using the SEEPROM..................................................................... 175Chapter Summary.......................................................................... 181Questions ....................................................................................... 182Assignment .................................................................................... 182

18 The Watch Dog Timer ............................................183Handling Software Faults using the WDT ..................................... 184Enabling the WDT ......................................................................... 186Waking the PIC using the WDT .................................................... 186Chapter Summary.......................................................................... 188Questions ....................................................................................... 189Assignment .................................................................................... 189

Apendix A - PIC-MDS Installation and Setup ............. A1PIC-MDS Professional Package...................................................... A3PIC-MDS Professional ..................................................................... A3PIC-MDS Hobbyist Package............................................................ A3PIC-MDS Hobbyist ........................................................................... A3PIC-MDS Requirements .................................................................. A4Windows 3.x and Windows 3.11 for Workgroups ........................... A4Windows 95 ..................................................................................... A4OS/2 Warp v.3 and OS/2 Warp Connect ........................................ A4Installing the Software ..................................................................... A4If you are using the PIC-MDS with the EPIC Programmer... ........... A4If you are using the PIC-MDS with a third-party programmer... ...... A5PIC-MDS Setup ............................................................................... A5Connecting the EPIC Programmer .................................................. A5Connecting the PIC-MDS ................................................................ A7Assembling and Downloading Programs ........................................ A8

Page 8: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

8 ©1998 Sirius microSystems

Table of Contents

Appendix B - Troubleshooting .................................... B1Troubleshooting ............................................................................... B3Software Installation ........................................................................ B3If the installation program does not work correctly: ......................... B3If the installed files are not in the volume or directory expected: .... B3Assembling Programs with ASM ..................................................... B3If you get a “Bad Command or File Name” message: ..................... B3If you get a “Fatal : [302] Unable to Open File” message: .............. B4“Error filename.SRC 1 : [202] Illegal Character” message: ............. B4Starting the EPIC Programmer Software ........................................ B4If you get a “Bad Command or File Name” message: ..................... B4If you get a “Programmer Not Found” message: ............................ B4If the object code of the file does not appear in the EPIC window: B5Downloading Programs ................................................................... B5If you get a “Verify Error at ” message: ........................................... B5Assembling, Downloading and Running Programs......................... B5If the PIC-MDS Chapter examples don’t work: ................................ B5Converting PIC-MDS Source Code ................................................. B6for Third-Party Tools ........................................................................ B6If you use a third-party assembler: .................................................. B6

Appendix C - PIC Macro Assembler Reference......... C1

Appendix D - Parallax Instruction Set Reference ...... D1

Program Pull-out References

Data Sheets

Page 9: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

9Chapter 1

Microcontrollers©1998 Sirius microSystems

What are Microcontrollers?

A microcontroller is essentially an entirely self-con-tained computer on a chip. Like personal computers,microcontrollers have memory, processing units, and in-put/output circuitry. Unlike personal computers, micro-controllers don’t have keyboards, monitors, disk drivesor mice—and programs are not loaded into microcon-trollers to change their function from playing games tocalculating finances. In fact, microcontrollers are pro-grammed to perform only one very specific task. Mi-crocontrollers are computers designed to control spe-cific processes or products. Applications that use mi-crocontrollers include household appliances, electronicdevices, automobile subsystems, electronic instrumen-tation, and even certain parts or functions of personalcomputers.

Microcontrollers are small and inexpensive allowing them to be built into, or‘embedded’ into, other devices to make these products more intelligent and easier touse. One microcontroller can replace a number of separate parts, or even a completecircuit. Product manufacturers stand to gain the following benefits by incorporatinga microcontroller in their design:

• increased reliability due to one microcontroller replacing many parts

• reduced inventory, simplified product assembly and smaller end products

• greater product flexibility and adaptability since features are programmed intothe microcontroller and not built into hardware

• rapid product changes by changing the program and not the hardware

Microprocessors such as the Intel Pentium™ get more main-stream attention,but microcontroller manufacturers such as Microchip sell hundreds of microcontrol-lers for every microprocessor sold.

What areMicrocontrollers?1

Microcontrollers arecomputers designed tocontrol specific processesor products.

It’s hard to believe, yet thissingle chip microcontrolleris a complete computer.

Page 10: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PB ©1998 Sirius microSystems

Microcontroller Features

Electronic designershave a great deal of choicewhen deciding on a micro-controller for their nextproject. A large number ofmicrocontroller familiesexist, with even greatervariations within each fam-ily. Manufacturers tailorthe features of each micro-controller or microcontrol-ler family to specific typesof applications. It becomeseasy for a designer tochoose just the features andmemory size that are re-quired for the application,keeping costs low by notbuying unneeded capabil-ity.

In general, all microcontrollers share some basic features. As a computer-on-a-chip, microcontrollers contain input circuitry to interface with their environment, aprocessing unit that executes the control program, permanent memory to hold thecontrol program, temporary memory to hold operating variables, a clock circuit toorchestrate operations, a timing circuit (usually called a watchdog timer) for reliabil-ity, and output circuitry to interface to other devices or processes. Optional featuresmight include specialized timing and pulse circuits, communication capability, ana-log input/output connections, or other inputs and outputs tailored to specific sensorsor transducers. In the paragraphs that follow, we will compare each of the basicfeatures of a microcontroller with those found in personal computers. We’ll do thisby looking at two typical control applications: a microwave oven, and an automotiveengine control computer.

Input/Output Ports

Most microcontrollers have built-in input/output (I/O) circuitry that makes iteasy for input and output devices to be added to them. Their input ports have specialfeatures such as counters, comparators, serial UARTs, or analog-to-digital convert-ers. Microcontroller output ports can often supply higher current to output devicesthan standard microprocessors and ordinary logic circuitry. By adapting themicrocontroller’s I/O circuitry to special applications, the need for external circuitryis reduced, allowing a single microcontroller to take the place of many other compo-nents.

Personal computers normally use I/O cards to add the type of functionality thatcomes built into microcontrollers. For example, most microprocessors found in per-sonal computers have general purpose I/O circuitry and require a serial/parallel I/O

MicrocontrollerFeatures

UARTs—Universal Asyn-chronous Receiver Trans-mitters—are used in serialcommunications.

Microcontrollers contain all of these functions on asimgle silicon chip.

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

Outside World

block1

Page 11: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

11Chapter 1

Microcontrollers©1998 Sirius microSystems

card to connect to modems, mice, printers and scanners. A SCSI or IDE interfacecard allows the microprocessor to connect to hard disks and CD-ROM drives. Ethernetcards allow connections to networks. In a personal computer, the device or applica-tion determines the type of interface card required to a attach a peripheral to thegeneral purpose microprocessor.

In the case of microcontrollers, the expected input and output devices and appli-cation determine the processor itself, since the processor incorporates all of the I/Ocircuitry. Often, microcontroller manufacturers produce different versions of the samebasic microcontroller model by changing the type of I/O ports it includes.

It’s easier to under-stand this concept if weuse a simple analogy. If ahousing contractor isready to buy a new vehi-cle for his (or her) busi-ness, a pick-up truckwould be better able tocarry lumber and bricksthan a Ferrari. In micro-controller families, just asin real life, choose the de-vice to fit the purpose.

Input Devices

Personal computers have standardized input de-vices—you wouldn’t buy one without a keyboard or amouse. You might add a joystick or scanner to your com-puter. Since microcontrollers are embedded into so manyproducts, their input devices reflect the function that theproduct performs. An engine control computer requiresvery little in the way of input from the user, but still hasmany input sensors. These would include throttle posi-tion sensors, crankshaft position or speed sensors, oiland coolant temperature sensors, exhaust gas sensorsand even wheel-speed sensors. The obvious input de-vice on a microwave oven would be the keypad on thefront of the unit. The door switch of a microwave is anequally important input device—just try (no, don’t try)cooking something with the door open! Some microwaveovens also include temperature probes or humidity sen-sors. It is the microcontroller’s job to know not onlyhow to cook your food, but also when it is safe to cookit, and when the food is done cooking.

Duh Homes went out of business shortly after young Harry took over whilehis father vacationed in the Carribean.

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

input2

ThrottlePositionSensor

ExhaustTemperature

Sensor

Tachometer

Page 12: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PB ©1998 Sirius microSystems

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

input3

DoorSwitch

1 2

30sec

10%

1min

30%

2min

50%

5min

100%

3

4 5 6

7 8 9

0

START

Stop

Power

Time CLR

Key Pad

7 Segment Display

Beeper

Magnetron

Output Devices

The output of a per-sonal computer is usuallydisplayed on a monitor, orcan come from a speakeras sound, or can be in theform of a print-out. Micro-controllers also connect toa variety of devices spe-cific to the application. Forexample the front paneldisplay on a microwave in-dicates the cooking timeand mode that was se-lected, but the microcon-troller also modulates thepower of the magnetronused to cook your food.The engine control compu-ter outputs ignition sparktiming, fuel injector dutycycle, and cooling fan op-eration. A number of to-tally different output de-vices can be controlled byone microcontroller.

Memory

Personal computers come with two types of memory:permanent memory and temporary memory. One typeof permanent memory—the Basic Input/Output System,or BIOS—is a read-only memory (ROM) that containsprograms which tell the microprocessor how to interactwith its peripheral devices, such as the monitor or key-board. Hard disks are another form of permanent stor-age for application programs. The applications are cop-ied from hard disk to temporary memory, or random-access memory (RAM). While the computer is turnedon, the RAM contains one or more active programs.When the computer is turned off, the contents of RAMare erased, so all programs and data must be saved inpermanent memory.

Microcontrollers have both permanent and tempo-rary memory on-chip. As in personal computers, ROMis the permanent memory that remembers its operatingprograms while the device is off. Since microcontrollershave no hard disk storage, and usually only one operat-

I/O Devices andMemory

The 7-segment display,beeper and magnetron areoutput devices specific to amicrowave oven.

Personal computers loadone or more applicationprograms stored on harddisk into RAM. The micro-processor then executes theapplication programs fromthe computer’s RAM.

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

Outside World

block1

RAMROM BIOS

HardDisk

Processing Unitmo1

Page 13: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

13Chapter 1

Microcontrollers©1998 Sirius microSystems

ing program, ROM is the only permanent memory theyneed. RAM is used only as a ‘scratch pad’ to hold tem-porary data and changing input or output variables. Amicrowave might use RAM to store the current cook-ing mode and the cooking time remaining. An enginecontroller would use RAM to hold a digital value rep-resenting the temperature, speed, or position of all ofthe inputs. The ROM in both the microwave oven andthe engine control computer holds the control programthat makes them work.

Even though both personal computers and micro-controllers use the same types of memory for similarfunctions, the relative amounts of memory are far dif-ferent. It is not uncommon for a personal computer to have from 500 Mb (millionbytes) to over 1 Gb (billion bytes) of permanent storage on the hard disk. RAMranges from 4 Mb to 128 Mb or more depending on the expected application pro-grams. Microcontrollers have far less memory, typically 512 bytes to 4 kb (thousandbytes) of ROM, and 20 to 512 bytes of RAM. Each byte contains one instruction, orone number or character. Why is there such a great difference in memory size be-tween computers and microcontrollers?

The memory size difference between com-puters and microcontrollers relates mainly tothe size and function of the devices. Microcon-trollers must be self-contained. Therefore, allof a microcontroller’s memory must fit onto asmall silicon chip in addition to the input/out-put circuitry and the processing unit itself. Therejust isn’t room on the chip for a large amountof memory. Also, the microcontroller has onlyone function and needs only one program whichoccupies a small amount of ROM. Since thereis only one active program, a large amount ofRAM is not needed to hold a copy of the activeprogram, and the program can be executed di-rectly from ROM. A small amount of RAM isnecessary only to hold any changing informa-tion during program execution.

Personal computers, on the other hand, require a temporary memory large enoughto hold a control program (the operating system of the computer—for example,Windows 95, or MacOS) as well as any application programs (such as a word proc-essor) and temporary data (the file being edited). The operating system is calledupon to hold information about how to use all of the input/output devices attached tothe computer as well, also requiring memory. The hard disk, or permanent memory,must hold all of the programs and all of the data while the computer is off. For thisreason, the hard disk is much larger than the RAM.

The difference in memory size between microcontrollers and computers can alsobe partially attributed to differences in the sizes and types of processing units. The‘bit-width’ determines how large a binary number the processing unit can handle.

Microcontrollers use ROMto store their operatingprogram. A small amountof RAM is necessary tohold variables and chang-ing data.

1 kilobyte is actually 210 or1 024 bytes. A megabyte is220 or 1 048 576 bytes.

RAM

ProgramROM

Processing UnitM02

In a typical microcontroller die,memory takes up a comparativelylarge amount of space.

Courtesy of Microchip Technology, Inc.

Page 14: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PB ©1998 Sirius microSystems

Typical computer micro-processors are 32-bit oreven 64-bit giving them arich instruction set andmany features—ideal forrunning many types of pro-grams. Computers typi-cally also have wide‘buses’ or groups of wiresthat connect to the memoryand peripherals. A 32-bitwide bus (8-bits to a byte,so this is a 4 byte bus) is

used to transport instructions and data to the 32-bit processor. The computer memoryneeds to be bit because it must feed four bytes at a time to the microprocessor.

Microcontrollers can be 32-bit, but since most control programs are fairly sim-ple and straightforward, 8-bit and 16-bit processors are very widely used. Loadingone byte at a time into an 8-bit processor requires four times less memory thanloading 4 bytes at a time into the microprocessor in the personal computer. The trade-off is that a one-byte number can encode fewer instructions than a 4 byte number,resulting in reduced instruction flexibility in the microcontroller.

Microcontrollers can contain four types of ROM: mask ROM, OTP ROM,EPROM, or EEPROM. Mask ROM is programmed with the designer’s applicationprogram during the chip manufacturing stage. As such, mask ROM is very costeffective for large quantities of a microcontroller with the same program. Since maskROM is permanent, a designer must be sure that no more changes are required to theprogram before committing to mask ROM. OTP (one-time-programmable) ROMallows the designer to program the microcontroller during assembly of the product.Code changes can be made at any time during the assembly cycle, giving the designermore flexibility and extra peace of mind for fixing the inevitable bugs. OTP ROMmicrocontrollers are only slightly more expensive than mask ROM versions, makingthem ideal for small to medium size production runs. EPROM (erasable-program-mable ROM) microcontrollers are programmed during assembly like OTP micro-controllers, but can also be erased with exposure to ultraviolet light. EPROM micro-controllers are distinguishable by their ceramic chip packages with a clear windowon the top. Since this elaborate packaging is more expensive than the typical plasticchip package, EPROM microcontrollers are most often used during program devel-opment or whenever changes are required to be made in the field. Engineers anddesigners can test and evaluate new programs and then just erase the programs tocontinue development. Finally, EEPROM (electrically erasable-programmable ROM)microcontrollers can be erased and re-programmed electrically, without ultravioletlight and so benefit from cheaper packaging. EEPROM microcontrollers can beembedded into complex assemblies and programmed or erased without removingthem from the circuit making them extremely flexible. Most EEPROM microcontrol-lers have a finite number of program/erase cycles, so continuous re-programming isnot recommended.

Memory

Microcontrollers require less memory than microprocessors with wide buses.

An embedded version of the32-bit PowerPC microcon-troller is being used as anengine control computer insome current cars.

ROM BIOS

ROM BIOS

RAM8 bit

RAM32 bit

8-Bit Processing Unit 32-Bit Processing Unitbit

The window of the PIC16C711 allows ultravioletlight to enter and erase theEPROM.

Page 15: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

15Chapter 1

Microcontrollers©1998 Sirius microSystems

Clock Circuit

The clock oscillator circuit is a required part of any processing unit, includingthose found in microcontrollers. The clock circuit generates a high frequency squarewave that is used to synchronize all internal operations. It is essentially the ‘orchestraconductor’ or ‘traffic cop’, ensuring that all parts of the processing unit maintainsynchronization.

Most microcontrollers include built-in clock circuits that can generate a range ofclock frequencies. A few external components are used to create the clock signal orto select the clock frequency. Clock signal frequencies can range from a few hertz toover 20 MHz. As with everything else in life, there are trade-offs involved in select-ing the clock frequency. Running the microcontroller at a higher clock frequencyresults in the microcontroller accomplishing a task more quickly than at a lowerclock frequency. Lower clock frequencies, however, reduce electrical current drainas well as operating power (and the heat produced during operation) prolongingbattery life as well as potentially increasing the lifetime reliability of the microproc-essor.

Processing Unit

The processing unit is the most important part of the microcontroller and definesthe features, functions and ease of programmability of the device or system to becreated. Electronic designers swear by their favourite microcontrollers with an al-most religious fanaticism, claiming theirs is the fastest, or the cheapest, or the mosteasy to use. It’s often very difficult to convert a seasoned programmer to another‘religion’.

The function of the processing unit is to execute the control program. In anymicrocontroller, the processing unit reads the instructions from the ROM (permanentmemory), decodes each instruction, and carries out one or more operations for eachinstruction. The speed at which these operations occur is controlled by the clockcircuit.

Watch-Dog Timer

Watch-dog timers were developed because control programs or devices can fail.When your personal computer software fails it’s relatively easy to recover. At most,you may lose a portion of a file and a few minutes of time while you restart yourcomputer. When the microcontroller operating your pacemaker fails, waiting in lineto see your doctor for a CTRL-ALT-DEL reset isn’t a desirable option!

Watch-dog timers are oscillator circuits independent of the main oscillator andare always running. Your program must be designed to reset the watch-dog timerduring its execution. If your program fails, the watch-dog timer will time out andreset the microcontroller, restarting your program from a known state.

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

Outside World

block1

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

Outside World

block1

InputCircuitry

OutputCircuitry

TemporaryMemory

PermanentMemory

Processing UnitClockCircuit

TimerCircuitry

Micro-ControllerBlock Diagram

Outside World

block1

Page 16: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PB ©1998 Sirius microSystems

Chapter Summary

Chapter Summary

Microcontrollers are built in many varieties to perform very specific functions,whereas personal computers are available with only a small variety of general pur-pose microprocessors. Microcontrollers are more suited to specific control tasks wheresize and cost is a concern. Because a microcontroller is a single chip computer, amicrocontroller can offer a single-chip solution to a design problem. While they aresingle-chip computers, microcontrollers are nowhere near as powerful as microcom-puters. Microcontrollers typically have less memory, lower operating speeds, andmost often run only a single program. Their advantages are that they are small,inexpensive, complete computers with integrated I/O circuitry.

Size

Memory

Processor

Clock Speed

Price

Power Requirements

ProgrammingLanguages

Complexity of design

Application

Laptop to Desktop

External - 10’s of Mb

32 - 64 bit

133 MHz - 575 MHz

$100.00 - $1000.00

0.5 W - 10 W

Numerous (Basic, C,C++, Java, etc.)

Very complex

General purpose

Pea size to VHS tape

Internal - 100’s of bytes

4 - 32 bit

DC - 50 MHz

$2.00 - $20.00

10 µW - 1 W

Limited to Assembly, C,Basic, Forth

Simple

Dedicated to specificpurpose

Personal Computer Microcontroller

Page 17: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

17Chapter 1

Microcontrollers©1998 Sirius microSystems

Questions

1. What types of household appliances can benefit from microcontrollers?

2. What parts of personal computers would contain microcontrollers?

3. Why does a microcontroller require far less RAM than a personal computer?

4. Why are the cheapest microcontrollers OTP?

5. How do microcontroller and personal computer input/output devices differ?

6. Compare and contrast the uses of RAM and ROM in personal computers andmicrocontrollers.

Assignments

1. Create a chart similar to that on the opposite page comparing a typical compu-ter system to one of the PICmicro™ family microcontrollers. Use a databookor distributor catalog to find some of the information.

2. Describe a project that you would like to build that uses a microcontroller.State why the project is ideally suited to using a microcontroller.

3. Sketch a large block diagram of a micro-controller and include a short state-ment describing the function of each block within each.

Office productivity improved greatly after the introduction of the PICranialTM Braininterface network adapters.

Page 18: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

PB ©1998 Sirius microSystems

Notes

Page 19: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

19Chapter 2

How do Micro-controllers work

©1998 Sirius microSystems

Microcontrollers work the same way that any computer works. They read aninstruction from memory, determine its meaning, and perform the operation(s) speci-fied by the instruction. This is known as a fetch-decode-execute cycle and this cycletakes place thousands or even millions of times each second. All computer proces-sors repeat this simple cycle when executing programs.

Processing Unit

As shown in the block diagram, the ROMcontains the program instructions. The Pro-gram Counter tells the Instruction Fetch/De-code unit which memory location to address.The instruction in the memory location thatthe program counter points to is decoded andsent to the ALU (arithmetic/logic unit). TheALU executes the instruction by performingsimple arithmetic or logic operations on bi-nary numbers. The results of these operationsare stored in a working register (W) or tomemory. Results are never stored to ROM be-cause ROM is Read Only Memory. When thecycle is complete, the Fetch/Decode unit getsthe next instruction from memory.

The clock oscillator circuit advances theprogram counter. Unless the program counteris modified by the previous instruction, the nextinstruction in the program sequence is fetched,decoded and executed. After this, the next in-struction is fetched, decoded and executed, andso on. The entire operation of any computerboils down to just three words: fetch, decodeand execute! That’s it.

How do MicrocontrollersWork?2

Fetch/Decode Unit

ALU

W

Program Counter

RAMContains

Data

I/O Port

To theoutsideworld

ROMContainsProgram

Instructions

ProcessingUnit

Dual Memory StackHarvard Architecture Harvard architecture is the

term used to describemicrocontrollers whichhave separate memorystacks (memory addressranges) for permanentmemory, temporarymemory and I/O devices.

Page 20: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

20 ©1998 Sirius microSystems

Memory

Memory is organized as a sequentiallynumbered stack of storage locations. Eachmemory location has its own unique address.Some microcontrollers have places forRAM, ROM and I/O circuitry assigned ina single memory stack, while others haveseparate RAM, ROM and I/O stacks. Whenthere is only one memory stack, the micro-controller is said to have a memory mappedarchitecture (see right diagram). When thereare separate memory stacks for instructions(ROM) and data (RAM) the microcontrol-ler is said to have a Harvard architecture.All PICmicro™ microcontrollers useHarvard architecture.

Note that when they are separated, themicrocontroller must distinguish betweenRAM and ROM memory locations. This isdone by using specific memory or I/O in-structions to address each type of memory.

The Outside World Connection

I/O ports connect a microcontroller to the outside world. All ports have a memorylocation or address which can be accessed by the processing unit. I/O ports are uniquein that external signals or the processor can modify their contents. In contrast, onlythe processor can modify the memory contents. When the processor modifies the I/Oport contents, they appear as a voltage on the external pins of the microcontroller.Most microcontroller I/O ports can be programmed to be either inputs or outputs.

How do Programs get into the Microcontroller?

Microcontroller programs are most often written as assembly language mne-monics called source code (see the Data Sheets for a list of all mnemonics). Mnemon-ics are short (3-5 letter) command representations that help programmers to remem-ber the function of instructions. An assembler program converts mnemonics intomachine code. Machine codes are binary numbers that the microcontroller interpretsas instructions. This binary number representation is called object code and is pro-grammed into the microcontroller ROM using a programmer. Programmers are hard-ware devices that connect to your PC and have a socket that accommodates themicrocontroller.

Memory

Fetch/Decode Unit

ALU

W

Program Counter

To theoutsideworld

ROMContains

Instructions

ProcessingUnit

Single Memory Stack

I/O Port

RAMContains

Data

Microprocessors with asingle, continuous memorystack (or memory addressrange) are said to have amemory mapped architec-ture.

Page 21: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

21Chapter 2

How do Micro-controllers work

©1998 Sirius microSystems

Some programmers use PC-based simulators to verify the operation of their pro-grams. Simulators allow a programmer to examine internal registers and programflow, helping them to find bugs. Since program execution is simulated and the micro-controller does not run in the target system, real-world timing problems may not beuncovered by a simulator.

Another popular PC-based debugging tool is an emulator. An emulator connectsto your microcontroller target circuit in place of your microcontroller. The emulatorhas functions similar to a simulator with the added bonus of actually running theprogram in your target system. As a general rule, emulators are more expensive thansimulators.

Chapter Summary

All microcontrollers execute programs by performing math or logic operationsin a fetch-decode-execute cycle. Instructions are fetched from ROM, and can modifyRAM or I/O ports. Likewise, the contents of RAM and I/O can affect program in-structions. Programs are written in assembly mnemonics, converted to object codeby the assembler program, and programmed into the processor with a programmer.Simulators are often used to examine the program flow during execution to check forerrors.

;VISINE.SRC V1.0 Simple addition and vision testprogram for Chapter 2.

;Demonstrates use of registers, small characters and

Device PIC16C71,HS_OSC,WDT_OFF,PROTECT_OFF, PWR ID �X+Y=�

ORG 00h ;Reset Vector GOTO 05h ;Jump over interrupt ve ORG 05h ;Actual program starts

;Hardware Equates

X EQU 0Ch ;X is a label given toY EQU 0Dh ;Y is the label for theResult EQU 0Eh ;Register 0E is labelle

;Software Equates

:020000000528D1:10000A00502058208C010C0814200038031910289D:10001A006C208C0A0828183068204520102882078E:10002A0053346934723469347534733420344D343A:10003A006934633472346F345334793473347434B6:10004A0065346D347334203426342034E434453432:10005A006E34673469346E346534653472346934A5:10006A006E34673420344C3461346234733400346F:10007A008E011A308F008E0B40288F0B4028080003:10008A008E018F01043090008E0B49288F0B49286E:10009A00900B492808008316F83085050001860070:1000AA00831205110800383068203D203830682056:1000BA003D20383068203D200C306820013068200F:1000CA000630682008000510860071208128051076:1000DA00860071200514812885148316FF30860056:1000EA00831205150000861B782805118316000166:1000FA008600831285100800051500000511080006:084000004C0043004400540091:02400E001A0096

010100101000101100010001000

Source code is converted by anassembler program into...

Object code which is downloadedto a programmer which programsthe microcontroller using...

Machine code, the form ofinstructions the microcontrollerunderstands.

The computer downloadsmachine code to theprogrammer which ‘burns’the code into the micro-controller.

MicrocontrollerProgammer

Microcontroller tobe programmed

Programming Socket

Page 22: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

22 ©1998 Sirius microSystems

Questions

1. Why is the result of an operation never stored to ROM?

2. What relationship does clock speed have to program operation?

3. Explain the difference between assembler and downloader software.

4. How do ports differ from memory locations?

5. What are the advantages of using an emulator vs. a simulator?

While ‘burning’ microcontrollers for the PICranialTM brain interface, Dr. vonNetzkopf utilized the services of many beta testers.

Questions

Page 23: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

23Chapter 3 - The

Microchip PIC familyof Microcontrollers

©1998 Sirius microSystems

The Microchip PIC familyof Microcontrollers3

The Microchip PICmicro™ family of microcontrollers is well established andinexpensive. PICmicro™ microcontrollers have been used for many applications in-cluding computer mice, remote controls, and caller-ID decoders. The reasons that thePICmicro™ family is so popular are due to low cost, high-speed devices and inex-pensive development tools. Its speed stems from its architecture—a modified Harvardarchitecture—and its RISC-like instruction set. RISC computers are characterizedby having a small instruction set in which each instruction executes very quickly. Inthis case, every instruction is a single word long and executes in a single clock cycle.

The PICmicro™ Product Range

Microchip, the manufacturer of PIC microcontrollers, have three ranges ofPICmicro™ microcontrollers (mcu’s) to choose from. The PIC16C5X series of partsmake up the low-end, the more powerful PIC16CXX chips form the mid-range lineand the PIC17CXX family completes the high-end. The chart below outlines thevarious PICmicro™ families.

Harvard architecture allowssimultaneous access to bothRAM and ROM. RISCstands for Reduced Instruc-tion Set Computer.

Actually, instructions thatmodify the program counterrequire two instructioncycles to complete.

UCMCIPseilimaF

margorPyromeM

MOR)sdroW(

ataDyromeM

MAR)setyB(

O/IsniP

kcolCdeepS)zHM(

slarehpireP ecirPegnaR)1.ytq(

XX5C21CIPX5C61CIP

k2-215eroctib-21

37-42 02-6 02-4 TDW,remittib-81 -00.2$00.51$

X76C21CIPX55C61CIP

X6C61CIPX7C61CIPX9C61CIP00041CIP

k8-215eroctib-41

863-63 25-6 02-4 ,sremittib-83ot1,CAD,D/Atib-8,TDW,TRASU,srotarapmoc

I/IPS 2 ,MORPEE,C/erapmoc/erutpacsrevirdDCL,MWP

-00.4$00.52$

X4C71CIPX57C71CIP

k61-k2eroctib-61

209-232 33 33 ,sremittib-61/84,D/Atib-21,TDW

I/IPS 2 ,TRASU,C/erapmoc/erutpacelbadnapxe,MWP

-00.31$00.53$

The main factor thatdistinguishes the threePICmicro™ families is theinstruction size of the core:12-bit in the low-end, 14-bit in the mid-range, and16-bit in the high-end.

Page 24: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

24 ©1998 Sirius microSystems

The 18-pin PIC16CXX Product Line

The PICmicro Development System (PIC-MDS) has been developed for the mid-range, 18-pin PICmicro™ devices. The PIC-MDS Professional comes with both thePIC16C711 and PIC16F84. The PIC-MDS Hobbyist system includes only thePIC16F84. The PIC16F84 can be programmed and erased while in the PIC-MDS.The PIC16C711 requires an ultraviolet light source for erasure. We’ll examine thefeatures of these two chips in more detail in a moment. Bear in mind that any 18-pinPIC highlighted in the chart above will work in the PIC-MDS.

The charts shown list only a small sampling of the large variety of PICmicro™microcontrollers available. Visit the Microchip Technology, Inc. website (http://www.microchip.com), or contact your local Microchip Distributor for the latest lit-erature.

The 18-pin PIC16CXXProduct Line

orcimCIPUCM

margorPMOR

)sdroW(

ataDMAR

)setyB(

kcolCdeepS)zHM(

D/A.nahc

golanA.pmoC

nworBtuO

teseR

MORPEE)setyB(

sremiT

455C51CIP 215 08 02 - - - - TDW+1

655C61CIP 4201 08 02 - - - - TDW+1

855C61CIP 8402 821 02 - - - - TDW+1

16C61CIP 4201 63 02 - - - - TDW+1

026C61CIP 215 08 02 - 2 seY - TDW+1

126C61CIP 4201 08 02 - 2 seY - TDW+1

226C61CIP 8402 821 02 - 2 seY - TDW+1

17C61CIP 4201 63 02 4 - - - TDW+1

017C61CIP 215 63 02 4 - seY - TDW+1

117C61CIP 4201 86 02 4 - seY - TDW+1

517C61CIP 8402 821 02 4 - seY - TDW+1

38RC61CIP 215 63 01 - - - 46 TDW+1

48C61CIP 4201 63 01 - - - 46 TDW+1

38F61CIP 215 63 01 - - - 46 TDW+1

48F61CIP 4201 86 01 - - - 46 TDW+1

This chart compares the features of all current 18-pin mid-range PICmicro™ mcu’s.Any of these PICmicro™ mcu’s can be used in the PIC-MDS.

Page 25: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

25Chapter 3 - The

Microchip PIC familyof Microcontrollers

©1998 Sirius microSystems

The PIC16F84

Program EEPROM

The PIC16F84 has 1 k (1024) locations of EEPROM or Flash ROM, and can beprogrammed and erased while in the PIC-MDS. Remember that ROM stores instruc-tions for the microcontroller. Since each instruction takes one memory location, yourprogram can have no more than 1024 instructions. Each instruction is 14 bits long,therefore each ROM location is 14 bits wide. ROM locations are addressed in hexa-decimal and range from 0000h to 03FFh (0 to 1023 in decimal).

Two ROM locations are special. Location 0000h is called the Reset Vector. Thisis where the PIC16F84 begins executing instructions immediately after a reset. Lo-cation 0004h is called the Interrupt Vector. The PIC16F84 begins executing instruc-tions from here immediately after an interrupt.

Data EEPROM

The PIC16F84 also has 64 bytes of 8-bit data storage EEPROM. This memoryis suited to storing values that need to be restored on power-up. Both the programand data EEPROM areas are electrically erasable. While the data EEPROM can bechanged by the program executing in the microcontroller, the program EEPROMcan only be written to by the programmer or downloader.

Interrupts are a techniqueby which the currentprogram is temporarilyplaced on hold while theprocessor performs anotherset of instructions inresponse to an event. SeeChapter 11 - Interrupts formore information.

represents a connection to the outside world.

The PIC uses Harvardarchitecture which meansseparate RAM and ROMstacks. In the PIC they aredifferent widths.

Data EEPROM is ideal forstoring user definablepasswords or configurationdata.

Page 26: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

26 ©1998 Sirius microSystems

RAM

The PIC16F84 has 68 general purpose RAM locations. Each is 8-bits wide.General purpose RAM locations begin at address 0Ch and extend to 4Fh. Microchipcalls RAM locations File Registers.

There are 16 other RAM locations known as hardware registers. Some are usedinternally, while others extend to the outside world as I/O ports. Notice that fileregister locations 00h through 0Bh have memory addresses on both page 0 and page1. The RP0 bit in the Status register (03h) determines the active page—0 equals page0, 1 equals page 1. Some page 0 registers are repeated in page 1 for programmingconvenience. Though not implemented in the PIC16F84, the microcontroller is capa-ble of accessing two more memory pages via the RP1 bit.

Input/Output Ports

The PIC16F84 has two input/output (I/O) ports. Each port pin can be programmedto be either an input or an output. Some port pins have more than one function. Allport pins can source up to 20 mA of current and are able to sink up to 25 mA. ThePIC can easily drive LEDs, speakers and small relays without adding external drivertransistors. Not all pins can handle high current simultaneously (see the PIC datasheets for details on the I/O ports).

Port A is a five bit wide digital port labelled RA.0 to RA.4. Pin RA.4 can be usedas an input to the real time clock counter/timer (TMR0 or RTCC) or can be used asa digital I/O pin. TMR0 can also generate an interrupt.

Port B is an 8-bit digital I/O port. All port B pins have an internal pull-up resis-tor that can be enabled when port B pins are set to be inputs. The internal pull-upresistors eliminate the need for external resistors, saving parts and circuit board space.Pin RB.0 (INT) can double as an interrupt source. Pins RB.4 through RB.7 can beset to generate an interrupt on a change in input state. This feature is useful forwaking up the PIC from sleep when a key is pressed.

I/O ports A and B are file registers 05h and 06h. Two other registers, TRISA(05h on page 1) and TRISB (06h on page 1), contain the direction bits which controlthe flow of data through the ports. A ‘1’ bit in the TRISX register denotes that pin asan input, a ‘0’ bit denotes an output.

TMR0

RAM register location 01h on page 0 contains TMR0, the counter/timer. It canbe fed from either pin 3 (RA.4), or from the internal clock. An 8 bit prescaler—which divides the incoming signal by a pre-programmed amount—can be applied tothe TMR0 input. Incoming clock signals can be divided by: 2, 4, 8, 16, 32, 64, 128or 256 depending on the prescale value. The prescaler value is set in the OPTIONregister (01h on page 1). The prescaler is shared with the watchdog timer (WDT),and if used for WDT is unavailable for use by TMR0.

RAM and I/O

The assembler also recog-nizes the labels PORTA.0 -PORTA.4 and PORTB.0 -PORTB.7 in addition toRA.X and RB.X. See theEPIC .INC files for a list ofall pre-defined labels foreach particular processor.

TMR0 was once known asRTCC—the Real TimeClock Counter.

The PIC instruction set hasa SLEEP command whichstops processing until aninterrupt occurs. Whileasleep, a PIC uses verylittle current.

Page 27: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

27Chapter 3 - The

Microchip PIC familyof Microcontrollers

©1998 Sirius microSystems

With TMR0 set to count external signals, it can count external events such asbottles moving down an assembly line, the rotations of a tire, or the number of timesyour desk drawer has been opened. With TMR0 counting internal clocks, you coulduse TMR0 to measure the width of a pulse if you turn on TMR0 when a signal on apin goes high and turn it off when the signal transitions back to low. This techniquecan be applied to measure pulse widths as small as 100 µs and frequencies up to 50MHz.

Watchdog Timer (WDT)

The Watchdog Timer (WDT) is an independent free running oscillator completelyself-contained on the chip. Being independent of the main clock means that if themain oscillator is halted by the SLEEP command, the PIC can be ‘awakened’ by thecontinually running watchdog timer.

The Watchdog timer has a nominal period of 18 ms (which is equivalent to afrequency of 55 Hz) but can vary from 9 ms to 40 ms depending on temperature andapplied voltage. A prescaler, shared with TMR0, can be applied to the Watchdogtimer to change its period.

The Watchdog can used to force a reset after either a software fault—the proces-sor may be stuck in an endless loop, or static discharge may have corrupted registermemory—or to wake the processor from a SLEEP command.

If not needed, WDT may be turned off via the configuration fuses. Configurationfuses are set by the programmer or downloader during programming.

Power-Up Reset Timer (PWRT)

The power-up reset timer is used to provide a nominal 72 ms delay after power isfirst applied. This allows the power supply 72 ms to stabilize before the reset signalis issued to the micro-controller. It is controlled via the configuration fuses.

Oscillator

The clock oscillator circuit in the PIC16F84 is very flexible. Four oscillatoroptions are available: quartz crystal, ceramic resonator, resistor-capacitor combina-tion (RC), or external clock input. The oscillator socket on the PIC-MDS allows youto plug in quartz crystals or ceramic resonators.

Quartz crystal and external clock inputs allow the highest speed and the mostaccurate timing. Ceramic resonators are cheaper but slightly less accurate than quartzcrystals. RC combinations are cheapest but suffer from timing inaccuracies depend-ent on temperature and the power supply voltage. The chosen oscillator option is setvia configuration fuses blown during programming.

While WDT is self con-tained and requires noexternal parts, the mainclock oscillator requiresexternal components (seeOscillator, below).

Capacitors have widetolerances and both resistorand capacitor valueschange with temperature.

Page 28: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

28 ©1998 Sirius microSystems

RAM Register Files

As mentioned earlier, RAM is divided into the hardware register file and general-purpose storage locations. We have already seen how some of the register files havebeen used (PORTA, PORTB, TRISA, TRISB, TMR0, and OPTION ). We’ll look atsome of the other important registers.

STATUS

The STATUS register (03h) holds arithmetic flags, page select bits and the mi-crocontroller’s reset status. More detail on STATUS can be found in the PIC16F84Data sheets.

PCL & PCLATH

PCL (02h) stands for Program Counter Low. It holds the lower 8 bits of theprogram counter. Remember that the PIC16F84 can have as many as 1024 instruc-tions in ROM (program) memory. Addressing 1024 locations requires 10 bits. Theupper two bits are stored in PCLATH (0Ah bits 0 and 1).

IND0 & FSR

IND0 (00h) is the first (and only) INDirect addressing register. It is used inconjunction with FSR (04h), the File Select Register, to indirectly access data.

A reference to IND0 retrieves the contents of the address location stored in FSR.This allows a programmer to increment FSR and access subsequent locations byusing the IND0 address as the target of the instruction. For example, if FSR contains20h, addressing IND0 will access RAM location 20h. Indirect addressing is particu-larly useful for look-up tables.

INTCON

The INTerrupt CONtrol register (0Bh) enables or disables interrupts and con-tains most of the interrupt flag bits.

OPTION

The OPTION register (01h on page 1) controls prescaler divisors, TMR0 triggerlevels and signal source, as well as the Port B pull-up resistors.

EEDATA & EEADR

The PIC16F84 has 64 bytes of EEPROM data memory which can be changedby the program, unlike the program EEPROM which can only be changed by theprogrammer. EEDATA (08h) holds the data to be written to or read from the locationspecified by EEADR (09h).

EECON1 & EECON2

EECON1 (08h on page 1) is the EEPROM data memory control register. EECON2(09h on page 1) is used during EEPROM data writes.

RAM Register Files

Page 29: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

29Chapter 3 - The

Microchip PIC familyof Microcontrollers

©1998 Sirius microSystems

The PIC16C711

Many of the parts of the PIC16C711 are identical to the PIC16F84. The differ-ences reflect the addition of a four-channel A/D converter and the use of EPROMprogram memory rather than EEPROM. The PIC16C711 has no EEPROM datamemory.

Program EPROM

The PIC16C711 EPROM memory is identical in size to that of the PIC16F84(1k words). Unlike the PIC16F84, the PIC16C711’s EPROM memory is erased byexposure to ultraviolet light. Be sure to cover the window after programming so thatambient light won’t affect the operation of the PIC.

The Reset and Interrupt Vectors are in the same locations as the PIC16F84.

Analog-to-Digital Converter

The PIC 16C711 is one of the few members of the PICmicro™ family with abuilt-in 8-bit analog-to-digital converter (A/D). In many cases it is cheaper to use aPIC16C711 than to use a PIC with an external A/D. The A/D converter can translatean analog voltage into a binary number.

Port A of the PIC16C711 can be configured to read two, three or four analoginputs. Conversions require a minimum of 20 µs. The A/D clock can be fed by its

Erasing a PIC16C711 takes5-10 minutes of exposureunder ultraviolet light.

Page 30: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

30 ©1998 Sirius microSystems

own RC oscillator or from the master clock through an internal clock divider undercontrol of the ADCON0 (08h) file register. Using the RC oscillator allows conver-sions to take place while the micro-controller is asleep, which provides the best con-version accuracy.

The A/D is controlledthrough two RAM regis-ters, ADCON0 (08h) andADCON1 (08h on page 1),and the result is placed inthe A/D result file registerADRES (09h).

The A/D is particu-larly useful when measur-ing the voltage from astrain gauge, liquid levelsensor, temperature sensor,light sensor, or perhapseven for measuring brain-wave activity.

Chapter Summary

The PIC16F84 and PIC16C711 are identical except:

• the memory on the PIC16F84 is electrically erased, the PIC16C711 requiresexposure to ultraviolet light

• the PIC16F84 has an additional 64 bytes of EEPROM data space

• the PIC16C711 has a 4-channel A/D converter

• the maximum clock speed of the PIC16F84 is 10 MHz, the PIC16C711 has a20 MHz maximum clock speed

It’s easiest to develop programs on the PIC16F84 becasue the EEPROM memoryallows quick erasing and reprogramming. The PIC16F84 can also be programmedin-circuit, without removing it from the PIC-MDS and plugging it into the program-mer. All necessary programming signals are supplied to the PIC through the In-Circuit programming cable.

If your program requires high speed operation, or A/D conversion, then thePIC16C711 must be used.

A/D Converter

While trying out the new PIC-Your-BrainTM brain waveanalyser, Bob realizes that he should never have removedthe ground prong from his oscilloscope’s power cord.

Page 31: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

31Chapter 3 - The

Microchip PIC familyof Microcontrollers

©1998 Sirius microSystems

Questions

1. What is the maximum size of program you could place inside a PIC16F84 orPIC16C711?

2. What is the location of the instruction that will be executed immediately aftera reset?

3. What is the maximum number of variables that could be stored in RAM?

4. What is the purpose of a watchdog timer? Why is the watchdog given its ownoscillator?

5. What is the advantage of EEPROM program memory?

6. Explain how an application might use EEPROM data memory.

7. Why is program memory wider than data memory?

8. Air bag sensors respond to rapid decelerations that occur within 30 ms. Can aPIC16C711 measure at least 20 analog samples within a 30 ms window todetermine whether or not to inflate the bag?

Assignment

1. You’ve developed a touch-tone dialer program using the PIC-MDS and aPIC16F84. The program is 487 bytes long. What other PICs could be usedinstead of the PIC16F84? Check supplier catalogs to find the least expensivePIC.

2. You have 6 relays to connect to PIC16F84. Each relay coil requires 20 mA toactivate. Examine the data sheets and determine how many relay coils can beactive simultaneously on Port B. How many of these relays could be connectedto Port A?

Page 32: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

32 ©1998 Sirius microSystems

Notes

Page 33: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

33Chapter 4 - Features

of the PIC-MDSDevelopment System

©1998 Sirius microSystems

4 Features of the PIC-MDSDevelopment System

The PIC-MDS contains everything you need to develop your own mid-rangePICmicro™ microcontroller applications. The advantage of the PIC-MDS is thatwas designed with typical microcontroller input/output (I/O) circuitry already pre-wired to the microcontroller, so that users can spend their time concentrating on codedevelopment and not on hardware debugging. This chapter explains the operation ofeach of the devices on the PIC-MDS board. Refer to the schematic on the next pageto examine the circuitry for each item.

Screw terminal stripallows access to allport signals andpower supplies.

2.1mm Power Jack12 VAC or 18 VDC(500mA) input

2-Line 16-Character LCD Displaywith 80 character memory andprogrammable characters

Buffered LEDdisplay showspower and portstatus

LCD contrast adjustpotentiometer

RS-232 Serialdriver/receiver

RS-232 input/output header

RS-232 transmit/receive select jumper

Fixed 5V regulator

5VDC internal/external selectjumper

Variable DCinternal/externalselect jumper

Variable DC adjustpotentiometer

16 key matrixkeypad withcustomizablekey legends

Variable DCregulator

Crystal or ceramicresonator socket

PICBUS expansionheader

Processor ZIF socket

EPIC in-circuitprogrammingheader

Two variableanalog inputpotentiometers

Hardwarereset button

Serial EEPROM

Page 34: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

34 ©1998 Sirius microSystems

Page 35: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

35Chapter 4 - Features

of the PIC-MDSDevelopment System

©1998 Sirius microSystems

Power Supply Circuit

The power supply of the PIC-MDS is capable of supplying both the microcon-troller and external circuitry with a range of voltages. Two independent regulatorsprovide a fixed +5VDC output as well as a variable DC output. The variable DCoutput can be connected to the 5V microcontroller power supply to run the microcon-troller at a lower voltage than 5V using a user-supplied jumper. Each power supplyvoltage is present at the PICBUS expansion connector (H1) for external circuitry.

Electrical current is supplied to the PIC-MDS through the 2.1mm co-axial powerjack (J1) or from pins 1 and 3 of the screw terminal strip (CON1-1 & CON1-3). Pin3 of the screw terminal strip (CON1-3) is the ground connection. Pin 2 of the screwterminal strip (CON1-2) in conjunction with the ground (CON1-3) allows an exter-nal power supply to provide the regulated +5VDC for the microcontroller.

The PIC-MDS power supply accepts either AC or DC input. The on-board powersupply will produce the necessary DC voltages for the PIC-MDS. The PIC-MDS isdesigned to work with either of the following AC adapters:

Input Voltage Output Voltage Output Current

120 VAC 9-12 VAC 300 mA

120 VAC 12-18 VDC 300 mA

Note that using AC adapters with higher output voltages will increase the powerdissipation of the regulators and will cause them to get quite hot during operation.

J1

J1 is a 2.1mm co-axial power jack This jack supplies current from an AC or DCwall adapter to the bridge rectifier (D1) and the regulator circuitry (C1-6, U1, U2,etc.). J1 also contains a normally closed switch connected to the 16-pin screw termi-nal strip (CON1-1). When no wall adapter is plugged into J1, current from pin 1 ofthe screw terminal strip (CON1-1) flows through J1 to the rectifier.

VR1

Potentiometer VR1 is used to adjust the variable DC power supply. The range ofthe variable DC power supply is from 1.3V to approximately 3V less than the volt-age into J1.

JU1

Default position: REG

3-pin shorting jumper, JU1, selects the voltage source for any circuits connectedto the variable DC power supply. In the REG position, the variable DC voltage isderived from the variable DC regulator (U1). In the CON1 position, the variable DCvoltage is taken from pin 2 of the screw terminal strip (CON1-2).

If you add high currentexternal circuitry to thePICBUS or CON1, powerthe PIC-MDS from anexternal power supplyattached to screw termi-nals 2 and 3 on CON1. ThePIC-MDS AC power supplycan supply only 300 mA tothe PIC-MDS and externalcircuitry.

The screw terminal strippins are numbered from thetop of the PIC-MDS.Therefore, pin 1 or CON1-1is closest to J1, and pin 16or CON1-16 is closest toC5.

Page 36: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

36 ©1998 Sirius microSystems

JU2

Default position: REG

The 3-pin shorting jumper, JU2, selects the fixed +5VDC voltage source. In theREG position, the fixed +5VDC voltage is derived from the 5V regulator (U2). In theCON1 position, the fixed +5VDC voltage is taken from pin 2 of the screw terminalstrip (CON1-2).

When the fixed +5VDC voltage source is present, the LED at the top of the LEDbar graph (LED1-PWR) lights.

External I/O Connectors

The PIC-MDS has two external I/O expansion connectors. The 16-pin screwterminal strip (CON1) allows for quick and easy connections from external circuitcomponents to the PIC I/O ports. The PICBUS expansion header (H1) allows exter-nal circuits to be connected more permanently to the PIC microcontroller. The PICBUSincludes both power supplies as well as the PIC reset line (MCLR) and is geared toadding microcontroller peripherals to the PIC-MDS.

CON1

CON1 is the 16-pin screw terminal strip at the extreme left of the PIC-MDS.Three power supply connections and 13 microcontroller I/O pins are brought out tothe screw terminals for ease of connection to external devices. The pinout of CON1is shown below:

Note that the input toCON1-2 is affected by boththe JU1 and JU2 settings.CON1-2 can provideeither the external +5VDCsupply or the externalvariable DC supply—butnot both at once!

Warning: Do not exceed+6VDC on CON1-2 whenJU2 is set to CON1 inputor you will destroy yourPIC microcontroller.

External I/OConnectors

+9V to +18VDC input — CON1-1+5VDC or variable DC — CON1-2

Ground — CON1-3RA0/AIN0 — CON1-4RA1/AIN1 — CON1-5RA2/AIN2 — CON1-6

RA3/AIN3/VREF — CON1-7RA4/RTCC — CON1-8

RB0/INT — CON1-9RB1 — CON1-10RB2 — CON1-11RB3 — CON1-12RB4 — CON1-13RB5 — CON1-14RB6 — CON1-15RB7 — CON1-16

Page 37: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

37Chapter 4 - Features

of the PIC-MDSDevelopment System

©1998 Sirius microSystems

Note that the PIC-MDSdoes not come with aconnector for thePICBUS header. Anumber of differentstyles of header plugsand sockets will fit intothe PICBUS connector.

PICBUS

The PICBUS connector on the PIC-MDS is compatible with the PICBUS con-nectors on the PIC-PROTO boards from microEngineering Labs. It is a 26-pin headerconnector socket at the right side of the PIC-MDS. The pinout of H1 is shown below:

Microcontroller Related Circuits

The PIC microcontroller is essentially connected to all of the circuitry on thePIC-MDS board. The following parts of the PIC-MDS relate most directly to thePIC microcontroller.

Microcontroller Socket

The PIC microcontroller socket (U3) is either an18-pin zero-insertion-force (ZIF) socket (in the case ofthe PIC-MDS Professional), or an 18-pin DIP socket(PIC-MDS Hobbyist). Pin 1 is the pin closest to the U3label on the PIC-MDS board.

H2

The EPIC In-Circuit programming header (H2) al-lows the EPIC programmer from microEngineering Labsto plug directly into the PIC-MDS to speed the pro-gram/test/erase process and to save wear and tear onthe microcontroller and socket (U3). By connecting the

RA4/RTCC — H1-1RA0/AIN0 — H1-3RA1/AIN1 — H1-5RA2/AIN2 — H1-7

RA3/AIN3/VREF — H1-9RB0/INT — H1-11

RB1 — H1-13RB2 — H1-15RB3 — H1-17RB4 — H1-19RB5 — H1-21RB6 — H1-23RB7 — H1-25

H1-2 — MCLR/VPPH1-4 — +5VDC/VDDH1-6 — Variable DCH1-8 — GroundH1-10 — GroundH1-12 — RC7H1-14 — RC6H1-16 — RC5H1-18 — RC4H1-20 — RC3H1-22 — RC2H1-24 — RC1H1-26 — RC0

Connected to oppositeRBx pin on PIC-MDS

Attention Hobbyist users:you will find that a ZIFsocket for U3 reduces thelikelihood of broken ICleads when removing andinserting PICs.

Page 38: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

38 ©1998 Sirius microSystems

EPIC programmer to thePIC-MDS, a PIC16F84can be programmed anderased without removing itfrom the microcontrollersocket on the PIC-MDSboard. Simply connect H2to the programming headeron the EPIC programmer(J3) with the supplied 10-pin ribbon cable.

Pin 1 of H2 is at thelower left of the header andis denoted by a triangulararrow on the outside of theheader shroud. Pin 1 of theprogramming header (J3)on the EPIC programmeris also at the lower left (far-thest away from the 25-pinparallel connector). Besure to connect the 10-pinprogramming ribbon cablein the proper orientation.

Reset Button

The Reset button (S1) pulls the PIC MCLR line low when pressed, causing ahardware reset. During a hardware reset, the PIC microcontroller stops executing thecurrent program and changes all I/O ports to inputs. When the Reset button is re-leased, the microcontroller begins executing its program from the beginning of memory,effectively restarting the program.

Y1

Y1 is the crystal oscillator/ceramic resonator socket. Crystal oscillators and two-pin ceramic resonators plug into the two outer socket pins (Y1-1 and Y1-3 on theschematic). Y1-2 is a ground pin and is used for 3-pin ceramic resonators.

The PIC-MDS is supplied with a 10 MHz crystal. The values of the externaloscillator components C7, C8 and R5 have been chosen to operate the PIC-MDSproperly at frequencies from 4 to 20 MHz. To operate the PIC-MDS at a clockfrequency other than 10 MHz, or to use a ceramic resonator instead of a crystaloscillator, simply install the crystal or resonator in Y1.

JU3

Default position: RUN

Three-pin shorting jumper JU3 changes the sourceof the +5VDC power supply for the microcontroller only.In the RUN setting, the PIC-MDS fixed +5VDC supply

It is sometimes necessaryto press and hold the Resetbutton while starting theEPIC software. This isbecause the EPIC pro-grammer programs the PICusing RB.6 and RB.7. TheEPIC software expectsthese two pins to be inputs.If your program uses RB6and RB7 as outputs, theEPIC software can’tinterrogate the PIC. Byholding the Reset button,these two pins float,essentially becominginputs.

MicrocontrollerRelated Circuits

The PIC16C711 can alsobe programmed through theIn-Circuit programmingheader, but requires UVlight for erasure.

The PIC-MDS connected to the EPIC programmerthrough the 10-pin programming cable. Be sure toconnect the cable in the proper orientation.

If you purchased the PIC-MDS with the EPIC program-mer, refer to the Quick Start sheet for information on howto get up and running fast!

Page 39: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

39Chapter 4 - Features

of the PIC-MDSDevelopment System

©1998 Sirius microSystems

powers the PIC microcontroller (as well as all other circuitry on the PIC-MDS). Inthe PROG setting, the microcontroller is powered by the EPIC programmer (all otherPIC-MDS circuitry is still powered by the fixed +5VDC supply).

This jumper allows you to take advantage of the ZIF socket on the PIC-MDS asan add-on to the EPIC programmer. When set to PROG, the EPIC programmerpowers only the microcontroller, not the rest of the PIC-MDS. Since the EPIC pro-grammer was not made to power external circuitry, setting JU3 to PROG prolongsthe battery life of the EPIC.

JU6

Default positions: RA0 - OpenRA1 - OpenRA2 - ShortedRA3 - OpenRA4 - Open

The 10-pin jumper block JU6 has two purposes. The RA0 and RA1 positionsconnect the analog input potentiometers (VR3 and VR4) to the PIC RA.0 and RA.1inputs, respectively. When not using the analog input capability of the PIC16C711,leave RA0 and RA1 open to eliminate interference from the analog voltage levels setby VR3 and VR4.

The RA2, RA3 and RA4 positions of JU6 select which of the microcontrollerPort A lines is connected to the LED labelled JU6 on the LED bar (LED1). Bydefault, the JU6 LED monitors the LCD enable line on RA2. Moving the shortingjumper from RA2 to RA3 or RA4 allows you to monitor those pins using the LED.

VR3 & VR4

VR3 and VR4 are analog input potentiometers meantto simulate analog sensors when using the PIC16C711’sbuilt-in A/D converter. Disable VR3 and VR4 when notusing the analog input capability of the PIC16C711, orwhen using the PIC16F84. To disable VR3 and VR4simply remove the jumpers from JU6-RA0 and JU6-RA1.

Matrix Keypad

KB1 is a 4X4 matrix keypad connected to Port B of the PIC microcontroller. Allswitches are normally open and will not interfere with the operation of any programsthat do not use the keypad. Resistors R6-R9 provide short-circuit protection in casetwo Port B pins are set to output and become shorted by a pressed keypad switch.

The key caps can easily be removed by gently lifting the left or right side of theclear plastic cover. This makes it easy for you to add your own custom key legends.

Select only one of RA2,RA3 or RA4 at a time.Otherwise you will shorttwo or more PIC outputstogether, potentiallydamaging the PIC throughexcessive output current.

RA2 is also the LCDenable line. Removing thejumper from RA2 lets theenable line float and maycause unreliable operation.

Page 40: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

40 ©1998 Sirius microSystems

LED Output Indicator Bar Graph

LED1, a 10-seg-ment LED (Light Emit-ting Display) bar graph,is used to indicate thatthe fixed +5VDC powersupply is operating aswell as to monitor thestatus of the microcon-troller I/O lines. TheLEDs are connected asshown.

Intelligent LCD Display

The LCD display (LCD1) is a 2-line by 16-character intelligent display with an80 character memory. A built-in microcontroller gives the LCD display intelligenceby allowing it to control the cursor, address specific character positions, shift thedisplay contents left or right and program custom characters.

The LCD display uses RA0, RA1 and RA2 as its Register Select, Read/Writeand Enable control signals, along with RB0-7 for character or command data. Whendisabled, the LCD display will not interfere with other circuitry connected to Port B,RA0 or RA1.

VR2

Potentiometer VR2 is the LCD contrast control. Rotate this potentiometer untilthe LCD displays the most readable image.

RS-232 Serial Port

U6 is an RS-232 serial line driver/receiver and translates the PIC microcontrol-ler’s +5V logic to bipolar RS-232 levels. It connects to pin RA4 of the PIC to allowtransmission or reception of standard RS-232 data. Note that many new computerswill accept +5V (TTL) logic levels allowing you to use any PIC I/O pin for serialdata transmission (over limited distances). U6 guarantees the correct voltage anddrive capability as specified by the RS-232 standard.

JU5

Default position: open

Transmit/receive select jumper, JU5, is a 3-pin shorting jumper used to selectwhether RA4 is connected as a serial input or output. Removing the shorting jumperplug, or connecting it to only one pin of JU5, disables the serial port. Putting thejumper in the Rx position couples incoming RS-232 data to RA4. Putting the jumperin the Tx position allows RA4 to output RS-232 data.

Disable the LCD by makingRA2 (LCD Enable) anoutput and setting it low. Atpower-up all PIC I/O portsare set as inputs. Anundefined input on RA2can activate the LCD andadversely affect yourprogram.

Note that you cannot useU6 to transmit and receiveserial data at the same timebecause only one PIC I/Oline (RA4) is connected toit.

LED, LCD Display,Serial Port

The LEDs will display thestate of the PIC I/O portsregardless of whether theyare outputs or inputs. Byconnecting externalcircuits to the PIC inputsyou can use the LEDs aslogic probes to monitoryour inputs.

— indicates +5VDC is present— displays state of RA2, 3 or 4— displays state of RB0— displays state of RB1— displays state of RB2— displays state of RB3— displays state of RB4— displays state of RB5— displays state of RB6— displays state of RB7

Page 41: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

41Chapter 4 - Features

of the PIC-MDSDevelopment System

©1998 Sirius microSystems

Remember that thePIC16F84 also has an on-board 64 byte EEPROM.

Like the LCD, disable theEEPROM by making RA3an output and setting itlow.

The full-size parts layout drawing, above, shows the default locations of all jumpers for most of the programexamples. Each program lists the required jumper locations.

H3

H3 is the RS-232 serial cable connection header. A user-supplied 3-pin plug canconnect this header to external RS-232 serial devices. Refer to the schematic dia-gram at the beginning of this chapter for the pinout of H3.

Serial EEPROM

Applications that require long-term data or variable storage can store informa-tion in the serial EEPROM. Its 256 bytes of memory are non-volatile, and can beprogrammed by the PIC microcontroller. The serial EEPROM is controlled by thesignals on RA0, RA1 and RA3. The serial EEPROM is similar to the LCD display inthat it uses Port A wires for its control signals—the Chip Select, Clock, Data In andData Out lines.

JU4

Default position: X8

3-pin jumper JU4 sets the data memory organization of the serial EEPROM. Inthe X8 setting, the serial EEPROM accesses memory in 8-bit bytes. When the jumperis closest to the JU4 label, the serial EEPROM accesses memory in 16-bit words.

PIC-MDS Default Jumper Locations

Page 42: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

42 ©1998 Sirius microSystems

Questions

Questions

1. Which pins of the screw terminal strip would be used to connect a 15VDC labpower supply?

2. What connections and jumper settings of JU1 and JU2 should be used for thefollowing:

a) a 9V battery powering the PIC-MDS board and a 12V battery providingadjustable power to circuits on the PICBUS

b) a 12V car lighter adapter powering only the PIC-MDS board

c) a 5V regulated lab power supply powering the PIC-MDS and a variable labpower supply powering PICBUS circuits

d) two D cells supplying power to a low-power PIC microcontroller

e) a 6V battery supplying 3V to a low-power PIC microcontroller through theon-board variable DC power supply

3. Can you put shorting jumpers on both JU6-RA3 and JU6-RA4 at the sametime? Why or why not?

Hmm...Was that JU1 to JU3 for 5V operation, except with batteries and when bypassingthe regulator attached to CON1-3, or was it...?

The default jumper settingson the previous page workfor mostof the programs inthis text when using thesupplied AC adapter.

Page 43: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

43Chapter 5

Writing a SimpleProgram

©1998 Sirius microSystems Microchip Code

5 Writing a SimpleProgram

If you have not yet in-stalled the PIC-MDSsoftware do so now. See theQuick Start! sheet forinstructions.

Recall from Chapter 2 that the first step in programming a microcontroller iswriting the program source code, after which the source code is converted to objectcode by an assembler program. The PM assembler supplied with the PIC-MDS pro-gramming packages supports two dialects of PIC instructions.

One dialect is the official Microchip instruction set and syntax, the other is com-patible with the Parallax’s 8051-like instruction set. Each has its advantages anddisadvantages.

If you are familiar with the Microchip instruction set, or have programmedMotorola family microcontrollers, you may find it easier to use the Microchip com-mand syntax and examples. If you have programmed Intel family microcontrollers ormicroprocessors (or want to), you may find it easier to use the Parallax commandsyntax and examples. If you are new to the PIC microcontrollers, we suggest thatyou read both until you find one that you are more comfortable with.

The PIC-MDS system, including this manual and all example programs, pro-vides source code and descriptions in both instruction sets. Chapters using the Mi-crochip instruction set and syntax are identified by the Microchip Code footer at thebottom of the page. Likewise, chapters using the Parallax instruction set and syntaxare identified by the Parallax Code footer at the bottom of the page.

Parallax, Inc. is a supplierof PIC development tools.

The Microchip Codesections are printed onwhite paper, and theParallax Code sections areprinted on blue paper.

xatnySnoitcurtsnIpihcorciM xatnySekil-1508xallaraP

tamrofalorotoMotralimis tamrofletnIotralimis

nraelotsnoitcurtsniwef morfesoohcotsnoitcurtsnierom

smargorpelpmaxeynam daerpsediwsaton

tcelfersnoitcurtsnisnoitcarellortnocorcim

enoetucexeyamnoitcurtsnienosnoitcurtsnipihcorciMeromro

Page 44: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

44 ©1998 Sirius microSystemsMicrochip Code

Examining Source Code—Microchip Code

The example programs have been written using the DOS text editor EDIT. Youcan, of course, use any text editor, but our instructions describe EDIT. Let’s look atthe source code for a simple program that displays a binary number on the LEDs.

From the MS-DOS prompt, change to the EPIC directory using the command:

cd \picmds [enter]

Open the OUTPUT.ASM file for editing by typing:

edit output.asm [enter]

Your screen should look like this. Use the cursor keys or mouse to move thecursor through the text as we examine the program.

If you have not used EDITbefore, you may want totake a quick look at theHelp menu at the top-righthand side of the screen.

Here is the same pro-gram routine written inboth Microchip (top) andParallax-compatible(bottom) source code.Notice that the programwritten in Microchipcode requires moreinstructions to beentered in order to dothe same thing as theParallax code. However,both programs assembleto six machine instruc-tions, meaning that theParallax code hidessome of the microcon-troller operations.

Main BTFSC PORTA.4 ;Check Port A bit 4 for a lowGOTO Main ;If we�re here, bit 4 is highINCF PORTB ;If bit 4 is low, increment Port B

Wait_for_High BTFSS PORTA.4 ;Check Port A bit 4 for a highGOTO Wait_for_High ;If we�re here, bit 4 is still lowGOTO Main ;Bit 4 went high, wait for next bounce

Microchip assembly source code example.

Main JB PORTA.4,Main ;Loop while Port A bit 4 is highINC PortB ;If we�re here, bit 4 is low so

;increment Port B to count the;transition and,

Wait JNB PORTA.4,Wait ;Loop until Port A bit 4 goes highJMP Main ;Bit 4 went high, wait for next bounce

Parallax-compatible assembly source code example.

EDIT is available fromwithin an MS-DOS sessionin Windows-95. If you usean editor or word processorother than EDIT to writesource code files, makesure that you save them inDOS Text or ASCII format.

Examining SourceCode

Page 45: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

45Chapter 5

Writing a SimpleProgram

©1998 Sirius microSystems Microchip Code

Source Code Conventions

Notice the way that text is organized in columns. Any text beginning in the veryfirst column is considered a Label, and is a part of the Label Field. The next threecolumns contain the Instruction Field, Data Field and Comment Field. Commentsmay also begin in the first column if they are prefixed with a semicolon (;).

Labels are names given to subroutines or sections of source code. By givingparts of a program names, other program instructions can jump to or reference thenamed parts. Most assemblers place some sort of limit on the length of labels, as wellas the characters that can be used to define labels. PM has a limit of 32 characters.

The PM assembler supplied with the PIC-MDS packages also allows the use oflocal labels. Local labels are prefixed with a colon (:) and remain as a label specificto the previous non-local label. For example, you could have two different subrou-tines labelled :Loop, one within a subroutine labelled Countdown and another withina subroutine labelled Countup. The assembler knows that a call to :Loop from withinCountdown should reference only that :Loop, and not the :Loop in Countup.

Assemblers usually onlyrequire a single space orpunctuation symbol toseparate columns. Usingnicely spaced columnsmakes it far easier foryou to read your sourcecode. Set Tab stopswhere you would likeyour columns to begin.

Local labels are explainedin more detail in Chapter10 - Calls and Includes.

;Description

; This program demonstrates port output. It initializes all port B pins; to be outputs and then places a pattern on port B to illuminate LEDs.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This is a simple program that requires no prior setup.

Maclib �Pf8x.INC� ;Library file for PIC16C84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �OUTP�

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0

Main MOVLW 01010101b ;Move 01010101b into W andMOVWF PORTB ;output pattern to LEDs on Port

Done SLEEP ;Stop executing the program

InstructionField

LabelField

DataField

CommentField

Initialize, Main and Doneare the three labels used inOUTPUT.ASM.

Page 46: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

46 ©1998 Sirius microSystemsMicrochip Code

The second column is the Instruction Field. Instructions can be either microcon-troller instructions or instructions for the assembler, called assembler directives. Theinstruction set of the PIC microcontroller is described in the PIC16F8x data sheets.Remember that the PM assembler supports two instruction sets, Microchip and Par-allax. The term directive is used for assembler commands so that they are not con-fused with microcontroller instructions (See Appendix C for more details).

The column following the Instruction Field is the Data Field. Data fields containdata used by the instructions. In the case of the PIC microcontrollers, data can be afile register, a bit within a file register, a label, or a number—called a ‘Literal’ byMicrochip. Some instructions have no data. If an instruction needs multiple pieces ofdata, they are separated by a comma.

The base unit of number is optionally specified by the suffixes b and h—binaryand hexadecimal. A number with no suffix is considered to be a decimal number.Therefore, the data 12, 00001100b and 0Ch are all the same. Note that if the firstdigit of a hexadecimal number is not numeric, it must be prefixed with a 0, even if itmakes a three-digit number. For example, 0FDh is acceptable, but FDh generates anerror because it is interpreted as a label by the assembler.

The last field is the Comment Field. Comments always have a semicolon as theirfirst character and can be placed anywhere in the program. Comments are one of themost important code conventions you should develop. Well written comments de-scribe the operation of your code, or the operation and requirements of subroutines.Without comments, it can be very difficult to decipher the source code that you cre-ated just a few days ago.

Some Other Common Source Code Conventions

Some conventions are used to make a programmer’s life easier. You’ll adoptyour own favourite conventions as you become more proficient. In general, conven-tions are any action that make it easier to review and understand any program, espe-cially the one that you wrote a few months ago! Here are some of the conventionsused in this manual:

• file naming - *.ASM for source files, *.LST for list files, *.HEX for object files

• name, revision level and revision date as the first line of a program

• tabs - every 4 or 8 spaces

• instructions in upper case - the code is more visible

• comments explaining every line of code

• a comment paragraph explaining routines - comment fields are very small

• “_” as space character - max_int_power is easier to read than maxintpower

Remember, conventions are anything that you find makes the code easier to read.

Now may be a good time tobrush up on binary andhexadecimal. Any gooddigital textbook willexplain number systems.

Source CodeConventions

Appendix D shows theParallax instruction setmnemonics.

Page 47: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

47Chapter 5

Writing a SimpleProgram

©1998 Sirius microSystems Microchip Code

Examining the Program

The Maclib Directive

After the disclaimer and description comments, the first part of the program isthe Maclib directive. Maclib is short for Macro Library. A macro library containslabels corresponding to the hardware locations of a particular microcontroller. In thiscase, the Maclib directive includes references for the PIC16C84 and PIC16F84microcontrollers. When you write a program for a different microcontroller, you willneed to include the proper file in the Maclib directive.

The Device and ID Directives

The next line of the program is the Device Directive. The Device directive sets anumber of parameters for the microcontroller. The first item in the Device directivetells the assembler to create a program for the PIC16C84 microcontroller. You couldchange this to PIC16C711—the other type of microcontroller supplied with the PIC-MDS—or to any other mid-range PIC microcontroller you wanted to program (seeChapter 3).

The data following the microcontroller type sets the configuration fuses in themicrocontroller. In this case the directive sets high speed oscillator operation(HS_OSC), watch-dog timer off (WDT_OFF), code-protect off (PROTECT_OFF),and power-up reset timer on (PWRT_ON).

The ID directive sets the four identification bytes. These could be anything froma name or serial number to the number of Sundays until Christmas. Note that the IDbytes are not protected by code-protect.

A common use of the ID bytes is to hold the name or name and revision level ofa program. The ID bytes of a microcontroller can be read by a programmer, lettingyou know at a glance what the chip is programmed to do.

The ORG Directive

The ORG directive tells the assembler where in ROM memory to begin placinginstructions. It is the ORiGin for all subsequent code. We place the origin at location00h because the mid-range PIC-micro™ family always executes the instruction atlocation 00h after a power-up or reset. Location 00h is called the Reset Vector.

Maclib is unique to the PMassembler shipped with theEPIC programmer andallows easy upgrades tonew microcontrollers—justreference a new .INC file.P84.INC works with thePIC16C84 and PIC16F84,but the newer PF8X.INCworks with the PIC16F83as well.

Maclib �P84.INC� ;Library file for PIC16C84 and PM assembler;Comment this line out for other assemblers

Device PIC16C84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �OUTP�

See Chapter 3 for otheroptions set by the configu-ration fuses. Code-protectprevents a standarddownloader/programmerfrom reading your pro-gram. This provides adegree of protection fromcopying. There are peoplewho claim to be able toread any code-protectedmicrocontroller.

ORG 00h ;Reset Vector location

The ORG directive can alsospecify the origin of theRAM register memory.

Page 48: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

48 ©1998 Sirius microSystemsMicrochip Code

Location 04h is the Interrupt Vector. The microcontroller will execute the in-struction here if an interrupt is generated. It’s good practice to leave location 04h freeso that you can add interrupt capability to your programs at a later date. This pro-gram jumps past the Interrupt Vector and begins at location 05h.

The GOTO Initialize instruction has been stored in location 00h because it is thenext instruction following the ORG 00h directive. Therefore, the first instructionexecuted by the microcontroller at power-up or after a reset is not ORG 00h, butGOTO Initialize. Remember, ORG 00h is an assembler directive, not a microcon-troller instruction.

The assembler would normally place the next instruction after GOTO Initializein location 01h, the next available memory location. The microcontroller, however,has jumped to a location pointed to by the label Initialize. Since ORG 05h precedesthe Initialize label, the memory location 05h contains the BSF RP0 instruction, andis the location of the next instruction to be executed.

Program Code

The three instructions following the Initialize label set Port B of the microcon-troller as output.

First, BSF RP0 (Bit Set in File Register, Register Page Select Bit 0 in the StatusRegister) sets RAM register page 1 as the active page (refer to the PIC16F84 blockdiagram on page 17). Then, CLRF TRISB (Clear File Register, in what Microchipcalls the Port B Tristate Register) clears the Port B data direction register, makingPort B an output port. A zero bit in a data direction register makes that port bit anoutput. Similarly, a one bit in a data direction register makes that port bit an input(0=Output, 1=Input). Finally, BCF RP0 (Bit Clear in File Register, Register PageSelect Bit 0) sets the RAM register page 0 as the active page.

Main is a label that is commonly assigned to the first line of program code. Thelines following the Main label move a constant into Port B which light the LEDs inan alternating on-off pattern.

The P84.INC file knowsthat RP0 is the fifth bit ofthe Status register andautomatically substitutesthis location for anyreference to RP0. P84.INCalso substitutes a fileregister location for thedata TRISB.

GOTO 05

BSF RP0

CLRF TRISBBCF RP0MOVLW 0101..

MOVWF PortBSLEEP

0000

000100020003

00040005

000600070008

0009000A

000B000C

03FE03FF

Program ROM

This memory map showswhere instructions wouldload into program ROM

Initialize BSF RP0 ;Select memory register page 1

CLRF TRISB ;Make PortB output by clearing TRISBBCF RP0 ;Go back to register page 0

Main MOVLW 01010101b ;Move 01010101b into W andMOVWF PORTB ;output pattern to LEDs on Port

Once again, the P84.INCfile knows the file registerlocation of Port B andsubstitutes this into theprogram during assembly.

Examining theProgram

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0

Page 49: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

49Chapter 5

Writing a SimpleProgram

©1998 Sirius microSystems Microchip Code

MOVLW 01010101b (Move Literal into Working Register) moves the binarynumber 01010101 into the Working Register. The PM assembler also accepts hexa-decimal and decimal numbers. The equivalent commands would be MOVLW 55hor MOVLW 85. Remember that a hex number beginning with A through F musthave a preceding zero in order not to be interpreted as a label by the assembler.

MOVWF PORTB (Move Working Register to File Register, Port B) copies thenumber in the Working Register to the Port B File Register. The Port B file registeris connected to the LEDs (refer to the schematic on page 26).

Since our program is now finished, we tell the microcontroller to stop executinginstructions. Notice that the SLEEP instruction requires no data. The SLEEP com-mand maintains all active outputs but stops program execution by stopping themicrocontroller clock. Power requirements during sleep mode are minimal.

Ending the Editing Process

To exit the EDIT program, select Exit from the File menu.

If you inadvertently made any changes to the program, EDIT will ask you if thechanges should be saved. Select No to keep the original program intact.

The next step in the programming process is assembling the source code file toproduce an object code file. After the object code file is created, it can be downloadedto the microcontroller. Chapter 6 will lead you through program assembly, andChapter 7 shows you how to download your program to the microcontroller.

Chapter Summary

Source code is a text file that contains microcontroller instructions and assem-bler directives. Recall from Chapter 2 that source code is the code from which thelist file and object code are derived.

Directives are assembler instructions which set device parameters and memorylocations. Directives are not stored in memory, but are used by the assembler andprogrammer. Instructions and their data make up the program that will eventuallybe stored in memory, and define what the microcontroller will do.

Labels can be used to differentiate program parts or subroutines, and commentsshould be used to make the instructions and routines more understandable.

Done SLEEP ;Stop executing the program

01010101 W Port B

Page 50: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

50 ©1998 Sirius microSystemsMicrochip Code

Questions

1. What is the difference between a directive and an instruction?

2. What are the requirements for a label field?

3. Must comments be placed in the comment field?

4. Why can we not make the directive ORG 05h the first line of code?

5. What is the result of omitting the SLEEP instruction at the end of the pro-gram?

Assignment

1. Follow the steps below to write a simple program which illuminates the firstfour LEDs (RB0 to RB3). Save the program as TOPFOUR.ASM and set themicrocontroller ID locations to ‘TOP4’.

Step 1. Start the EDIT program.Step 2. Enter the program comment and Device directives.Step 3. Examine OUTPUT.ASM and the schematic diagram on page 26

to determine the commands needed to illuminate the top four LEDs.Step 4. Save your program using the Save As option from the File menu.

Questions

BSF RP0 CLRF TRISB BCF RP0 MOVLW 01010101b MOVWFPORTB SLEEP... the only thing I understand is SLEEP!

As you continue to programyou will become morecomfortable with theassembly instructions.Really! Flip to the DataSheets to see all of theother instructions you don’tyet know.

Page 51: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

51Chapter 6

Assembling aProgram

©1998 Sirius microSystems Microchip Code

6 Assemblinga Program

The function of an Assembler is to convert text source code into numeric ma-chine language instructions for the microcontroller. For example, the hexadecimaldigits 2805h represent the GOTO Initialize statement in the program, below. Al-though we understand the meaning of the instruction GOTO Initialize, themicrocontroller understands only the numeric instructions contained in the objectcode.

The assembler program converts your source code to object code in two passes.During the first pass the assembler checks for correct instruction syntax, duplicatelabel names, and assigns numeric values to symbols. In the example above, the labelInitialize is replaced with the numeric address 05h during assembly. During the sec-ond pass, the assembler converts all instructions to their numeric machine codes.

Assembling the Program

Follow the steps, below, to assemble the OUTPUT.ASM source code from Chapter5. From the MS-DOS prompt, change to the PICMDS directory by typing:

cd \picmds [enter]

The assembler program is called PM.EXE. The batch file ASM.BAT callsPM.EXE using default settings. Typing ASM filename will assemble the program.Assemble OUTPUT.ASM by typing:

asm output [enter]

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISB

From OUTPUT.ASM in Chapter 5.

If you have not installedthe PIC-MDS software, doso now. See the QuickStart! sheet for details.

All programs can be foundin the Pull-Out ProgramReferences section.

Page 52: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

52 ©1998 Sirius microSystemsMicrochip Code

Your screen should display the following:

The assembler has created two new files from your source code: the assemblylisting, OUTPUT.LST, and the object code, OUTPUT.HEX. Let’s examine the listfile first. Type the following to start the MS-DOS editor:

C:\PICMDS>edit output.lst [enter]

Notice that the List file contains a copy of your source code file along with threeextra columns of text. The assembler PM.EXE numbers every line of source code,and identifies each memory address and its contents. If there were any errors duringassembly, PM would report the line number at which the error occurred.

C:\PICMDS>asm output

C:\PICMDS>pm -l outputPICmicro Macro Assembler 3.01, (C) 1995, 1998 microEngineering Labs, Inc11 words used

C:\PICMDS>

When ASM.BAT calls PM,the -l option creates a Listfile. See Appendix C formore assembler options.

Line number

34 ;Requirements 35 36 ; This is a simple program that requires no prior setup. 37 38 39 Maclib �PF8x.INC� ;Library file for PIC16C84 and PM assemble 40 ;Comment this line out for other assembler 41 42 Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ON 43 =554F ID �OUTP� 44 45 ORG 00h ;Reset Vector location 46 0000- 2805 GOTO Initialize ;Start program after Interrupt vec 47 48 ORG 05h ;One location past Interrupt vecto 49 50 0005- 1683 Initialize BSF RP0 ;Select memory register page 1 51 0006- 0186 CLRF TRISB ;Make Port B output by clearing TR 52 0007- 1283 BCF RP0 ;Go back to register page 0 53 54 0008- 3055 Main MOVLW 01010101b ;Move 01010101b into W and 55 0009- 0086 MOVWF PORTB ;output pattern to LEDs on Port 56 57 000A- 0063 Done SLEEP ;Stop executing the program

Address

Address Contents

Assembling theProgram

Page 53: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

53Chapter 6

Assembling aProgram

©1998 Sirius microSystems Microchip Code

The first item in the address column (=554F) is not an address at all. It is pro-grammer information representing the microcontroller type. Addresses are not pre-ceded by an equal sign.

Notice that the address and address content areas of comments and directives(such as Device or ORG 00h) are blank. Directives and comments do not generateinstructions or associated data for the program ROM. Remember, directives are in-structions for the assembler, not instructions for the microcontroller.

The first generated address is on line 46 of the list file and contains 2805h. 2805his the machine code equivalent of GOTO Initialize. By examining the List file, youcan see each machine code instruction and its exact location. The memory map atright graphically shows the ROM addresses and contents.

The list file demonstrates the result of the ORG directives. For example, theORG 05h directive on line 48 generates no instruction for the program ROM. Rather,it tells the assembler that the next instruction (BSF RP0, or 1683h) should be placedin location 0005h.

BSF RP0 also has the label Initialize associated with it. The assembler willassign location 0005h to this label on the first assembly pass. During the secondpass, any instructions which reference Initialize will be replaced with 0005h. Forexample, GOTO Initialize in line 46 converts to GOTO (28) Initialize (05).

Some patterns in the list file are obvious. 28xx is the machine code for GOTO,and xx86 alters RP0. The job of the assembler is to convert all of the mnemonics tonumeric machine code. These numbers represent our program. In fact, numbers arethe only thing the microcontroller understands. Before assemblers, programmers wouldpainstakingly convert each mnemonic to a machine code number by hand. This bringsa whole new meaning to the phrase ‘some assembly required’!

2805

1683

018612833055

00860063

0000

000100020003

00040005

000600070008

0009000A

000B000C

03FE03FF

Program ROM

Microhard Inc.

Assembly by

the NumbersTM

cordless assembler.

A typical day in the life of a programmer at MicroHard Inc., where their corporatemotto is: “If it’s hard to understand, it’s ‘cause we programmed it by hand!”

The OUTPUT.ASM pro-gram loads into the PICsmemory as shown above.

Page 54: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

54 ©1998 Sirius microSystemsMicrochip Code

Object Code

The object code is the other file created by the assembler. Object code is thenumeric form of your program saved in ASCII format. The EPIC programmer usesthis object code to program the microcontroller.

If you were to examine the object code file, you would see the numeric instruc-tion equivalents that make up your program.

If you examine the numbers carefully, you’ll find the 2805 (GOTO Initialize)and the 1683 (BSF RP0), etc. The object code is stored in an Intel Merged Hexformat with the low byte followed by the high byte (so 2805 becomes 0528). Pro-grammer information and checksums are interspersed throughout.

PM can also generate binary output, map and symbol files. If you need to knowmore about these options, see Appendix C for the details.

Chapter Summary

The function of an assembler is to convert text source code mnemonics intonumeric machine codes. The machine codes generated by the assembler are found inboth the listing and object code files.

Listing files can be used to verify the location of instructions and their addresses.

Object code is used by the programmer to download your program into the mi-crocontroller.

Type ‘edit output.hex’ fromthe MS-DOS prompt toexamine the object codefile. Since object code isonly used by programmer/downloaders, we won’tspend too much timelooking at it.

Object Code

Page 55: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

55Chapter 6

Assembling aProgram

©1998 Sirius microSystems Microchip Code

Questions

1. What is the function of an assembler?

2. How does the assembler generated list file differ from the source code file?

3. Why is the ‘GOTO Initialize’ in line 46 of OUTPUT.ASM a better way ofcoding than ‘GOTO 05h’?

4. Why does the assembler read your source code two times?

5. What address does the assembler assign to the label ‘Main’ on line 54?

Assignment

1. Following the steps described earlier, assemble TOPFOUR.ASM. Examinethe list file. How many instructions were produced?

Page 56: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

56 ©1998 Sirius microSystemsMicrochip CodeNotes

Page 57: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

57Chapter 7

Downloadinga Program

©1998 Sirius microSystems Microchip Code

7 Downloadinga Program

The next—and long awaited step after writing the program source code andassembling it to product object code—is to download our object code into the micro-controller. Once this is done, we can see the program at work.

Which Microcontroller Should I Program?

The PIC-MDS Professional system comes with both the PIC16C711 andPIC16F84 microcontrollers, but is capable of programming any of the 18-pin mid-range (16Cxx series) PICmicro™ microcontrollers. The PIC-MDS Hobbyist sys-tems include only the PIC16F84 microcontroller. Since you will be writing and test-ing a number of programs in the next few chapters, you will need at least one eraseablePIC. The PIC16F84 is EEPROM-based (Electrically Eraseable Read Only Memory)and can be quickly and easily erased while in-circuit.

If you need analog input capability, you may want to use the EPROM-basedPIC16C711 or one of the other PIC16Cxx family. These microcontrollers are avail-able in OTP (one time programmable) and windowed versions. Make sure that youuse one in a ceramic package with a window as specified by the -JW suffix in the partnumber. Otherwise, you will know exactly what Microchip means by one time pro-grammable! To erase EPROM microcontrollers, you will need an uv (ultravioletlight) EPROM eraser. UV erasers are available from most electronic distributors.

Programming

We will program a PIC16F84 with the OUTPUT program we just assembled.At this time, connect the EPIC programmer to your personal computer’s parallel portwith a 25-pin male to female DB-25 cable, and attach the 12 VAC wall adapter.Make sure that the EPIC programming socket is empty until the programming soft-ware is executed. Also be sure that the EPIC Programmer is placed on an insulatedsurface to prevent the circuit traces and pins on the bottom of it from shorting to eachother.

When using an EPROMmicrocontroller with awindow, always cover thewindow after programming.Because silicon is photo-sensitive, light striking thechip die through thewindow can affect themicrocontroller’s opera-tion. Black electrical tapeis an opaque and easilyremovable window cover-ing.

The older PIC16C84 andthe PIC16F84 are electri-cally compatible and canbe used interchangeably.

Page 58: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

58 ©1998 Sirius microSystemsMicrochip Code

The EPIC programmer can be operated from batteries instead of using the 12VAC wall adapter. If you choose to power the EPIC Programmer with two 9 voltbatteries, plug each battery onto the battery snaps. Connect the 2 pin shorting jumperto the 2 pin “Batt ON” jumper. It is a good idea to check the battery voltage fromtime to time, especailly if you are having difficulty programming parts.

WARNING: Do not connect a battery across the centre snaps. Doing soshorts out the battery and may cause it to explode.

The EPIC programmer can program 18-pin mid-range PICs either in its ownprogramming socket, or through the microcontroller socket of the PIC-MDS. Pro-gramming PICs in the PIC-MDS requires that you plug in the wall adapter and thatyou connect the 10-pin programming ribbon cable to the EPIC programmer. Thecable attaches to the PIC-MDS in only one way. However, make sure that the cableconnects to the EPIC programmer properly, as shown in the photograph below:

The programmer should now be powered up and ready to program your PIC.Note that the EPIC LED may be lit at this point. This is no cause for alarm. The LEDshould go out as soon as the EPIC programming software is started. Do not insert orremove a microcontroller from the EPIC or PIC-MDS when the LED is on.

On both the PIC-MDS and EPIC, pin 1 of the programming ribbon cable header is atthe lower left when the writing on the boards is upright. Make sure that you connect theEPIC end of the ribbon cable properly, with pin 1 of the cable closest to the wordprogrammer.

JU3, the RUN/PROGramjumper near the program-ming header on the PIC-MDS should remain in theRUN setting duringprogramming. This isolatesthe power supplies of thePIC-MDS and EPIC andprevents the EPIC fromhaving to power the PIC-MDS.

Programming

Page 59: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

59Chapter 7

Downloadinga Program

©1998 Sirius microSystems Microchip Code

Downloading the Object Code

From the MS-DOS prompt, start the EPIC program by typing:

epic output.hex [enter]

Your computer screen should look like the one shown below:

Your program object code will be visible in the blue portion of the screen, alongwith the address locations of the fist instruction of each line of object codes. Alongthe right, in the turquoise section of the screen are the configuration fuses settingsselected by the Device directive in your program. These settings are the defaults forthe OUTPUT program, but can be changed by clicking on them with a mouse. Chap-ter 3 and the PIC data sheets explain all of the configuration fuse meanings.

We’re now ready to program a PIC16F84. Place the PIC16F84 into the pro-gramming socket of the PIC-MDS with pin 1 at the top-left. Before starting to pro-gram the PIC, make sure that the EPIC Device section matches the one in the dia-gram, above.

Select the Program button now. The EPIC software reads all of the PICs memorylocations to verify that it really is blank, and then programs it. If the PIC in theprogramming socket contains a previous program, EPIC warns you of this and asksif the PIC should be programmed anyway. Select ‘OK’ to continue programming.

A few second later, you will see the message ‘Programming Complete’ at thebottom of the blue section of the screen.

As the microcontroller gets programmed, EPIC verifies the contents of eachmemory location by reading the the memory location and comparing its contents tothe original object code. If the instruction from the memory location and does notmatch the object code, a problem has occurred and EPIC produces a verify error.You may also use the Verify command to compare the memory of a PIC with anobject code program at any time.

If you see a messagestating ‘Programmer notFound’, press and hold theRESET button on the PIC-MDS while selecting Retry.On start-up, EPIC checksfor the presence of a PIC.If the PIC is blank, all I/Opins are inputs and thecheck completes properly.If the PIC has previouslybeen programmed andPORTB.6 and PORTB.7were set as outputs, thecheck will fail. HoldingRESET forces all I/O pinsto input and lets EPIC findthe programmer.

Any of the grey buttons onthe EPIC screen can beselected with the mouse orby pressing and holding theAlt key along with thehighlighted letter of thebutton.

Page 60: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

60 ©1998 Sirius microSystemsMicrochip Code

Running the Program

If you programmed the PIC while in the PIC-MDS, the PIC will execute theprogram as soon as programming has stopped. If you programmed the PIC in theEPIC programmer, gently pry the PIC from the programming socket, insert it into thePIC-MDS and apply power by connecting the plug from the wall adapter.

You should immediately see the binary number 10101010 displayed on the eightLEDs. Congratulations on writing, assembling and programming your first PICmicrocontroller program!

Reprogramming PIC Microcontrollers

As you progress through this text, you will need to reprogram your PIC. If youleave the PIC16F84 in the microcontroller socket of the PIC-MDS you can effort-lessly program it with new programs. The only exception, of course, is programsrequiring analog input. The PIC16C711 can be programmed while in the PIC-MDSbut must be removed for erasure under ultraviolet light.

Chapter Summary

Programming a microcontroller requires that the object code program bedownloaded to the microcontroller. Downloading is most easily accomplished byconnecting the EPIC programmer to the PIC-MDS through the programming ribboncable. Remember to press and hold the RESET button if you get a ‘Programmer notFound’ error when starting EPIC. After programming, the PIC immediately executesthe program.

If you don’t see the properdisplay, try pressing theRESET button. WhileRESET is pressed all LEDsshould be on. If this doesn’thappen, or the outputpattern is not displayedupon releasing RESET, seeAppendix B, Troubleshoot-ing.

Running the Program

Page 61: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

61Chapter 7

Downloadinga Program

©1998 Sirius microSystems Microchip Code

Questions

1. What precautions must be taken before placing a PIC into the EPIC program-mer?

2. When is erasing necessary?

3. How is the PIC16C711 erased?

Assignment

1. Erase and program your microcontroller with both the TOPFOUR programthat you wrote and assembled previously. Verify its operation by running theprogram in the PIC-MDS board.

Remember to put your PIC into the programming socket theright way around, or you’ll find out why programming is alsonicknamed “burning”!

Page 62: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

62 ©1998 Sirius microSystemsMicrochip CodeNotes

Page 63: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

63Chapter 8

Looping©1998 Sirius microSystems Microchip Code

8 Looping

One of the most fundamental programming concepts is looping. If you’ve pro-grammed in BASIC or another high level language you’re probably familiar with theconcept. Basically, looping allows a programmer to repeat code again and again.Loops can go on forever (infinite) or they can repeat a finite number of times. We’llfirst examine infinite loops.

Infinite loops

Infinite loops do not end and have the following structure:

Start code,more code,and still more codeGo to Start

Microcontroller programs almost always have this basic structure. Rememberthat microcontrollers run a program designed for a specific purpose. Most microcon-troller applications involve monitoring and controlling a continuous process. In orderto keep the program running continuously a GOTO instruction is often used to tellthe microcontroller to repeat code from the beginning of the program.

For example, the microcontroller in a computer mouse will check the button androller positions and send this information to a personal computer. The simplifiedpseudo-code for the mouse might look like:

Start Send button 1 stateSend button 2 stateSend X roller motionSend Y roller motionGo to Start

This is an example ofPseudo-code. Pseudo-codeis code programmers writeto identify the flow andstructure of programs.

Page 64: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

64 ©1998 Sirius microSystemsMicrochip Code

Let’s look at a simple program which demonstrates an infinite loop. The pro-gram COUNT.ASM sequentially displays the binary numbers from 0 to 255 on theLED bar graph display. The count will repeat as the Port B register ‘rolls-over’ from255 to 0, very much like a car odometer. The pseudo-code for COUNT.ASM is:

Initialize Set Port B for outputClear Port B

Loop Increment Port BGo to Loop

You may wish to pull out the program COUNT.ASM from the Pull-Out Pro-gram References Section as we describe it.

The program begins with the familiar Maclib, Device and ID directives. Theseare followed by the ORG 00h and GOTO Initialize instructions that form the Resetcode of many example programs (refer to Chapter 5 for more detail).

The Initialize routine prepares Port B for output and clears the LEDs.

INCF PORTB (Increment the File Register, Port B) adds one to the contents ofthe Port B register. Since Port B is connected to the LED bar graph, the value in PortB immediately appears on the LEDs. GOTO Loop forms the infinite loop structure.

Assemble and download this program as you did with OUTPUT.ASM in Chap-ter 6 and Chapter 7. When the PIC microcontroller executes this program, all of theLEDs will appear to be lit. Because there is no delay after the increment instruction,each count appears on the LED only for as long as it takes to execute the GOTOLoop and the next INCF PORTB—about one-millionth of a second at a 10 MHzclock speed!

Maclib �P84.INC� ;Library file for PIC16C84 and PM assembler;Comment this line out for other assemblers

Device PIC16C84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �CNT �

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Turn off LEDs by clearing Port B

Loop INCF PORTB ;Add 1 to Port B registerGOTO Loop ;and do it again, and again...

Done SLEEP ;Stop executing the program

Infinite Loops

To see the current count,just remove the crystalfrom its socket. This stopsthe clock and displays thecount. When you reinsertthe crystal, the programcontinues!

Page 65: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

65Chapter 8

Looping©1998 Sirius microSystems Microchip Code

Finite Loops

Finite loops execute a set number of times and can have two structures. The firstchecks for a condition, and either repeats or exits the loop based on the result of theconditional check. In pseudo-code:

Label code,more code,and still more codeIf condition, go to LabelOtherwise,code,code,and more code

An example of this first structure might be a burglar alarm. The microcontrollermight check a number of sensors, and if one or more are tripped sound an alarm. Thepseudo-code follows:

Check If sensor 1 open, go to AlarmIf sensor 2 open, go to AlarmIf sensor 3 open, go to AlarmGo to Check

Alarm Activate SirenIf correct code entered, go to Alarm_OffGo to Alarm

Alarm_Off Deactivate SirenGo to Check

The second structure requires a variable which is modified during loop execu-tion. The modification of this variable should make a condition true or false. Thecheck for the condition should occur immediately after the modification becausesubsequent instructions can affect this condition. Again, the microcontroller repeatsor exits the loop based on the condition. The pseudo-code looks like:

Initialize variable

Label code,more code,and still more code.Modify variableIf condition, go to LabelOtherwise,code,code,and more code

An example of this structure can be found in a digital clock. The Hours variablemight be set to ‘12’ and the Minutes variable to ‘00’. Every 60 seconds, the Minutesvariable is incremented. When the Minutes variable becomes ‘60’, it is reset to ‘00’and the Hours variable is incremented. When the Hours variable becomes ‘13’ it isreset to ‘01’. The pseudo-code follows on the next page:

Of the 35 PIC mnemonics,13 are commonly used tomodify variables beforemaking a decision based onconditions. They are:ADDWF, ADNWF, COMF,DECF, DECFSZ, INCF,INCFSZ, IORWF, MOVF,RLF, RRF, SUBWF, andXORWF. See the PIC datasheets for more instructiondetails.

Page 66: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

66 ©1998 Sirius microSystemsMicrochip Code

Hours = 12Minutes = 00

Main Wait 60 secondsIncrement MinutesIf Minutes = 60, go to Inc_HoursGo to Main

Inc_Hours Minutes = 00Increment HoursIf Hours = 13, go to Reset_HoursGo to Main

Reset_Hours Hours = 01Go to Main

The number of times that this second type of finite loop structure executes can beaccurately determined. For this reason, it is found in timing and counting applica-tions. Contrast this with the first type of finite loop structure, which exits when acondition is true, rather than when a set number of loops has occurred.

Nested Loops

The program DELAY.ASM modifies COUNT.ASM to include a finite loop de-lay routine. The finite delay includes a nested loop. A nested loop is a loop within aloop. The total number of loops executed in a nested loop is the product of the innerloop and the outer loop. This gives programmers the ability to easily execute morethan 256 loops. The inner loop executes 256 times (as does Port B in the COUNT.ASMprogram) and the outer loop executes once for each time the inner loop cycles through256 loops. In the DELAY.ASM program, the outer loop variable, Counter2, decre-ments 256 times resulting in a total loop count of 65 536 loops (256 X 256) beforeincrementing the count on the LEDs. In pseudo-code:

Initialize Clear Counter1 and Counter2Set Port B for outputClear Port B

Main Increment Port B

Loop Decrement Counter1If Counter1 > 0, go to LoopDecrement Counter2If Counter2 > 0, go to LoopGo to Main

You may find it useful to pull out DELAY.ASM from the Pull-Out ProgramReferences Section as we examine DELAY.ASM in detail.

After the directives, you’ll notice the Hardware Equates comment. The EQU(EQUate) directive, assigns values to labels and symbols. A label is a memory loca-tion that the program can jump to, and a symbol is simply characters which havebeen assigned a numeric value.

The total number of loopsin a nested loop = innerloops X outer loops.

Nested loops are alsouseful for array or matrixapplications. For example,keeping track of keyboardrows and columns.

Finite Loops

inner loop

outer loop

Actually, labels are sym-bols—they are assigned anumeric address value bythe assembler duringassembly.

Page 67: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

67Chapter 8

Looping©1998 Sirius microSystems Microchip Code

At assembly time, the equate statement assigns the value 0Ch to the symbolCounter1, which is also the first unused address location in the RAM register file.Similarly, 0Dh is assigned to the symbol Counter2.

The equates section is followed by the initialization code commonly used in pre-vious example programs.

The initialize routine prepares Port B for output, clears the LEDs, and clears theCounter1 and Counter2 variables. When power is applied to the microcontroller, theunused RAM file registers are not automatically cleared to zero. They contain ran-dom data and should be cleared before use.

;Hardware Equates

Counter1 EQU 0Ch ;First delay counter registerCounter2 EQU 0Dh ;Second delay counter register

The variables Counter1and Counter2 will be storedhere.

Don’t confuse Programmemory locations 000Chand 000Dh with RAMRegister File locations. TheProgram memory containsonly program instructions,not the variables used byprograms.

An ‘=’ can be used inplace of the EQU directive.

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Clear Port B registerCLRF Counter1 ;Clear Counter1 register (0Ch)CLRF Counter2 ;and Counter2 register(0Dh)

Page 68: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

68 ©1998 Sirius microSystemsMicrochip Code

INCF PORTB (Increment the File Register, Port B) adds one to the contents ofthe Port B register. Since Port B is connected to the LED bar graph, the value in PortB immediately appears on the LEDs.

DECFSZ Counter1 (Decrement File Register, Counter1, and skip the next in-struction if zero) is a combined variable modification and jump instruction. Sincethis is a common loop structure, Microchip includes a number of single instructionwords which accomplish both the modification and jump functions.

Before DECFSZ Counter1 executes, Counter1 contains the data 00h (it wascleared in the initialize section). When DECFSZ Counter1 executes for the first time,Counter1 will contain FFh (a decrement from 00h causes a roll-back to FFh). SinceFFh is not equal to zero, the GOTO Loop instruction which follows is not skipped.This inner loop will continue until Counter1 equals 0—256 loops later. When Coun-ter1 finally reaches zero, the DECFSZ Counter1 (Decrement File register, Counter1,and Skip the next instruction if the file register is Zero) skips the GOTO Loop in-struction and DECFSZ Counter2 is the next instruction to be executed.

When DECFSZ Counter2 executes for the first time, Counter2 contains the valueFFh. Since FFh is not equal to zero, the GOTO Loop instruction which follows isexecuted next, which starts the inner loop a second time. After 256 more counts ofthe inner loop, Counter2 will decrement to FEh. For each decrement of Counter2,Counter1 has decremented 256 times.

Eventually, Counter1 and Counter2 both reach zero. In this case, the DECFSZCounter2 instruction causes the microcontroller to skip the GOTO Loop instructionand GOTO Main is the next instruction to be executed.

Again, the total number of loops executed by a nested loop is inner loops X outerloops. In DELAY.ASM this nested loop takes a relatively long time and allows us seethe transitions between successive LED increments.

Calculating Execution Times

The speed at which code executes is dependent on the oscillator clock speed andnumber of machine cycles executed. Instructions require either 1 or 2 machine cyclesto execute. A machine cycle is an internal clock used by the PIC to synchronizeinternal events and is equal to four oscillator clock cycles. Therefore the period ofone machine cycle equals 4 times the main oscillator period.

Main INCF PORTB ;Add 1 to Port B registerLoop DECFSZ Counter1 ;Decrement Counter1 and check for 0

GOTO Loop ;If not 0, decrement Counter 1 againDECFSZ Counter2 ;If 0, decrement Counter2GOTO Loop ;If Counter2 is not 0, decrement

;Counter1 another 256 timesGOTO Main ;Update the LEDs after 65536 counts

DECFSZ and INCFSZ arecommonly used for loops.

One Machine Cycle

Oscillator ClockClock Period

Nested Loops

Page 69: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

69Chapter 8

Looping©1998 Sirius microSystems Microchip Code

If the PIC-MDS clock oscillator frequency is 10 MHz, the oscillator period wouldbe: 1 ̧ 10 MHz = 100 ns. A machine cycle would therefore take 4 X 100 ns = 400 ns.

The number of machine cycles needed to execute an instruction depends on theinstruction type. Any instruction that modifies the program counter requires twomachine cycles to execute. All other instructions require only one machine cycle.Let’s calculate the exact time taken by the nested loop in DELAY.ASM.

The inner loop will take three cycles to execute, and will execute a total of 255times. The 256th time takes only two cycles, because the 00h result in Counter1causes DECFSZ to modify the program counter. GOTO Loop is skipped.

The total number of machine cycles executed in the inner loop is:

(255 X 3) + 2 = 767

After 767 inner loop machine cycles, the outer loop adds three cycles to get backto the inner loop. The outer loop executes 255 times, including the inner loop. On the256th loop, Counter2 will equal zero and the DECFSZ command will skip the GOTOLoop instruction, taking two cycles. Algebraically:

(255 X (767 + 3)) +2 = 196 352

Finally, GOTO Main adds another two cycles giving a total delay until the nextincrement of 196 354 machine cycles.

Since a 10 MHz clock produces a 400 ns machine cycle time, the overall delaybetween LED increments is:

196 354 cycles X 400 ns = 78.5416 ms (or a frequency of 12.7 Hz)

In COUNT.ASM, the number of machine cycles used to increment the LEDs isthree. INCF PORTB requires 1 cycle, GOTO Loop requires two. This means thatLEDs are updated every 3 X 400 ns = 1.2 ms (or at 833.3 kHz)!

With a 10 MHz clock, the execution time of programs can be calculated down to400 ns periods. Although this level of accuracy is not always required, knowing howto calculate cycle times exactly is crucial for timing sensitive applications.

Period =1f

Main INCF PORTB ;Add 1 to Port B registerLoop DECFSZ Counter1 ;Decrement Counter1 and check for 0

GOTO Loop ;If not 0, decrement Counter 1 againDECFSZ Counter2 ;If 0, decrement Counter2GOTO Loop ;If Counter2 is not 0, decrement

;Counter1 another 256 timesGOTO Main ;Update the LEDs after 65536 counts

Number ofmachine cycles

1 (2 if skip)21 (2 if skip)2

2

255 X

255 X

The PIC16C711 suppliedwith the PIC-MDS Profes-sional can be clocked at upto 20 MHz, giving a 200 nscycle time. That’s 5 millioninstructions per second!

Since,

Page 70: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

70 ©1998 Sirius microSystemsMicrochip Code

Chapter Summary

Loops are used to repeat commonly used sections of code and to count. Loopscan be infinite, or be dependent on conditions. Finite loops deliberately modify avariable and branch depending on the occurance of a condition. Microchip providesa number of commands which combine variable modification with a conditionalbranch. Nested loops allow for the efficient execution of a large number of loops.

The time taken by loops is dependent on the instructions used and the number ofmachine cycles taken by those instructions. For the PIC microcontrollers, one ma-chine cycle is four times the oscillator clock period. Most instructions complete inone machine cycle. Those that modify the program counter always take two machinecycles to complete.

Chapter Summary

After much frustration, Suzette finally executes the looping of her code.

Page 71: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

71Chapter 8

Looping©1998 Sirius microSystems Microchip Code

Questions

1. Where in a program would you expect to find commands which form an infi-nite loop? Select from the following:

at the beginningnear the middlenear the beginning and endnear the endreally doesn’t matter, could be anywhere

Explain the reasoning you used to choose your answer.

2. Why do variables need to be initialized as part of a finite loop structure?

3. When does the DECFSZ instruction require 2 cycles? When does it require 1?

4. Examine the PIC16F8x Data Sheets and list all of the instructions that com-bine variable modification and conditional branching.

5. Draw arrows showing program flow in the BLIP.ASM code below.

6. Calculate the length of time for each blip and the delay between blips.

;Hardware EquatesCounter1 EQU 0Ch ;First delay counter registerCounter2 EQU 0Dh ;Second delay counter registerCounter3 EQU 0Eh ;Third delay counter register

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vectorORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Clear Port B registerCLRF Counter1 ;Clear Counter1 register (0Ch)CLRF Counter2 ;and Counter2 register (0Dh)

Main MOVLW 0FFh ;Load W with ones to turn on LEDsMOVWF PORTB ;and write to Port B registerMOVLW 03h ;Load W with 3MOVWF Counter2 ;and preset Counter2 before Loop_On

Loop_On DECFSZ Counter1 ;Decrement Counter1 and check for 0GOTO Loop_On ;If not 0, decrement Counter1 againDECFSZ Counter2 ;If 0, decrement Counter2GOTO Loop_On ;If not 0, do Counter1 loop

CLRF PORTB ;Turn off LEDs by clearing Port BMOVLW 0Dh ;Load W with 13MOVWF Counter3 ;and preset Counter3 before Loop_Off

Loop_Off DECFSZ Counter1 ;Decrement Counter1 and check for 0GOTO Loop_Off ;If not 0, decrement Counter 1 againDECFSZ Counter2 ;If Counter1=0, decrement Counter2GOTO Loop_Off ;If not 0, do Counter1 loopDECFSZ Counter3 ;If Counter2=0, decrement Counter3GOTO Loop_Off ;If not 0, do Counter1 & 2 loopsGOTO Main ;If 0, go to Main

BLIP.ASM is supplied onthe PIC-MDS disk so thatyou can run it and see whatit does.

From BLIP.ASM

Page 72: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

72 ©1998 Sirius microSystemsMicrochip Code

Assignment

1. Write a program which will sweep a single LED across the LED bar graphdisplay continuously. (Hint: Look at the rotate instructions)

2. Modify the program, above, to sweep the LED back and forth across the LEDbar graph display.

3. Write a program which will generate a 440 Hz, 50% duty cycle square waveon an output port pin. You can connect a piezo audio transducer (or a speakerin series with a 270 W resistor, or preferably a 1 mF capacitor) between theoutput port pin and ground on the screw terminal to hear this tone.

4. Write a program which will generate a beep every second. Make the beepduration 250 ms.

Assignment

Page 73: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

73Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

9 Switch InputProgramming

Microcontroller applications often depend on receiving and acting upon inputs.Many of these inputs come from other binary digital devices and are in the form of avoltage (0V or +5V) on an I/O pin. Common binary input devices include pushbuttons,key switches, rotary switches, rotary position encoders, slotted opto-isolators, ma-trix keypads, RS-232 transceivers, and infra-red remote receivers.

Interfacing to Switches

Switches represent one of the most common microcontroller interfaces. Mostswitches provide two contacts which close or open when activated. Normally open(N.O.) pushbuttons provide closed contacts when activated and normally closed (N.C.)switches provide open contacts when activated. Both types of switches can be used toprovide active high or active low inputs to a microcontroller.

The diagram below shows how a normally open pushbutton can be wired toprovide an active low input to a microcontroller. The pull-up resistor provides a logicone (or V+) level to the microcontroller input when the switch is not activated. Whenthe switch is pressed, the switch connects the microcontroller input to ground. Thepull-up resistor prevents the power supply (V+) from being shorted directly to ground.

Port B of the PIC16Cxxmicrocontrollers containsbuilt-in, user controllablepull-up resistors. Thiskeeps external part countsto a minimum. The nominalvalue of these internal pull-ups is 20 kW.

“Active high” means thatthe PIC reads a high (V+)voltage when the switch isactivated, and a low (0V)voltage otherwise. Activelow inputs are the opposite.

Although the PIC-MDSsystem uses +5V for itspower supply and logichigh state, many of thePICmicro™ processors canrun at 2-6V. We’ll repre-sent this voltage as V+.

Page 74: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

74 ©1998 Sirius microSystemsMicrochip CodeInterfacing toSwitches

This next diagram shows how a normally closed pushbutton can be used to pro-vide a logic high level when activated. Once again, the pull-up resistor performs thesame function of providing a logic high when the switch is open, and preventing ashort circuit when the switch is closed.

Let’s look at the program ALARM.ASM which uses a piece of wire as a switch.An LED is turned on if the input wire is disconnected from ground. The structure ofthis program could be used as the basis of an alarm circuit. The pseudo-code for theprogram is as follows:

mainif wire disconnected from ground,

turn on LEDand jump to main

otherwise,turn off LEDand jump to main

If the LED turns on, it indicates that someone has broken the alarm loop.

ALARM.ASM uses the programmable internal pull-up resistors on Port B. Thismeans that an external pull-up resistor is not needed and allows a single piece of wireto act as our switch.

Page 75: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

75Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

Although they are a part of the PIC, our program must enable the pull-up resis-tors in order to use them. The pull-ups are only active when the port pin is an input.Output ports have no need for pull-ups unless they are open-collector outputs.PORTA.4 is the only open-collector output on the PIC16C711 and PIC16F84.

Before running ALARM.ASM youwill need to make a connection to the PIC-MDS terminal strip (CON1) to create thealarm loop. Attach a wire to the PIC-MDSas shown so that CON1-9 (PortB.0) is con-nected to CON1-3 (GND). Remove the wirefrom either terminal to simulate the break-ing of the alarm loop.

You may wish to pull out the programALARM.ASM from the Pull-Out ProgramReferences section as we describe it.

The Initialize section of the program configures the PORTB tristate register,enables the pull-up resistors and turns off the LEDs on Port B. Note how the MOVLW00000001b instruction sets only PORTB.0 as an input. The BCF RBPU (Bit Clearin File register, Port B Pull-Up enable) instruction clears bit 7 in the Option register.Clearing Option.7 enables the pull-up resistors on all Port B inputs.

Note that both TRISB and the OP-TION register are on register page 1. Al-though the TRISB and OPTION regis-ters are both on the PIC block diagram,there is no indication of where the RBPUbit is. RBPU is defined in the .INC fileas Option.7, but referencing RBPU doesnot automatically select register page 1.It is up to you to select register pages, soit is imperative to check the data sheetsbefore using register bits that you are un-familiar with. As you gain more experi-ence with the PIC family, you will get abetter idea of the location of key regis-ters and control bits.

Initialize BSF RP0 ;Select register page 1MOVLW 00000001b ;Load W with desired I/O patternMOVWF TRISB ;Move W to TRISB to make bit 0 input

;(1=input, 0=output)BCF RBPU ;Enable Port B pull-up resistors

;(OPTION.7 on register page 1)BCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDs

Remember, RP0 is theregister page selection bit.Setting RP0 selects registerpage 1.

The symbol RBPU has beenassigned to be Option.7 bythe .INC file.

If you haven’t yet done so,consider reading theMicrochip data sheets now.They provide invaluableinsight into the innerworkings of the PICmicro™family of microcontrollers.

RA.4 is pulled up by R3 inthe PIC-MDS—a 4.7 kWresistor. See the schematicin Chapter 4.

Page 76: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

76 ©1998 Sirius microSystemsMicrochip Code

The Main routine of ALARM.ASM checks our wire and determines whether ornot to light the LED. BTFSC PORTB.0 (Bit Test File register, Skip the next instruc-tion if Bit is clear) is a combination condition test and branch instruction, and checksthe state of the input at Port B, bit 0. If the input is low—or clear, as it would be if thewire is connected—the GOTO LED_On instruction will be skipped, and the BCFPORTB.1 (Bit Clear File register, PORTB.1) instruction will be executed. Clearinga Port B bit turns off the LED associated with it. This part of the program has onefunction: if the wire is connected from PORTB.0 to ground, the LED on PORTB.1 isturned off.

If the wire is disconnected from ground, the input will be pulled high (or set) bythe internal pull-up resistor, and the GOTO LED_On instruction will be executednext. The PIC jumps to the BSF PORTB.1 (Bit Set File register, PORTB.1) instruc-tion and lights the LED on Port B.

Assemble and download the program ALARM.ASM and verify that it works.

Counting Switch Activations

Counting how many times an event has occurred is another common microcon-troller application. Programs which count how many times a switch has been pressedmust take into account one significant characteristic of many switches, namely con-tact bounce. Every time switch contacts close, they may make and break many timesbefore settling down to their final state. The duration of each contact bounce dependson the switch but can be up to a few milliseconds. Remember that instructions takeonly 400 to 800 ns to execute at a 10 MHz clock rate (see Chapter 8). Since themicrocontroller can easily execute over 2000 instructions per millisecond it is fastenough to count each contact bounce as a switch closure. To avoid this, a shortsoftware delay is used to de-bounce the switch, and count only one switch closure.

Remember, the .0 inPORTB.0 is Microchip’sway of checking a singlebit in a file register—notthe whole register.

Counting SwitchActivations

Since PORTB.0 is an input,the LED connected toPORTB.0 will show thestate of the input wire. TheLED on PORTB.1 showsthe output from the PIC.

Main BTFSC PORTB.0 ;Check Port B bit 0 for a lowGOTO LED_On ;If we�re here, bit 0 is highBCF PORTB.1 ;If bit 0 is low, turn off LEDGOTO Main ;Check bit 0 again

LED_On BSF PORTB.1 ;Turn on LED on bit 1GOTO Main ;Check bit 0 again

Software switch de-bounc-ing is cheaper than hard-ware solutions.

Contact Bounce

V+

V+

0 V

Pressed Released

This diagram represents typical switch contact bounces. Your results may vary—widely!

Page 77: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

77Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

BOUNCE.ASM is a program whichwill count the number of times a switchbounces. Program a PIC16F84 withBOUNCE.ASM. BOUNCE.ASM usesPORTA.4 as the input and displays thenumber of bounces on the LEDs in binary.Before running BOUNCE.ASM, connecta wire or switch to ground (CON1-3) andPORTA.4 (CON1-8). The program dis-plays a cumulative count of each switchcontact bounce to ground. To reset the countto zero, press the RESET button on thePIC-MDS.

You should notice that a wire connecting PortA.0 to ground bounces many times.Try a few different switches and note how many times they bounce.

Pull BOUNCE.ASM from the Pull-Out Program References section as we ex-amine how it works. The pseudo-code looks like this:

Initialize variables & ports

MainIf PortA.4 is high, go to mainOtherwise, increment Port B

WaitIf PortA.4 is low, go to WaitOtherwise, go to main

Counting Contact Bounce

V+

V+

0 V

Pressed

Wait foractivation

Inc.count& wait

forhigh

Inc.count& wait

forhigh

Inc.count& wait

forhigh

Inc.count& wait

forhigh

Inc.count& wait

forhigh

Wait! Since the PIC onlyhas built-in pull-ups onPort B, and BOUNCE.SRCuses Port A, don’t we needa pull-up resistor? Yes, andPORTA.4 is pulled up byR3 on the PIC-MDS—a 4.7kW resistor. See the sche-matic in Chapter 4.

Note that BOUNCE.SRCcannot just check for a lowto increment Port B. It mustwait until the input bounceshigh before counting thenext low bounce.

Page 78: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

78 ©1998 Sirius microSystemsMicrochip Code

The Initialize section of the program configures the PORTA and B tristate regis-ters, and turns off the LEDs on Port B.

Main waits for PORTA.4 to go low before incrementing the count on Port B.Then the PIC then executes the Wait_for_High loop until PORTA.4 returns high.

BTFSC PORTA.4 (Bit Test File register, Skip the next instruction if bit Clear)will skip the GOTO Main instruction if PORTA.4 is low. A low on PORTA.4 repre-sents a contact bounce to ground. When this happens, INCF PORTB (Increment Fileregister) adds one to the contents of Port B. Note that the Port B register not onlyconnects to the LEDs, but is also used to store our count.

After incrementing Port B, BTFSS PORTA.4 (Bit Test File register, Skip thenext instruction if bit Set) will execute GOTO Wait_for_High as long as PORTA.4remains low. When PORTA.4 goes high, BTFSS PORTA.4 will skip GOTOWait_for_High and GOTO Main will execute next, repeating the program.

Switch Debouncing

If our applications are going to use switches, our programs obviously need to beable to accommodate the contact bouncing that occurs. The software method of switchdebouncing involves waiting for a switch activation, and then pausing for a fewmilliseconds before checking to see if the button is still activated. By that time thecontacts should have settled down and the activation can be sensed by the program.If the code finds the switch is not activated when it checks for the second time, thefirst detection was likely noise and should not be registered as a switch activation.

DBOUNCE.ASM demonstrates switch debouncing. The pseudo-code is:

Initialize variables & ports

MainIf PortA.4 is high, go to mainOtherwise, execute debounce delayIf PortA.4 has returned high, go to mainOtherwise, increment Port BGo to main

Main BTFSC PORTA.4 ;Check Port A bit 4 for a lowGOTO Main ;If we�re here, bit 4 is highINCF PORTB ;If bit 4 is low, increment Port B

Wait_for_High BTFSS PORTA.4 ;Check Port A bit 4 for a highGOTO Wait_for_High ;If we�re here, bit 4 is still lowGOTO Main ;Bit 4 went high, wait for next bounce

Initialize BSF RP0 ;Select register page 1MOVLW 00010000b ;Load W with the desired I/O patternMOVWF TRISA ;Make Port A bit 4 input

;(1=input, 0=output)CLRF TRISB ;Make Port B outputBCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDs

Noise can be generated byelectrostatic discharge(ESD) from people, or canbe induced from highcurrents being switchednearby. Microchip recom-mends 100 W seriesresistors on inputs tokeyswitches for ESDprotection.

Switch Debouncing

You can use BOUNCE.SRCto check switches forcontact bounce by connect-ing a switch betweenPORTA.4 and ground.Some switches rarelybounce while others maybounce more than tentimes.

Page 79: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

79Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

DBOUNCE.ASM uses the same connections as BOUNCE.ASM. Assemble,download and execute DBOUNCE.ASM to verify its operation. You should be ableto quickly touch and release the wire (or a switch) to PORTA.4 (CON1-8) and causePort B to increment only once.

Pull out DBOUNCE.ASM as we examine it, below:

The Equates section assigns register file locations to our two delay counter vari-ables. The standard Reset Vector code follows the equates.

Initialize configures the Port A and B tristate registers, setting PORTA.4 asinput and all of PORTB as output.

Counter1 and Counter2 are set to 00h and 40h, respectively. This provides anoverall loop delay of 64 (40h) loops of 256. Counter1 decrements from 00h, to FFh,then FEh, and so on back to 00h, providing 256 inner loops.

Main waits for PORTA.4 to drop low. When it does, the GOTO Main instructionis skipped and the Delay subroutine code executes.

The Delay routine is a two-level deep nested loop that executes 16 384 times,wasting 48 512 processor cycles. At a 10 MHz clock speed this provides a delay ofapproximately 19.4 ms—a typical debounce delay time. When the delay loop is com-pleted, Counter2 is re-initialized by MOVLW 40h and MOVWF Counter2 so that itrestarts from 40h rather than 00h.

;Hardware Equates

Counter1 EQU 0Ch ;First delay counter variableCounter2 EQU 0Dh ;Second delay counter variable

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 00010000b ;Load W with the desired I/O patternMOVWF TRISA ;Make Port A bit 4 input

;(1=input, 0=output)CLRF TRISB ;Make Port B outputBCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDsCLRF Counter1 ;Clear location Counter1 (0Ch)MOVLW 40h ;Load W with preset for counter 2MOVWF Counter2 ;Store W to Counter2 (0Dh)

Main BTFSC PORTA.4 ;Check Port A bit 4 for a lowGOTO Main ;If we�re here, bit 4 is high

Delay DECFSZ Counter1 ;If we�re here, bit 4 is lowGOTO Delay ;Let�s wait at least 20 ms for theDECFSZ Counter2 ;contacts to settleGOTO Delay

MOVLW 40h ;Once delay is done, reset counter 2MOVWF Counter2 ;Store W to Counter2 (0Dh)

Page 80: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

80 ©1998 Sirius microSystemsMicrochip Code

BTFSS PORTA.4 ;Is Port A bit 4 still low?INCF PORTB ;If so, increment Port B

Wait_for_High BTFSS PORTA.4 ;Wait for Port A bit 4 to go highGOTO Wait_for_High ;If low, keep checkingGOTO Main ;If high, go back to Main

BTFSS PORTA.4 checks the input, and only increments Port B if PORTA.4 isstill low after the debounce delay. Next, the BTFSS PORTA.4 after the Wait_for_Highlabel causes GOTO Wait_for_High to be executed while PORTA.4 is low. Onlywhen PORTA.4 goes high will GOTO Main be executed.

Interfacing to Matrix Keypads

Matrix keypads are wired in a row-by-column arrangement in order to reducethe number of input/output lines needed to interface them to a microcontroller. In anon-matrix keyboard each button requires its own input line. A matrix keypad isorganized such that each key connects to a row and column in a matrix of wires. Thenumber of lines needed for the matrix keypad is equal to the sum of the columns andthe rows. The number of switches that can be connected in a matrix is the product ofcolumns and rows.

Rows Cols. Sw. Lines

2 2 4 4

2 3 6 5

3 3 9 6

3 4 12 7

4 4 16 8

4 5 20 9

... etc.

Note that for fewer than fourswitches there are no input/output linesavings when using a matrix.

The software technique used to scan matrix keypads connected to microcontrol-lers involves the use of both input and output signals. The rows are connected to theoutput pins, and the columns to the inputs. A ‘0’ output is placed on one row, and ‘1’sare placed on the remaining rows. If a key in the ‘0’ row is pressed, the ‘0’ appears atthe row-column intersection. Column inputs are scanned sequentially, looking for a‘0’. If no ‘0’ is found, the first row is set to a ‘1’ before the second row is lowered to‘0’ and the columns are scanned again.

If a key in a row is not pressed, the input wires are effectively floating. For thisreason, pull-up resistors are required to pull the inputs up to the power supply highlevel. The PIC’s programmable internal pull-ups allow us to interface to matrix keypadswithout adding any external components!

Matrix Keypad

Eight non-matrix switchesrequire eight separatelines—the same numberused to interface sixteenmatrix switches on the PIC-MDS.

Interfacing to MatrixKeypads

Page 81: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

81Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

The diagram shows anexample of key scanning.After making the top rowlow and scanning the col-umns, each of the inputswould be sensed as a ‘1’since none of the top rowkeys are pressed. The pro-gram would then advancethe low to the second row.

As soon as the firstcolumn is scanned, the lowwill be sensed. The pro-gram now knows that thekey at the intersection ofrow two, column one isbeing pressed.

The pseudo-code for a routine which will scan 16 keys, determine which waspressed, and assign a number to the key pressed looks like this:

Initialize variables and ports

MainPlace a low on first rowSet key counter to 1

Column_CheckIf column 1 low, go to DoneOtherwise increment key_counterIf column 2 low, go to DoneOtherwise increment key_counterIf column 3 low, go to DoneOtherwise increment key_counterIf column 4 low, go to DoneOtherwise increment key_counter

Row_SetIf key_counter > 16, go to MainOtherwise, set next row lowGoto Column_Check

Doneadd any code that will use the key press value stored inkey_counter

The program KEYSCAN.ASM is a program which does just this and displaysthe key pressed on the LEDs as a binary number for approximately 0.5 seconds. Aclever feature of this program is that is Port B is shared between the LEDs andkeypad (see the schematic of the PIC-MDS in Chapter 4). Port B is reconfigured tobe an output port during the display phase, and half input and half output duringkeypad scanning.

In order to protect two Port B outputs from being shorted by a key press, eachrow includes a series 2.2 kW resistor (see the schematic in Chapter 4).

Sharing two or moredevices on a microcontrol-ler’s I/O ports is an effi-cient way of using I/O. ThePIC-MDS also shares PortB with the LCD display.

You could, conversely,output on the columns andscan the rows for akeypress. We don’t do this,however, since the columnsof the keypad in the PIC-MDS are wired to the PortB pins which have interruptcapability.

Page 82: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

82 ©1998 Sirius microSystemsMicrochip Code

The opening comments of KEYSCAN.ASM show the keypad row-column con-nections to Port B (as does the schematic) as well as the number assigned to each key.

The Hardware Equates section sets up variables for a delay counter and for thekey return code. The standard reset code follows the variable equates.

Initialize sets half of Port B to input and the other half to output with the MOVLW0F0h and MOVWF TRISB instructions. BCF RBPU enables the internal pull-ups,but they are only active on the input pins (PORTB.4-PORTB.7). Remember thatpull-ups are needed to hold column inputs high when keys are not pressed. Next, thecounter variables are cleared and pre-loaded as indicated by the comments in order toprovide a half second display delay.

Main resets the Key register to one by using the CLRF Key and INCF Key

Main CLRF Key ;Clear Key register andINCF Key ;Increment KeyMOVLW 0Eh ;Output 0 to first row only,MOVWF PORTB ;Output to Port BNOP ;Wait for signals to settle

; Col. 1 2 3 4; Row +----+----+----+----+; Port B.0----1--| 1 | 2 | 3 | 4 |; +----+----+----+----+; Port B.1----2--| 5 | 6 | 7 | 8 |; +----+----+----+----+; Port B.2----3--| 9 | 10 | 11 | 12 |; +----+----+----+----+; Port B.3----4--| 13 | 14 | 15 | 16 |; +--+-+--+-+--+-+--+-+; Port B.4----------+ | | |; | | |; Port B.5---------------+ | |; | |; Port B.6--------------------+ |; |; Port B.7-------------------------+

;Hardware Equates

Counter1 EQU 0Ch ;Delay counter registerCounter2 EQU 0Dh ;Delay counter registerCounter3 EQU 0Eh ;Delay counter registerKey EQU 0Fh ;This register will hold a number from

;0-15 representing the last key pressed

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 0F0h ;Set keypad column connections to input

;(Port B.4-7) and row connections to;output (Port B.0-3)

MOVWF TRISB ;Write to Port B tristate registerBCF RBPU ;Enable pull-ups on inputsBCF RP0 ;Go back to register page 0CLRF Counter1 ;Clear delay loop countersCLRF Counter2MOVLW 08h ;Preload Counter3 delay loop counterMOVWF Counter3 ;for 1/2 second delay

Interfacing to MatrixKeypads

The key numbers areassigned by the order inwhich the matrix scanningtakes place.

Page 83: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

83Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

Col_Check BTFSS PORTB.4 ;Check first column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.5 ;Check second column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.6 ;Check third column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.7 ;Check fourth column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key number

Row_Set MOVLW 11h ;Load W with number of keys + 1SUBWF Key,0 ;and compare with current key valueBTFSC Z ;If keys + 1 = current key thenGOTO Main ;no key was pressed

BSF C ;Set carry bitRLF PORTB ;so that row 1 is high during rotateGOTO Col_Check ;and check next column

instructions. The MOVLW 0Eh and MOVWF PORTB instructions place a low onPORTB.0, the top row of the keypad.

The NOP (No OPeration) instruction is very important, although it seems to donothing. Whenever the state of an output pin is changed, time must be given for thatoutput to settle to the new value before the pin is read. The capacitance of a load onan output pin requires time to charge or discharge to its new value. A NOP instruc-tion can provide a one cycle delay—long enough for an output to stabilize. Even verylow I/O capacitances can introduce a read error because a port write occurs at thevery end of an instruction cycle, and a port read occurs at the very beginning of acycle. Therefore, any port write immediately followed by a port read should be sepa-rated from by a NOP or other non-port modifying instruction so the pin can settle.

The Col_Check routine matches the pseudo-code quite closely. The Done labelin the pseudo-code has been replaced with Dispkey, which displays the value in Keyon the LEDs for half a second. INCF Key updates the key variable after each check.

If no key in the first row is found to be pressed, the Row_Set subroutine willexecute. Row_Set checks to see that the Key variable has not been incremented pastthe number of keys on the keypad (11h equals 17 decimal) by checking if Key equals17. It does this by subtracting 11h from the Key variable using MOVLW 11h andSUBWF Key,0 (SUBtract W from File register Key, leaving the result in W). If Keyequals 17, the result of the subtraction will be zero and the Z bit of the Status registerwill be set. BTFSC Z (Bit Test File register, and Skip the next instruction if thespecified bit is Clear) tests the Z bit of the Status register and returns to Main if nokeys were pressed, beginning the key scanning again.

If the Key variable is below 17, Z will not be set and the BSF C (Bit Set Fileregister, Carry Bit) instruction executes. RLF PORTB (Rotate Left File register)shifts all bits in Port B one position to the left through the Carry bit. This moves the

Though BCF and BSFappear to be outputinstructions, they areactually read-modify-writeinstructions. They read theentire port value, modifyone bit, and write the valueback to the port. Separatethese and subsequent portread instructions withNOPs.

The ‘,0’ in SUBWF Key,0denotes that the result ofthe operation will be storedin W. A ‘,1’ suffix will storethe result in the file registerused in the operation. ThePM assembler also recog-nizes ‘,W’ as a suffix toleave the result of theoperation in W. Notspecifying a destinationsuffix leaves the result inthe file register by default.

Port BC Port B

Before RLF PORTB After RLF PORTB

C

Page 84: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

84 ©1998 Sirius microSystemsMicrochip Code

low from row one to row two. Following the rotate, Col_Check scans the four key-pad columns again. If no key press is detected, Row_Set repeats, checking for thehighest key code and setting the next row low.

If a key is pressed, the low found during Col_Check causes the program toexecute the Dispkey subroutine. Dispkey reconfigures all Port B pins to be outputsand then moves the contents of the key variable to Port B.

Delay is a three-level nested loop providing approximately half a second to viewthe key return code. Following the time delay, the program begins again at Initializeso that Port B is reconfigured and the delay counters are reset.

Chapter Summary

Switches are common input devices for microcontrollers. They can be normallyopen or normally closed and are used with pull-up resistors to provide a logic high orlogic low to the microcontroller when activated.

Switches exhibit contact bounce and this may adversely affect some programs.Debouncing is easily done in software by using a short time delay.

Keypads are commonly wired in a matrix to save on I/O lines. Matrix keypadsrequire row and column scanning to determine the key pressed.

Dispkey BSF RP0 ;Select register page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0

MOVF Key,0 ;Put value of Key into WMOVWF PORTB ;and display on LEDs

Delay DECFSZ Counter1 ;3-level nested loopGOTO Delay ;gives approx. 1/2 second delayDECFSZ Counter2GOTO DelayDECFSZ Counter3GOTO Delay

GOTO Initialize ;We�re done. Reset Port B and delay;counters

Interfacing to MatrixKeypads

Page 85: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

85Chapter 9 - Switch

Input Programming©1998 Sirius microSystems Microchip Code

Questions

1. What is the function of a pull-up resistor?

2. In the switch circuit below, what is the level of the output both during activa-tion and during release?

3. Does bouncing occur on activation, release or both? Explain your reasoning.

4. Explain the concept behind switch debouncing.

5. You are working on a simplified television remote control with five buttons:power, volume up, volume down, channel up and channel down. Show howyou would wire the buttons to a microcontroller. Explain why you chose ma-trix or non-matrix wiring.

6. Explain the concept behind matrix keypad scanning.

7 You are designing a simple serial output keyboard. If you dedicate one I/O lineto the serial output, what is the maximum number of key switches that caninterfaced?

When Grog began working in theQuality Control department atZerocks Information Systems, certainproduct lines showed signs of severeswitch contact bounce.

Page 86: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

86 ©1998 Sirius microSystemsMicrochip CodeAssignment

Assignment

1. Find at least five different switches and using the BOUNCE program make achart of the average number of bounces they produce both on activation andrelease.

2. Using ALARM.ASM as a guide, create a program to indicate not only when acircuit is open, but to flash an LED if the circuit was opened and reconnected.

3. Modify your program, above, so that a key press on the keypad clears theflashing LED.

4. Modify the program further still so that a four-digit code disables the LED.

Page 87: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

87Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

10 Calls andIncludes

Most microcontrollers include instructions that allow you to jump to a subrou-tine and return to your main program routine when the subroutine is finished. Callingsubroutines from your main program has a number of advantages. First, commonlyused sections of code can be written as subroutines which can later be re-used byother programs (for example, a keypad scanning routine). Second, subroutines makeyour programs modular—you can quickly write a new program by stringing togetherexisting subroutines. Third, they save typing and, more importantly, debugging sincethe same pre-tested subroutine can be used again, and again. Finally, code becomessimpler to read because you can get an overview of the program by reading throughthe subroutine calls, not all of the subroutine instructions.

Include, CALL and RETURN

The INCLUDE directive and the CALL and RETURN instructions are neededto incorporate subroutines in your programs. The INCLUDE directive pastes the filereferred to by it into your program, at the location of the INCLUDE statement. Theincluded file is inserted into your code at assembly time.

CALL (CALL subroutine) is the instruction that causes program execution tocontinue at the subroutine memory location, similar to a GOTO. Unlike a GOTO,however, CALL pushes the memory location of the next instruction to be executedafter the call onto the stack in the processing unit. When the subroutine finishesexecuting, a RETURN (RETURN from subroutine) instruction can pop the memorylocation saved in the stack into the Program Counter, and the PIC continues execut-ing the program from the instruction following the CALL instruction. RETURN isalways the last instruction executed in a subroutine.

The stack in the mid-range PICmicro™ family is an eight-level, first-in, last-outmemory. If a CALL occurs within a called routine, the address of the next returnmemory location is pushed onto the stack on top of the first memory location. Assuch, the second memory location will be the first to be popped off the stack by theRETURN instruction—similar to stacks of dinner plates at a buffet restaurant.

With an eight level stack asubroutine can call anothersubroutine, which can callanother subroutine, and soon, a maximum of eighttimes.

Page 88: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

88 ©1998 Sirius microSystemsMicrochip CodeInclude, CALL andRETURN

Scanning a matrix keypad is just the kind of application that is suited to beingwritten as subroutine. KEYSCLB.ASM is a program which accomplishes the sametask as KEYSCAN.ASM in Chapter 9, but uses the INCLUDE directive along withCALL and RETURN. Let’s look at the pseudo-code for KEYSCLB.ASM first.

Initialize variables

StartCall keypad initialize subroutine

MainCall keypad scanning subroutineIf no key was pressed, go to MainOtherwise, set Port B to outputDisplay key for 0.5 sGo to Start

The keypad initialize and scanning subroutines look like:

InitializeSet PORTB.0-3 as output and PORTB.4-7 as inputReturn

ScanPlace a low on first rowSet key counter to 1

Column_CheckIf column 1 low, ReturnOtherwise increment key_counterIf column 2 low, ReturnOtherwise increment key_counterIf column 3 low, ReturnOtherwise increment key_counterIf column 4 low, ReturnOtherwise increment key_counter

Row_SetIf key_counter > 16, go to No_KeysOtherwise, set next row lowGoto Column_Check

No_KeysClear key_counterReturn

Normally, program pseudo-code does not need to show the subroutine’s pseudo-code. We have included the matrix key scanning pseudo-code to highlight the execu-tion sequence. When subroutines are written, they can be documented with their owncomments, pseudo-code, or flow charts.

The real power behind subroutines lies in the fact that it is not necessary for youto understand the inner workings of the subroutine in order to use it. As long as youunderstand what the subroutine does and how to call it, you can use it in your code.

You may wish to pull out both KEYPAD.LIB and KEYSCLB.ASM from thePull-Out Program References section as we describe how KEYSCLB.ASM callsKEYPAD.LIB to perform the matrix keypad scanning.

Notice how muchsmaller the mainprogram has become byusing calls to thesubroutine rather thanwriting the subroutineas part of the mainprogram code.

The PIC-MDS comes with anumber of pretestedsubroutines to assist you inprogramming.

Page 89: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

89Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after interrupt vector

ORG 05h ;One location past interrupt vector

Include �KEYPAD.LIB�;KEYPAD.LIB subroutines go here

;Hardware Equates

Counter1 EQU 0Ch ;Delay counter registerCounter2 EQU 0Dh ;Delay counter registerCounter3 EQU 0Eh ;Delay counter register

;Equates required by KEYPAD.LIBKey EQU 0Fh ;This register will hold a number from

;0-15 representing the last key pressed

Counter1-3 are variable locations used by the three-level, 0.5 s display delayloop. The Key variable is used by the included KEYPAD.LIB subroutine library.

The calling program—in this example, KEYSCLB.ASM—must define the fileregister locations that its included subroutines use. To find out which subroutinevariables require registers, you must read the comment sections of the subroutinelibraries. These comments also explain the function and use of the subroutines.

Although the Included library files can define register locations by using EQUatestatements, the subroutine library file has no way of knowing if these locations havealready been assigned by your program. Therefore, the PIC-MDS subroutines re-quire that the calling program assigns all register locations to variables.

The Include directive inserts the file specified within quotes at the exact locationof the Include statement. In this example, the instructions in the file KEYPAD.LIBwill be placed into program memory starting at location 0005h.

After assembly, the KEYSCLB.LST file will show the included files. Includedfiles have an asterisk beside their line number to denote that they were not a part ofthe original source code.

Placing Include directives at the beginning of your program is a convention thatmakes it easy to find the files that have been included into your program. The includestatement can, however, be placed anywhere in your program. Care must be taken sothat the include file does not disrupt or break into any existing code. For this reason,another convention is to place the Include directives at the end of the program.

Now might be a good timeto read over the commentsin the KEYPAD.LIBsubroutine library.

106 ORG 00h ;Reset Vector loc 107 0000- 2825 GOTO Initialize ;Start program af 108 109 ORG 05h ;One location pas 110 111 Include �KEYPAD.LIB� ;KEYPAD.LIB subro* 1 ;KEYPAD.LIB v1.1 Last Modified on May 20, 1996* 2* 3 ;These program subroutines were written for the Sirius Mi* 4 ;microcontroller development system (http://www.siriusmic* 5* 6 ;Sirius MicroSystems provides this software on an �as is�* 7 ;warranty, either expressed or implied. All Sirius MicroS

If you look further downthe .LST file, you will findthe first instruction of theKEYPAD.LIB file, or 1683h(BSF RP0), at location0005h.

Page 90: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

90 ©1998 Sirius microSystemsMicrochip CodeInclude, CALL andRETURN

Initialize CALL KB_Port ;Library call to initialize Port B for;keypad input

CLRF Counter1 ;Clear delay loop countersCLRF Counter2MOVLW 08h ;Preload Counter3 delay loop counterMOVWF Counter3 ;for 1/2 second delay

The KB_Port label references a subroutine that is a part of the KEYPAD.LIBinclude file. You will not find the KB_Port subroutine in KEYSCLB.ASM. KB_Portsets Port B for keypad input, and when KB_Port returns, CLRF Counter1 is the nextinstruction to be executed. Let’s examine KEYSCLB.LST to see what takes place inthe hardware stack when this call instruction occurs.

The CALL KB_Port instruction pushes theaddress of the next instruction (CLRF Coun-ter1) on to the stack before loading the Pro-gram Counter with the address of KB_Port.After address 0026h is saved on the stack, ex-ecution begins at KB_Port (location 0005h).

After the KB_Port subroutine has finished,its RETURN instruction pops the top stackaddress back into the program counter. Pro-gram execution continues at the address loca-tion immediatley following the CALL (0026h).

KB_Scan is another subroutine in the included KEYPAD.LIB subroutine library.KB_Scan scans the keypad, and returns a value in the Key variable. If a key ispressed, the value returned in Key is a number from one to sixteen. If no key ispressed, the value returned in Key is zero. Examine the KEYPAD.LIB library file fordetails.

MOVF Key,0 and BTFSC Z check to see if the Key value is equal to zero, and ifKey is zero, KB_Scan is called again. The MOVF Key,0 instruction is used withBTFSC Z to ensure that the Z flag accurately reflects the value in Key. If you exam-ine KB_Scan closely, you will find that no instructions modify the Z flag after Key iscleared. However, it is good programming practice to force flag updates before con-ditional checks, since previous instructions and subroutines may have corrupted theflags. This is especially important with subroutines that you have not created orthoroughly examined.

113 0025- 2005 Initialize CALL KB_Port ;Library call to 114 ;keypad input 115 0026- 018C CLRF Counter1 ;Clear delay loop 116 0027- 018D CLRF Counter2 117 0028- 3008 MOVLW 08h ;Preload Counter3 118 0029- 008E MOVWF Counter3 ;for 1/2 second d

Fetch/Decode Unit

ALU

W

Program Counter

ProcessingUnit

0026

Fetch/Decode Unit

ALU

W

Program Counter

ProcessingUnit

0026

Main CALL KB_Scan ;Library call to scan keypadMOVF Key,0 ;Load value of Key into WBTFSC Z ;Check for no keyGOTO Main ;If Z set, no key so scan again

Though most PIC instruc-tions execute in one cycle,any instruction thatmodifies the ProgramCounter requires twocycles. CALL and RETURNboth need two cycles.

Page 91: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

91Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

Delay DECFSZ Counter1 ;3-level nested loopGOTO Delay ;gives approx. 1/2 second delayDECFSZ Counter2GOTO DelayDECFSZ Counter3GOTO Delay

GOTO Initialize ;We�re done. Reset Port B and delay;counters

Dispkey BSF RP0 ;Select register page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0

MOVF Key,0 ;Put value of Key into WMOVWF PORTB ;and display on LEDs

If the Key value is not zero, BTFSC causes GOTO Main to be skipped and theDispkey routine executes next. Dispkey sets all of Port B to output, and displays thekey value on the Port B LEDs.

Delay is a 3 level nested loop which ensures that the key value remains on theLEDs for about 0.5s

Reading ROM Data Tables using Calls

A ROM data table is a list of constants in program memory. These constants canbe musical tunes, delay values, ASCII characters, default parameters, serial num-bers, sine wave look up tables, or any constant required by your program. ROMtables should not be confused with RAM data tables which contain dynamic valuesstored in file registers or the PIC16F84’s Data EEPROM.

Our example for ROM data tables is the KEY.ASM program which displays thekey value on the LCD display. In addition to demonstrating data tables it also usestwo subroutine libraries (LCD.LIB and BIN2DEC.LIB) that you are not yet familiarwith.

Pull out KEY.ASM from the Pull-out Program References section and find thehighlighted sections of code as we describe them.

Actually, MOVF Key,0 isnot needed as W containsKey from the earlier check.However, if memory allows,adding the MOVF instruc-tion allows you to makemodifications within orbefore Dispkey withoutworrying about the con-tents of W changing. Thisconvention results in morerobust code which can bemore easily modified.

Although LCD.LIB isdescribed in more detail inChapter 12, that shouldn’tdeter you from using it.One of the advantages ofsubroutines is that theycontain pre-written codethat works! You only needto know how to call thesubroutines and define thevariables they require.

Like most of us, Gus wasalready familiar with thestack concept of last-in,first-out.

Page 92: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

92 ©1998 Sirius microSystemsMicrochip Code

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key storage registerCALL LCD_Port ;Set up ports for LCD outputCALL LCD_Init ;Initialize LCD and clear screenGOTO Initialize ;Continue with initialize routine

ORG 05h ;Continue after interrupt vector

Include �LCD.LIB� ;LCD subroutines go hereInclude �KEYPAD.LIB�;followed by Keypad subroutinesInclude �BIN2DEC.LIB� ;and Binary to Decimal conversion

Initialize CALL DisplayInit ;Display �Key Pressed:� on LCD

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by KEYPAD.LIB:Key DS 1 ;Key code return register

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Other equatesCounter DS 1 ;character counter for LCDCounter1 DS 1 ;general purpose counterCounter2 DS 1 ;general purpose counterCounter3 DS 1 ;general purpose counter

As discussed earlier, ORG sets the ORiGin for program instructions. ORG canalso be used to set the origin for file register memory. In KEY.ASM, above, ORG0Ch points to the first free file register location (0Ch). The DS (Define Space) direc-tives which follow the ORG assign file register locations to the referenced symbols.

In KEY.ASM, for example, the variable Key is assigned a one byte location at0Ch. Hundreds follows at 0Dh. In contrast with EQU, using DS to define variablelocations makes the locations dynamic—the assembler assigns locations as needed atassembly time. EQU requires you to assign each location.

The advantage of using DS is that variables can be created and removed withoutmanually reassigning their addresses. The disadvantage of using DS is that variablelocations may not be known until assembly time. Another consideration when usingDS is that the ORG used to define the beginning of file register space also defines thebeginning of program memory. A subsequent ORG statement must be used to resetthe pointer to program memory.

The ORG 00h directive resets the origin to the beginning of program memory.

Up to this point, the first instruction following ORG 00h has been a GOTOwhich will jump over the interrupt vector. This program shows how you can cram anextra three words of program code into the space from 0000h to 0003h. Rememberthat the Interrupt Vector is still at location 0004h. Therefore, CLRF Key, CALLLCD_Port, CALL LCD_Init, and GOTO Initialize occupy the first four locations ofprogram memory. The fifth location (0004h) is jumped over by the GOTO Initializeand is left blank for use as an interrupt vector if needed.

Interrupts are described inmore detail in Chapter 11.Actually, this program willbe modified in Chapter 11to use interrupts.

Reading ROM DataTables using CALLs

KEY.ASM uses DS todynamically allocateregisters instead ofEQUate. See the text forthe advantages and disad-vantages of doing this.

Page 93: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

93Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

Notice again that the Include directives occur after the ORG 05h directive. Allthree included subroutine library files are located in program memory starting withLCD.LIB at location 0005h.

CLRF Key initializes the Key register to zero. CALL LCD_Port configures PortsA and B for LCD use. Chapter 12 and the LCD.LIB subroutine explain the operationof LCD.LIB in more detail. For now, all you need to know to use the LCD display isthat you must first initialize the ports for LCD use by calling LCD_Port, and theninitialize the LCD by calling LCD_Init. After this, load W with an ASCII charactervalue and call LCD_Data to display the character. Commands to set cursor position,scroll the display, set line number and cursor options are also loaded in W, butLCD_Reg is called rather than LCD_Data. Also, LCD.LIB calls a delay subroutinecalled Delay_5ms. You must include a five millisecond or longer delay subroutinewith this name in your calling program.

The Delay_5ms subroutine in KEY.ASM assumes a clock speed of 16 MHz.You can change MOVLW 1Ah to increase or decrease the delay to match your clockfrequency. The delay can be longer than 5 ms, but not shorter—so you can leave theMOVLW 1Ah unchanged for slower clock speeds.

After the LCD is initialized, GOTO Initialize is the next instruction to be ex-ecuted. The GOTO Initialize calls DisplayInit. You may wonder why a CALLDisplayInit is not used in place of GOTO Initialize. Remember that DisplayInit is asubroutine and therefore the last instruction executed will be a RETURN. Returncauses the execution of the instruction following the CALL to occur—in this casethere is no instruction at 0004h, the interrupt vector, where the program executionwould return had a CALL DisplayInit been used.

DisplayInit writes the words ‘Key Pressed:’ on the LCD using a Data Tableread. The first part of DisplayInit sends commands to the LCD display which clearthe display and set the cursor to the first character of line 1. In preparation for thedata table read, CLRF Counter resets the data table pointer to zero.

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with Timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

DisplayInit ;Writes �Key Pressed:� to first line of LCD using;LCD display library (LCD.LIB).

MOVLW LCDCLR ;Send LCD clear display codeCALL LCD_REG ;to LCD as a commandMOVLW LCDLine1 ;Send LCD line one address toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Page 94: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

94 ©1998 Sirius microSystemsMicrochip Code

The Get_Char loop reads one character at a time from the data table, comparesthe character value to zero—a check to see if the end of data has been reached—andsends the character to the LCD for display.

The first time through the loop, Counter is zero. The CALL Message jumps toMessage where the ADDWF PCL (ADD W to File register, Program Counter Lowbyte) adds the value of counter to the low byte of the Program Counter. What isn’tobvious at this point is that the Program Counter is already pointing at the location ofthe RETLW ‘K’ instruction. Microprocessors typically increment the Program Counterto the next location after having read the current location.

Therefore, the ADDWF PCL adds zero to the location of the Program Counter,so the Program Counter continues to point to the memory location containing RETLW‘K’. RETLW ‘K’ (RETurn from subroutine with Literal in W) returns execution ofthe program to the line following CALL Message with the ASCII value of ‘K’ in W.

With W now containing the first character from the table, the character needs tobe checked to see if it equals zero, representing the end of data. RETLW does not,however, update the Z flag based on the contents of W. IORLW 00h (Inclusive ORLiteral with W) is a non-destructive way of checking W for zero and updating the Zflag—subtracts, adds and ANDs can also be used.

If the RETLW character is not zero, BTFSC Z skips the RETURN, and CALLLCD_Data is executed next. Calling LCD_Data writes the character in W to theLCD display. INCF Counter,1 increments the data table counter so that the nextcharacter will be read by CALL Message. GOTO Get_Char starts the table readprocess again with the new value of Counter in W.

When CALL Message executes the second time, W will contain one. ADDWFPCL adds one to the PCL this time, offsetting the Program Counter to the line con-taining RETLW ‘e’. Each successive time through the Get_Char loop, INCF Coun-ter,1 causes ADDWF PCL to return and display the next character, until the zerocharacter is returned. This process shows how the Message data table is read.

Get_Char MOVF Counter,0 ;Get character offset into WCALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for next character

Message ADDWF PCL ;Offset program counter by adding WRETLW �K� ;MessageRETLW �e�RETLW �y�RETLW � �RETLW �P�RETLW �r�RETLW �e�RETLW �s�RETLW �s�RETLW �e�RETLW �d�RETLW �:�RETLW 0 ;End of message marker

Since subroutines maymodify flags duringexecution, RETURNs donot change the status of theflags so your callingprogram can check them.

At this point, two levels ofStack are used: one for theCALL DisplayInit and onefor CALL Message.

Reading ROM DataTables using CALLs

Page 95: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

95Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

Main ;This program loop scans the keypad using KEYPAD.LIB and;gets the key value from Key register. BIN2DEC.LIB is used;to convert the binary key number to three decimal digits.;Each decimal digit is converted to ASCII by adding 30h and;is sent to the LCD display.

MOVF Key,0 ;Get key code in WCALL BIN_DEC ;and convert to decimalCALL LCD_Port ;Set up ports for LCD outputMOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to LCD display data RAMMOVLW 30h ;Load constant to convert to ASCIIADDWF Hundreds,1 ;and add to hundreds digitADDWF Tens,1 ;add to tens digitADDWF Ones,1 ;and add to ones digitMOVF Hundreds,0 ;Get hundreds digit into WCALL LCD_Data ;and send it to LCDMOVF Tens,0 ;Get tens digit into WCALL LCD_Data ;and send it to LCDMOVF Ones,0 ;Get ones digit into WCALL LCD_Data ;and send it to LCDCALL KB_Port ;Set up Port B for keypad inputCALL KB_Scan ;Read Port B for key pressGOTO Main ;Do it again!

Finally, we can examine the main program routine. MOVF Key,0 is placed hereto load W with the key value from a later call to KB_Scan. The first time throughMain, Key will be zero since it has been cleared by the very first instruction afterORG 00h. CALL BIN_DEC converts the value in W to three decimal digits—onefor each of the hundreds, tens and ones digits. The result of the conversion is storedin the previously defined Hundreds, Tens and Ones registers.

CALL LCD_Port is executed again, since the call to KB_Port in Main modifiesthe port configuration. MOVLW 8Dh loads W with the address location of the thir-teenth (0Dh equals 13, and 80h is the start of line 1) character position on line one ofthe LCD display. The call to LCD_REG sends the 8Dh command to move the cursorto the specified position.

MOVLW 30h and ADDWF Hundreds,1 converts the binary number in Hun-dreds to an ASCII number. The digits 0-9 are encoded in ASCII as values 30h-39h.The tens and ones digits are also converted, and in each case the ‘,1’ specifies that theresult is stored in the file register, and not in the working register. Note how W stillcontains 30h after each addition.

With the ASCII equivalent of the numbers now in Hundreds, Tens, and Ones, thefollowing MOVF and CALL LCD_Data instructions write the numbers to the LCDdisplay. The cursor automatically moves to the next position after each character iswritten.

Finally, CALL KB_Port and CALL KB_Scan reconfigure the ports for matrixkey scanning and return a key value in the Key register. GOTO Main restarts theprocess and updates the LCD display with the current value of Key.

Notice how calls to included files greatly simplify the Main code. Main callssubroutines to control and write to the LCD display, convert numbers from binary todecimal, and scan the matrix keypad, but the details of these operations do not clutterthe Main code. As such the Main code is easily readable and understandable.

You can examine thecomments in theBIN2DEC.LIB andDEC2BIN.LIB files for adetailed explanation ofhow they work.

Remember, a ‘,0’ stores theresult of operations in W.

Page 96: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

96 ©1998 Sirius microSystemsMicrochip CodeChapter Summary

Chapter Summary

CALL is a powerful instruction that lets you jump to program subroutines. ARETURN command in the called subroutine returns execution to the instructionfollowing the CALL. CALLing and RETURNing is different from GOTO, whichsimply redirects program execution.

The Include directive allows you to easily insert previously written subroutinesinto your program and execute them with either CALLs or GOTOs.

RETLW is a variation of RETURN that loads W with a constant before return-ing execution to the calling routine. RETLW is ideally suited to reading data tablesfrom program memory.

Page 97: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

97Chapter 10

Calls and Includes©1998 Sirius microSystems Microchip Code

Questions

1. Why must every called subroutine have a RETURN instruction?

2. Can a subroutine have more than one RETURN? Explain.

3. What limits whether a subroutine can be called from within a subroutine?

4. How does RETLW differ from RETURN?

5. Why can RETLW not be used in the Data EEPROM of the PIC16F84?

6. Describe what the assembler does when it encounters an Include directive.

7. Explain why the included library is corrupted in the program segment, below:

8. What variables must be defined by your calling program in order to use eachof the following subroutine libraries:

KEYPAD.LIB BIN2DEC.LIB DEC2BIN.LIBLCD.LIB ATOD.LIB EEPROM.LIBRS232RX.LIB RS232TX.LIB SEEPROM.LIB

ORG 00h ;Start program at Reset VectorGOTO Initialize ;Continue with initialize routine

Include �KEYPAD.LIB�;followed by Keypad subroutines

ORG 05h ;Continue after interrupt vector

Initialize BSF RP0 ;Select register page 1CLRF PORTB ;Set Port B to output

Page 98: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

98 ©1998 Sirius microSystemsMicrochip CodeAssignment

Assignment

1. Using a data table and KEYPAD.LIB, write a program to light the LED corre-sponding to the number of the key pressed (from Key one to eight). For exam-ple, pressing key one should light LED RB0, pressing key two should lightLED RB1, etc.

2. Write a program to display the numbers 01 to 99 in BCD (binary coded deci-mal) on the Port B LEDs. For example, pressing key 1 followed by key 6should display the value 00010110 on the LEDs.

3. Write the pseudo-code for digital lock program subroutine that compares sixdigits entered on the keypad to six numbers stored in a data table. If the correctcode is entered the subroutine should clear a file register bit named Code_Ok,otherwise Code_Ok should be set to one.

4. Write the subroutine using the pseudo-code described in 3, above. DefineCode_Ok as a single bit in the file register Alarm_Bits. You can do this by:

Alarm_Bits EQU 0ChCode_Ok EQU Alarm_Bits.0

5. Write alarm code which displays the message ‘Enter Code’ and checks thenext six digits entered from the keypad against values stored in the data tableusing the subroutine from 4, above. If the correct code is entered, your pro-gram should display ‘Access Granted’, otherwise display ‘Access Denied’.

Page 99: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

99Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

11 Interrupts

Interrupts are microcontroller hardware responses to specific events. When aninterrupt event occurs, the microcontroller hardware temporarily suspends the cur-rent program in order to handle the interrupt. Once the interrupt has been serviced,normal processing resumes. This process is very similar to calling a subroutine andthen returning to the calling code except that hardware events, not software calls,trigger a call to the interrupt service routine. Interrupt events can be internal or exter-nal. Internal interrupt triggers include timer/counter (TMR0) overflow, the comple-tion of an EEPROM write, and the completion of an A/D conversion. External eventsthat cause interrupts are a change on PortB.0 (INT), a change on PortB.4-7 (Port BChange), or an overflow of the timer/counter (TMR0).

Interrupts are ideally suited to processing random events as they occur, and thenreturning to the previous task. In essence, this enables an efficient form of multi-tasking. In interrupt-driven programs, the processor focuses on one main task untilan interrupt occurs. As soon as an interrupt occurs, the processor always executes aninterrupt service routine, and, once finished, the main program resumes executionfrom where it was interrupted. For example, the keypad interface programs in theprevious chapters repeatedly polled the keypad for user input. Polling is inefficient ifother processing must take place while waiting for a key press. That is, your programspends valuable clock cycles checking for key presses—clock cycles that may beneeded for a complex math routine, for example. With interrupts, the program canperform other tasks and respond to a key press only when it occurs, because thekeypress itself forces the program to read the keys. The only time the key scanningcode would execute when using interrupts is in response to a key press.

The response of the microcontroller to an interrupt is similar to that of the CALLinstruction. During an interrupt the microcontroller finishes the current instruction,pushes the address of the next instruction onto the stack, and performs an automaticcall to the Interrupt Vector at memory location 0004h—which is where you wouldeither put the interrupt service subroutine, or a GOTO to the routine. The interruptservice routine should determine the cause of the interrupt, respond appropriately,and exit with a RETURN or RETFIE instruction. The RETURN or RETFIE in-struction pops the top address off the stack so that processing can continue fromwhere the microcontroller was interrupted.

TMR0 can count externalevents (counter mode) orinternal processor cycles(timer mode), but not at thesame time. An interrupt isgenerated whenever TMR0overflows.

RETFIE (RETurn FromInterrupt, & Enableinterrupts) is most com-monly used. An interruptdisables further interruptsso that interrupt processingisn’t interrupted. RETFIEre-enables interruptswhereas a RETURN doesnot.

Page 100: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

100 ©1998 Sirius microSystemsMicrochip Code

Interrupt Registers and Flags

Interrupts are controlled through registers and flags. A number of registers con-tain interrupt control bits, and the INTCON register (0Bh or 8Bh) contains mostinterrupt flag bits. Interrupt control bits enable and configure interrupts. Interruptflag bits signify that an interrupt event has occurred.

The Global Interrupt Enable (GIE) bit in the INTCON register enables all inter-rupts. Each interrupt flag has a corresponding enable bit that must be set in order forthe interrupt to pass on to the final AND operation with GIE. Notice also, that eachinterrupt can wake the processor from a SLEEP instruction, even with GIE cleared.

The interrupt flags and enable bits are found in the INTCON register with theexception of EEIF in the PIC16F84 and ADIF in the PIC16C711.

TMR0 Interrupt

A Timer 0 (TMR0) interrupt flag is generated when the TMR0 register over-flows from FFh to 00h. Timer 0 can be fed by either the internal instruction cycleclock or by an external clock on the PortA.4 pin. The INTCON register bit T0IEenables the timer 0 interrupt, and T0IF is the timer 0 interrupt flag bit. The OPTIONregister controls the TMR0 clock source, the clock edge used, and the prescalerdivisor.

GIE

bit 7 bit 0

RBIEEEIE T0IFT0IE INTFINTE RBIF

INTCON Register

T0IF

Interrupt to CPU

Wake-up if inSLEEP

EEIF

RBIF

INTF

T0IE

EEIE

GIE

RBIE

INTE

Interrupt Logic

EEIF signifies the comple-tion of an EEPROM Datawrite. ADIF signifies thecompletion of an A/Dconversion.

RBPU

bit 7 bit 0

PSAINTEDG PS2T0CS PS1T0SE PS0

OPTION RegisterPages 16-17 of thePIC16F8X data sheetssummarize the OPTIONand INTCON register bits.

Interrupt Registersand Flags

Interrupts connect to thePIC16F84 microcontrollerthrough the logic at right.T0IF is the TMR0 InterruptFlag, and T0IE is theTMR0 Interrupt Enable bit.Likewise, the INT pin(PORTB.0) has a flag andenable bit, as do PORTB(RB) change interrupts,and the data EEPROM.The PIC16C711 has A-to-DADIF and ADIE inputsinstead of EEIF and EEIE.

Clock Out (fosc/4)0

0

1

1

RA4/T0CKI

8-bit PrescalerT0SE

T0CS

PSA

T0IF

PS2 PS1 PS0

MUX M

UX

TMR0 Register

Page 101: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

101Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

Setting the timer 0 Clock Select bit (T0CS, or OPTION.5) selects a transition onthe PortA.4 pin, whereas clearing T0CS selects the internal instruction cycle clock.When using an external clock (T0CS is set), setting T0SE selects a high to low clocktransition to increment the TMR0 register. Conversely, clearing T0SE incrementsTMR0 on a low to high clock transition.

When cleared, the Prescaler Assignment Bit (PSA, or OPTION.3) divides theTMR0 clock source by a programmable prescaler value of 2 to 256. The prescalerdivisor is selected using bits PS0, PS1 and PS2. To increment TMR0 on every clock(without a prescaler), the PSA bit must be set, assigning the prescaler to the WatchDog Timer (WDT).

When TMR0 is set to count internal cycles, it can provide accurate time delayswhile allowing other processing to still take place. TMR0 can count external eventsto a maximum frequency of 50 MHz.

In the PIC-MDS, PortA.4 is connected to the serial receiver input. A serial char-acter arriving from an external device can overflow TMR0, generating an interrupt.

INT Interrupt

PortB.0 is also known as the interrupt pin (INT). The INTF flag is generatedwhenever a transition matching the interrupt edge setting (INTEDG, or OPTION.6)occurs. The INT interrupt is enabled by the interrupt enable bit (INTE) and GIE.

A single event generated by an external peripheral such as a limit switch can besensed using the INT pin.

Port B Change Interrupt

When set as inputs, PortB.4-7 were designed to generate an interrupt in responseto any change in signal level from the last level read. RBIF and RBIE are the flag andenable bits, respectively.

The Port B change interrupt is ideally suited to scanning keypads for a change,even while the PIC is in SLEEP mode. The PIC-MDS uses PortB.4-7 as inputs forthe matrix keypad, so that any key press can generate an interrupt.

Waiting for a PortB change while putting the PIC to ‘sleep’ is an effective way ofprolonging battery life. The PIC SLEEP instruction stops the processor clock, greatlyreducing power consumption. A television remote control can save battery power by‘sleeping’ most of the time, and ‘waking up’ in response to a key press.

EEPROM Interrupt

The EEIF interrupt flag bit (EECON1.4) is set when a write to the EEPROMData Memory of the PIC16F84 is finished. EEIE (INTCON.6) gates the EEIF inter-rupt. An EEPROM interrupt is useful since a write to the EEPROM can take aconsiderable amount of time. A typical EEPROM write takes 10 ms. In 10 ms a 10MHz PIC16F84 can execute 25 000 instructions!

See page 16 of thePIC16F8X data sheet forprescaler assignments.Note: The prescaler may beassigned to either TMR0 orWDT, but not both.

Refer to Chapter 13 formore information on theData EEPROM.

Page 102: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

102 ©1998 Sirius microSystemsMicrochip Code

A/D Converter Interrupt

The ADIF flag (ADCON0.1) is set when the A/D converter in the PIC16C711has finished its conversion. The A/D interrupt is gated by ADIE (INTCON.6). Al-though the A/D converter is quite fast, interrupt capability is provided so that thePIC can be put to sleep to minimize switching noise during conversion. See Chapter16 for more information on the A/D converter.

Interrupt Service Routines

Unlike a planned CALL, an interrupt can occur during the execution of any partof your program, totally disrupting your program’s normal execution. The job of anInterrupt Service Routine (ISR) is to transparently respond to the interrupt beforerestarting your program from where it was interrupted. The ISR does this by deter-mining the cause of the interrupt, doing some action related to the interrupt (servicingthe interrupt), and clearing the appropriate interrupt flag bit before exiting and re-turning control to your main code.

Although servicing the interrupt seems to be the primary task of the ISR, anequally important requirement is that the ISR leave the processor state unchanged.For example, the ISR code is just a new set of software commands that executewithin the processor after an interrupt. If, during the execution of the ISR, any proc-essor registers are modified by the ISR, their contents must be restored to pre-inter-rupt values before returning to your program. Otherwise, your program will notwork as expected after returning from the interrupt.

Saving and restoring registers without modifying their contents is not as straight-forward as it first seems. The W register contents must be saved first, as all otherregisters pass through W on the way to their temporary storage locations. But, sim-ply moving W to another register can corrupt the Z flag, modifying the STATUSregister, and potentially invalidating a math operation in progress before the inter-rupt. Microchip’s recommended code sequence provides a way to save and restoreregisters without modifying them. We’ll examine this code in detail in our examples.

First, let’s examine the pseudo-code of a typical interrupt serviced routine:

SaveStore W in temporary registerStore STATUS in temporary registerStore PORTB in temporary register if neededStore other registers if needed

Service_InterruptDetermine cause of interruptService interrupt

.

.Clear interrupt flag

RestoreRestore other registers if savedRestore PORTB if savedRestore STATUSRestore W

Return and enable interrupts

See 8.10, page 49 in thePIC16F8X data sheets formore information.

The interrupt automaticallyclears GIE, disablinginterrupts so that your ISRis not interrupted. RETFIEcombines a RETURN andBSF GIE.

Interrupt ServiceRoutines

Page 103: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

103Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

Using Interrupts to Wake-up on Key Press

KEY.ASM from Chapter 10 spent most of its time scanning the keypad waitingfor the user to press a key. Instead of constantly polling the keypad, KEYINT.ASMputs the PIC to ‘sleep’ and uses the Port B Change interrupt to wake the processorfrom ‘sleep’ whenever a key is pressed.

Although interrupt code is more complex than polling, it provides the followingadvantages:

• processor current is reduced from 8 mA during polling to less than 0.05 mAwhen asleep

• SLEEP can be replaced by other code routines, so the PIC doesn’t waste its timewaiting for a key press

Since KEYINT.ASM performs no processing other than executing the SLEEPinstruction, no registers need to be saved or restored during the interrupt serviceroutine.

Pull KEYINT.ASM from the Program References Section as we describe it.

The CLRF Key instruction presets the Key register with the no-key code. Thenext two CALLs initialize the LCD for later use. GOTO Initialize continues initiali-zation after the interrupt service routine with a call to DisplayInit.

The operation of DisplayInit is described in Chapter 10 in the description ofKEY.ASM. After returning from DisplayInit, Nap_Time is the next routine to beexecuted.

Rather than displaying ‘000’ during a no-key press, Nap_Time displays ‘ZZZ’to indicate that the PIC is going to sleep. CALL Init_Port_B configures Port B forkey scanning and enables the Port Change interrupt.

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear key storage registerCALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenGOTO Initialize ;Continue with initialize routine

Initialize CALL DisplayInit ;Display �Key Pressed:� on LCD

Nap_Time MOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to display data RAMMOVLW �Z� ;Load ASCII character ZCALL LCD_Data ;and send it to LCDMOVLW �Z� ;Re-load ASCII character ZCALL LCD_Data ;and send it to LCDMOVLW �Z� ;One more time!CALL LCD_Data ;and send it to LCD

CALL Init_Port_B ;Get Port B ready for interrupts

Page 104: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

104 ©1998 Sirius microSystemsMicrochip Code

Init_Port_B ;Sets Port B up for keypad scanning. RB0-3 are low outputs;and RB4-7 are inputs with pull-ups enabled. When a key;press occurs, one of the RB4-7 inputs goes low, generating;and interrupt.

CALL KB_Port ;Set Port B for keypad scanning

CLRF PORTB ;Make outputs lowMOVLW 08h ;Set only RB port change interruptMOVWF INTCON ;and write to interrupt registerRETFIE ;Return and enable interrupts

Init_Port_B first calls KB_Port to configure the Port B tristate registers andpull-up resistors for the keypad. CLRF PORTB clears the keypad output lines sothat a key press will generate a change on one of the Port B input lines. Remember,Port B inputs are pulled-up and normally read as a high. If the Port B outputs werealso high, pressing a key would not change the level on the input pins, consequentlynot generating a Port Change interrupt.

Moving 08h into INTCON sets only the Port B Change enable (RBIE, orINTCON.3). This allows the RBIF flag to be passed on to the GIE gate. Finally,RETFIE (RETurn From Interrupt, and Enable all interrupts) returns execution toMain and simultaneously enables all interrupts by setting GIE. RETFIE is usuallyalso the last instruction of any interrupt service routine.

After initialization, Main executes putting the PIC to sleep. Pressing a key on thekeypad will change the state of PortB.4-7 and generate both an interrupt and wake upfrom sleep signal. Normally an interrupt would cause the PIC to push the address ofthe NOP onto the Stack, but the SLEEP instruction pre-fetches the NOP and ex-ecutes it before the ISR, and leaves the address of GOTO Main on the stack.

ORG 04h ;Interrupt service routine starts

Check_RBIF ;When an interrupt occurs, Check_RBIF confirms it was;generated by RB Port Change. If not, and other interrupts;are enabled, they must get serviced in the Other_Int;routine. When a valid key arrives, it gets displayed,;then the port is re-configured for keypad input. Exiting;this interrupt service routine, re-enables interrupts.

BTFSS RBIF ;Check for RB port change interruptGOTO Other_Int ;If cleared, check other interruptsCALL Delay_5ms ;Wait key to settleCALL Delay_5ms ;10 ms should be enough timeCALL KB_Port ;Set up Port B for keypad scanningCALL KB_Scan ;Scan keys for key pressMOVF Key,0 ;Check Key register for 0 - no keyBTFSC Z ;by testing the Z flagGOTO Nap_Time ;If no key was returned, user let go

;so we display ZZZ to indicate sleep

CALL BIN_DEC ;If key returned, convert to decimal

CALL LCD_Port ;Set up ports for LCD outputMOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to display data RAM

Main SLEEP ;Shut down and wait for key pressNOPGOTO Main

Using Interrupts toWake-up on KeyPress

The NOP is often placedafter a SLEEP as theinstruction following aSLEEP is always executedupon wake-up. The CALLto the ISR occurs after theNOP has executed. (See8.12 on pg. 51 of thePIC16F8X data sheets)

Page 105: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

105Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

MOVLW 30h ;Load constant to convert to ASCIIADDWF Hundreds,1 ;and add to hundreds digit,ADDWF Tens,1 ;add to tens digitADDWF Ones,1 ;and add to ones digitMOVF Hundreds,0 ;Gets hundreds digit into W andCALL LCD_Data ;send it to LCDMOVF Tens,0 ;Get tens digit into W andCALL LCD_Data ;send it to LCDMOVF Ones,0 ;Get ones digit into W andCALL LCD_Data ;send it to LCD

CALL KB_Port ;Set up Port B for keypad scanningCLRF PORTB ;and get ready for Port B changeMOVF PORTB,0 ;Update Port B input latchesBCF RBIF ;Clear the Interrupt flagRETFIE ;and return

Other_Int RETFIE ;Return and enable global interrupts

This is the interrupt service routine for KEYINT.ASM. The ISR immediatelyservices the interrupt without saving the contents of any registers. In this case noother event could have caused the interrupt, but BTFSS RBIF is included to showhow you can check to see which event caused the interrupt. If RBIF is not set, youcan use GOTO Other_Int to poll INTCON, determine what caused the interrupt, andservice it appropriately. Here, Other_Int returns to the previously executing code andenables further interrupts via the RETFIE instruction because all other interrupts aredisabled.

After confirming that a port change caused the interrupt, CALL Delay_5ms isused twice to allow the keys to finish bouncing before they are scanned. CALLKB_Port and CALL KB_Scan configure Port B for keypad use and determine whichkey is being pressed. The variable Key contains the key return code and is placed intoW via the MOVF Key,0 instruction. When a key is being pressed, BTFSC Z willskip GOTO Nap_Time as the key return code is not zero. When the key is releasedthe key return code will be zero and GOTO Nap_Time will display the ‘ZZZ’ toindicate sleeping between key presses.

CALL BIN_DEC converts the value in W (key return code) from binary to BCDdigits which are stored in the Hundreds, Tens and Ones variables.

CALL LCD_Port is required because of the CALL KB_Port earlier. The LCDcursor is told to move to position 8D via the MOVLW 8Dh and CALL LCD_Reginstructions. 8Dh is the 14th position on line 1 of the LCD.

Adding 30h to the Hundreds, Tens and Ones variable converts them to ASCII,and then the MOVF and CALL LCD_Data instructions send the Hundreds, Tens andOnes digits to the LCD.

Next, CALL KB_Port configures Port B for keypad scanning, CLRF PORTBclears Port B outputs in preparation for the Port Change, and MOVF PORTB,0performs a Port B read. The read is necessary to update the Port B input latches.When interrupts are re-enabled, the Port B Change interrupt continuously comparesthe value of Port B to the value stored in the input latches. Reading Port B updatesthe input latches so that they reflect the key being held. When interrupts are re-enabled, the PIC won’t generate a new Port Change Interrupt until the key is re-leased.

This double-check ensuresthat nothing has corruptedthe INTCON register.

Actually, the PIC will gotosleep while the key is beingheld, but the LCD contin-ues to display the key codeat this time.

Page 106: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

106 ©1998 Sirius microSystemsMicrochip Code

Finally, BCF RBIF clears the Port B Change Interrupt flag just before RETFIEreturns to Main and re-enables interrupts. The interrupt flag should be cleared justbefore exiting the ISR. If the interrupt flag is cleared too early, an ISR operationcould set the flag, causing an interrupt to be re-triggered immediately after exitingthe ISR causing an endless interrupt loop.

In KEYINT.ASM, the Include directives are placed at the very end of the code.Since KEYINT.ASM uses interrupts, placing the Include directives at location0005h— as was done with KEY.ASM—would have written over the interrupt serv-ice routine beginning at location 0004h.

Managing Multiple Tasks using the TMR0 Interrupt

CLOCK.ASM demonstrates two tasks running concurrently. The program cy-cles a single LED across the LED bar graph and uses the TMR0 interrupt to keeptrack of how long the program has been running. This elapsed time is displayed onthe LCD. Before explaining the program code, let’s look at how CLOCK.ASM usesthe TMR0 register.

Timer 0 (TMR0) is set to count internal oscillator clocks by clearing T0CS. PSAis cleared so that the instruction cycle clock (Clock Out in the diagram) is divided bythe 8-bit prescaler. PS2, PS1 and PS0 are set to divide the input clock by 256. Theend result of this is that TMR0 increments at a rate of 9765.6 times per second (at a10 MHz clock oscillator frequency).

Let’s look at how this is calculated. A 10 MHz clock is divided by four internallyto generate the 2.5 MHz instruction cycle clock. Dividing the 2.5 MHz instructioncycle clock by a prescaler of 256 yields the 9765.6 Hz TMR0 clock.

TMR0 increments on every input clock. TMR0 generates an interrupt after 256counts. At the 9765.6 Hz rate, interrupts are generated at a rate of 38.15 Hz(9765.6÷256).

Often, TMR0 is modified to provide interrupts at a specific rate. CLOCK.ASMpre-loads TMR0 to 93 to provide an interrupt rate close to 60 Hz. By doing this,TMR0 increments from 93 to 256—instead of from 0 to 256—generating an over-flow after 163 counts (256-93). With an input clock rate of 9765.6 Hz to TMR0,interrupts will be generated at 59.91 Hz (9765.6÷163).

Include �BIN2DEC.LIB� ;Binary to Decimal conversion routinInclude �KEYPAD.LIB� ;Key pad scanning routinesInclude �LCD.LIB� ;LCD subroutine library

If you really wanted toplace the included files atthe top of the program, youcould either place a GOTOin location 0004h toredirect the interrupt to anew location, leaving theincludes at location 0005h,or you could just add theincludes between the ISRand main code—just don’tuse ORG to force theincludes to a specificaddress.

Clock Out (fosc/4)0

0

1

1

RA4/T0CKI

8-bit PrescalerT0SE

T0CS

PSA

T0IF

PS2 PS1 PS0

MUX M

UX

TMR0 Register

Managing MultipleTasks using theTMR0 Interrupt

See page 16 of thePIC16F8X data sheet forprescaler assignments.Note: The prescaler may beassigned to either TMR0 orWDT, but not both.

We chose 60 Hz becausethat is the North Americanpower line frequency,which just might be usefulfor other projects.

Page 107: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

107Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

Refer to CLOCK.ASM in the Program References Section as we describe itsoperation.

In the Equates section, these Temp_ registers are noteworthy because theCLOCK.ASM ISR saves and restores the contents of all the registers that it uses.

In the Initialize subroutine the Counter variables are cleared, and sixtieth is set to60 by the MOVLW 60 and MOVWF sixtieth instructions. The ISR decrements six-tieth to determine when one second has passed. CALLS to initialize the LCD anddisplay the text ‘Elapsed time:’ and ‘00:00:00’ on the LCD follow. The CALLTMR0_Init sets TMR0 to generate an interrupt 59.91 times per second.

TMR0 and the watchdog timer (WDT) share the prescaler. The CLRWDT in-struction is recommended by Microchip to ensure that a WDT time-out does notoccur while assigning the prescaler to TMR0.

Temp_W DS 1 ;Temporary registersTemp_Status DS 1 ;used to save values during interrupTemp_TRISB DS 1 ;service routine (ISR) The ISRTemp_TRISA DS 1 ;will save their values on entryTemp_PortB DS 1 ;and restore them on exit.Temp_PortA DS 1

TMR0_Init ;Assign prescaler to TMR0 and preload TMR0 for 60 Hz;interrupts.

CLRWDT ;Clear WDT and prescalerBSF RP0 ;Select register page 1MOVF OPTION,0 ;Load W with current OPTION reg.ANDLW 11000111b ;Clear T0CS, T0SE and PSA bits

;T0CS=OPTION.5, Counter select;0=Timer mode, 1=Counter mode;T0SE=OPTION.4, Source Edge select;0=Rising edge, 1=Falling edge;PSA=OPTION.3, Prescaler Assignment;0=TMR0, 1=WDT

IORLW 00000111b ;Set PS2, PS1 and PS0;000=/2, 001=/4, ...111=/256

MOVWF OPTION ;Set OPTION register with new valueBCF RP0 ;Return to register page 0

MOVLW 93 ;Load W with 93 because incrementingMOVWF TMR0 ;TMR0 from 93-256 takes 1/60s

MOVLW 20h ;Enable only the TMR0 interruptMOVWF INTCON ;and write to INTCON

RETFIE ;Return and enable global interrupts

MOVLW 60 ;Preload sixtiethsMOVWF sixtieth ;with 60

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Init ;Display �Elapsed time:� on line 1CALL Disp_Time ;Display time on line 2

CALL TMR0_Init ;Initialize Real Time Clock Counter;Timer 0 (TMR0) and enable interrupt

We know that servicing theTMR0 interrupt will disruptthe LED cycling on Port B.All of the Port B registersmust be saved, and laterrestored.

Page 108: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

108 ©1998 Sirius microSystemsMicrochip Code

Unlike KEYINT.ASM where the registers are loaded with an absolute value,CLOCK.ASM loads the current state of OPTION into W and modifies only therequired bits, leaving the others unchanged. The MOVF OPTION,0 loads OPTIONinto W and the ANDLW 11000111b clear the bits 4, 5 and 6 of OPTION leaving theremaining bits unchanged. IORLW 00000111b sets bits 0, 1 and 2 in OPTION leav-ing the remaining bits unchanged. MOVWF OPTION stores W into the OPTIONregister.

MOVLW 93 and MOVWF TMR0 pre-loads TMR0 with the preset value 93. 93will cause TMR0 to generate interrupts 59.91 times per second as described earlier.INTCON is loaded with 20h so that only the TMR0 interrupt is enabled.

RETFIE ends the TMR0_Init initialization routine. It enables interrupts and re-turns to Initialize.

Here, Port B is set for output and begins to cycle the LED. The scan rate of theLED is determined by the nested loop. At this point interrupts have been enabled andwhen TMR0 overflows (~16.7 ms later) the ISR takes control of the PIC.

The technique makes thecode more portable. Thatis, it can be used in otherprograms with little or nomodification.

BSF RP0 ;Select Register Page 1CLRF TRISB ;Make Port B outputBCF RP0 ;Back to Register Page 0

MOVLW 01h ;Light up the first LEDMOVWF PORTB ;on Port BBCF C ;Clear the Carry

Main ;This code runs when the Interrupt service routine isn�t;running and cycles a single LED across the display.

:Loop DECFSZ Counter3,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter4,1 ;Decrement, second counterGOTO :Loop ;from constant, above

RLF PORTB ;Rotate PORTB to the leftGOTO Main ;Do it again and again and ...

It takes ~80 ms to completethe delay loop for the LED.Four interrupts will haveoccurred and been servicedbefore the LED moves tothe next position! Check_T0IF ;When an interrupt occurs, Check_T0IF confirms it was

;generated by a TMR0 overflow. If not, and other interrupts;are enabled, they must get serviced in the Other_Int;routine. When TMR0 overflows sixtieth is decremented and;checked for equalling zero. If Zero then Seconds, Minutes;and Hours are updated and displayed. Otherwise, interrupts;are re-enabled and execution continues.

Save MOVWF Temp_W ;Save W in Temp_WSWAPF Status,0 ;Swap Status halves into WMOVWF Temp_Status ;and save Status in Temp_Status

MOVF PORTA,0 ;Load W with Port and TRIS contentsMOVWF Temp_PortA ;and save to temporary registersMOVF PORTB,0MOVWF Temp_PortBBSF RP0MOVF TRISA,0MOVWF Temp_TRISAMOVF TRISB,0MOVWF Temp_TRISBBCF RP0

Managing MultipleTasks using theTMR0 Interrupt

Page 109: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

109Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

The Save routine must be the first part of the ISR to execute. As mentionedearlier, W and the STATUS registers must be saved without altering their contents.MOVWF Temp_W stores the contents of W into one of the previously definedstorage registers. SWAPF STATUS,0 (SWAP nybbles of File register, store resultin W) copies the contents of the STATUS register into W with upper and lowernybbles exchanged. SWAPF is used because a MOVF modifies Z which is one ofthe STATUS register bits. With STATUS now in W, albeit with reversed nybbles, itis moved to a temporary storage register by MOVWF Temp_Status.

The subsequent series of MOVF and MOVWF instructions save the contentsof the PORT and TRIS registers. With all of the important registers now saved, theISR can service the interrupt.

The BTFSS T0IF and GOTO Other_Int form the structure needed to testINTCON and select the appropriate interrupt to service. In this case, only the TMR0interrupt is enabled, but this type of check can used to identify the cause of aninterrupt if more than one is enabled.

DECFSZ sixtieth determines if 60 interrupts have occurred and exits the ISR ifnot. After 60 interrupts, the elapsed time on the clock is updated.

The time is updated by first incrementing Seconds, and checking for an over-flow to 60. If an overflow occurs, Minutes is incremented, again checking for anoverflow to 60. If an overflow occurs, Hours is incremented. Hours is checked foran overflow to 24. If Hours overflows, the Hours, Minutes and Seconds are all resetto zero. Finally, the calls in Update_Clock display the updated time on the LCD.

ISR BTFSS T0IF ;Check for TMR0 interruptGOTO Other_Int ;If cleared, check other interrupts

DECFSZ sixtieth ;Has 1 second elapsed?GOTO Exit ;If not, use Exit to leave ISRMOVLW 60 ;If zero, reset sixtieth counterMOVWF sixtieth ;to 60INCF Seconds ;Update seconds andSUBWF Seconds,0 ;check for overflow (Seconds=60)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLRF Seconds ;If Z=1, Seconds is 60, reset to 0MOVLW 60 ;reload W with 60INCF Minutes ;Update Minutes andSUBWF Minutes,0 ;check for overflow (Minutes=60)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLRF Minutes ;If Z=1, Minutes is 60, reset to 0MOVLW 24 ;Load W with 24INCF Hours ;Update Hours andSUBWF Hours,0 ;check for overflow (Hours=24)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLRF Hours ;If Z=1, reset hours to 00

Update_Clock CALL LCD_Port ;Reconfigure Ports for LCD andCALL Disp_Time ;display the new time

Page 110: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

110 ©1998 Sirius microSystemsMicrochip Code

To end the interrupt, Exit reloads TMR0 with the 1/60th second delay value andclears the T0IF flag.

The Restore subroutine restores the contents of the Port and Tris registers to thevalues they contained before the interrupt.

SWAPF Temp_Status,0 moves the saved STATUS register (with its nybbles re-versed) into W in its correct order. The MOVWF STATUS instruction copies W—containing the saved Status—back to the STATUS register. MOVWF does not affectany of the STATUS register flags.

Finally, W must be restored. Since MOVF cannot be used since it can affect theSTATUS register flags, two SWAPFs are used to restore W. SWAPF Temp_W,1reverses the order of the nybbles in Temp_W, leaving the result in Temp_W. Thismust be done because the W register itself cannot be swapped. The next SWAPFTemp_W,0 swaps the nybbles back to their original form and leaves the result in W.

Once all of the registers have been restored, RETFIE returns execution to Mainwhere the LED scanning continues.

CLOCK.ASM demonstrates how easily the PIC can accomplish two tasks at thesame time. What is not as apparent, however, is exactly how much unused processortime is available for use by other tasks. Updating the clock uses less than 1% of theprocessor’s time! By exploiting interrupts, you can cram a lot of functionality into asimple microcontroller.

Exit ;Reloads TMR0 so the next 60th second time-out can generate;an interrupt and restores all registers.

MOVLW 93 ;Preload W for 60 Hz delayMOVWF TMR0 ;and save to TMR0BCF T0IF ;Clear TMR0 interrupt flag and

Restore MOVF Temp_PortA,0 ;Restore registers from temporaryMOVWF PORTA ;registersMOVF Temp_PortB,0MOVWF PORTBBSF RP0MOVF Temp_TRISA,0MOVWF TRISAMOVF Temp_TRISB,0MOVWF TRISBBCF RP0

SWAPF Temp_Status,0 ;Swap Status halves to WMOVWF Status ;and return Status to pre-interrupt

;valueSWAPF Temp_W,1 ;Swap halves of Temp_WSwAPF Temp_W,0 ;Swap Temp_W back to W

RETFIE ;Return and enable interrupts

Other_Int ;Insert other interrupt checks here

RETFIE ;Return and enable global interrupts

Managing MultipleTasks using theTMR0 Interrupt

Page 111: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

111Chapter 11Interrupts©1998 Sirius microSystems Microchip Code

Chapter Summary

Interrupts are used to place one program subroutine on hold while anotherprogram subroutine automatically responds to the hardware event that caused theinterrupt. The PIC16F84 can be interrupted by Timer 0 overflows, transitions ofthe INT pin, changes on PortB.4-7, and completed EEPROM writes. The PIC16C711includes the same interrupt sources except that the EEPROM write complete inter-rupt is replaced with an A/D conversion complete interrupt.

The INTCON and OPTION registers control most interrupt functions. All in-terrupts have an interrupt enable and an associated interrupt flag. The enable bitdoes not suppress the generation of the flag, but only the generation of an interrupt.All interrupts are gated with the Global Interrupt Enable bit (GIE).

Interrupts cause the execution of the instruction at location 0004h—the Inter-rupt Vector. An interrupt service routine located here must:

• save all registers they modify

• determine the cause of the interrupt and service it

• clear the interrupt flag

• restore all registers to their original values

Interrupts can be used to wake the processor from sleep (reducing power con-sumption), manage multiple concurrent tasks, and allow the PIC to respond to un-predictable events as they occur.

No matter how complex the interrupt code became, Phil wasalways impressed by how quickly Spike could locate the errors.

Page 112: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

112 ©1998 Sirius microSystemsMicrochip Code

Questions

1. Describe how interrupt-driven input differs from polling an input for a change.

2. What are the four interrupt sources for the PIC16F84?

3. List the pseudo-code steps to enable the INT interrupt for a falling-edge inputon RB.0.

4. How does the GIE bit affect a wake-up from a SLEEP? Refer to the interruptlogic diagram and the Microchip data sheets.

5. Explain why it is important to update the Port B input latches before enablingthe Port B change interrupt.

6. How much error does the displayed time in CLOCK.ASM have due to soft-ware? How can it be made more accurate?

Assignment

1. Write the pseudo-code for a program which incorporates interrupts and flashesan LED at a set rate. When a button on the keypad is pressed the flashing rateshould change to a new rate determined by the number of the key pressed.Include the pseudo-code for the ISR.

2. Write the program outlined in 1.

3. Write the pseudo-code for a program which uses TMR0 to generate an inter-rupt after 10 ms have elapsed.

4. Write the pseudo-code for a program which uses a transition from high to lowon the INT (PORTB.0) pin to display the text ‘INT pin interrupt’ on the LCDdisplay. Otherwise, the LCD should be cleared and a single LED should bescanning across the bar graph display from PORTB.1 to PORTB.7 (PORTB.0will be needed to generate the interrupt).

5. Write the pseudo-code for a program which accepts a 60 Hz input clock onPORTA.4 and displays the elapsed time on the LCD in hours, minutes, sec-onds, and tenths of seconds. When a key is pressed, generate a Port B changeinterrupt. The ISR should determine which event caused the interrupt. If TMR0generated the interrupt, the elapsed time routine should be serviced. If a keypress caused the interrupts, they key pressed should either increment or decre-ment the hours, minutes, seconds, or tenths of seconds variables.

6. Write the programs outlined in 4 and 5.

Questions andAssignments

Page 113: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

113Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

12 Using theLCD Display

The PIC-MDS includes an intelligent 2-line by 16-character LCD display. Intel-ligence is provided by an on-board controller chip based on the Hitachi HD44780—a common LCD controller. The LCD controller:

• displays ASCII characters as well as some Kanji and Greek characters

• can shift characters left or right on the display

• provides absolute and relative character position addressing

• has a 40 character memory for each line of the display

• supports cursor movement and appearance

• allows 8 custom characters to be programmed

• can be connected to a microcontroller using a 4-bit or 8-bit interface

Adding LCD capability to your projects is remarkably easy, once you know howto communicate with the LCD controller. This chapter will give two examples ofusing the LCD. The first program displays the ASCII character entered using thekeypad and demonstrates character positioning. The second uses custom charactersto demonstrate cursor cell animation and display scrolling.

Before we examine the code, we need to understand how the LCD is connected tothe microcontroller and the function of the internal LCD registers.

The LCD Interface

In the PIC-MDS, the LCD display is connected to both Port A and Port B of themicrocontroller (refer to the schematic segment on the next page). Port A is used toactivate the LCD control lines, and Port B connects to the LCD data lines.

As you look at the schematic, notice that the LCD data lines are shared with thekeypad (and with the LED’s—see Chapter 4). Sharing Port B like this takes advan-tage of the PIC’s ability to easily and rapidly reconfigure ports. KEY.ASM,KEYINT.ASM and CLOCK.ASM have all used Port B for more than one function.

LCD displays using theHD44780 controller and itsderivatives are widelyavailable. The techniquesused in this chapter applyto any LCD using thiscontroller family.

Page 114: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

114 ©1998 Sirius microSystemsMicrochip Code

A section of the PIC-MDS schematic showing the LCD and Keypad connections to the PIC microcontroller.

RS DB0

1000000000

•100000000

0Inc.

Inc. - Increment or decrement cursor position. 1=increment, 0=decrement

10000000

Blink

Blink - Cursor blink. 1=blinking, 0=underscore

Curs.

Curs. - Cursor On/Off control. 1=on, 0=off

Disp.

Disp. - Display On/Off control. 1=on, 0=off

1000000

••R/L

R/L - Right/left shift direction. 1=shift right, 0=shift left

D/C

D/C - Shift display or cursor. 1=shift display, 0=shift cursor

100000

••Font

Font - Font select. 1=5X10 dots, 0=5X7 dots

MSB

MSB

MSB

MSB

MSB

LSB

LSB

LSB

LSB

LSB

Lines

Lines - Number of display lines. 1=2 lines, 0=1 line

Data

Data - Interface data bus width. 1=8 bits, 0=4 bits

CGRAM Address

DDRAM Address

RAM Address

RAM Data

RAM Data

10000

1000

100

0 1 Busy

Busy•

- Busy Flag. 1=busy, 0=ready

- Not used.

1 0

1 1

Clears display and sends

Returns cursor to home

Sets cursor and display

Sets cursor increment/dec-

Sets data width, number of

Display and cursor on/off

Sets character generator

Sets display data RAM

Reads LCD Busy Flag

Writes data to RAM

Reads data from RAM

cursor to home position.

position, leaving characters.

shift direction.

rement mode.

lines and character font.

control, and cursor blink.

RAM (CGRAM) address.

(DDRAM) address.

DB1DB2DB3DB4DB5DB6DB7R/WCOMMAND DESCRIPTION

Clear Display

Return Home

Entry Mode

Display Cont.

Shift Mode

Function Mode

CGRAM Addr.

DDRAM Addr.

Read Busy

RAM Write

RAM Read

LCD Controller Commands

This chart summarizes the LCD controller commands used by LCD.LIB, the LCD subroutine library.

The LCD Interface

Page 115: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

115Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

Port A connects to the LCD control lines is as follows:

PORTA.2 LCD Enable (LCDE in LCD.LIB)PORTA.0 LCD Register Select (RS in the chart, and LCDRS in LCD.LIB)PORTA.1 LCD Read/Write (R/W in the chart, and LCDRW in LCD.LIB)

LCD Enable

LCD Enable is an active-high input on the LCD. When low, the LCD is disabledand all other LCD I/O lines are in the high impedance state—effectively disconnect-ing the LCD display from the PIC. The LCD Enable line must be pulsed high in orderto write or read commands or data to the LCD. The duration of this pulse must be atleast 500 ns. The LCD_Enable routine in LCD.LIB pulses the enable line.

LCD Register Select

RS on the LCD selects either command mode (when RS=0) or character read/write mode (when RS=1). CALL LCD_Reg is used to write commands to LCDregisters. The CALL LCD_Reg subroutine in LCD.LIB ensures that RS is low be-fore pulsing the enable line. Similarly, CALL LCD_Data is used to write charactersto the LCD. The CALL LCD_Data subroutine in LCD.LIB sets RS high beforepulsing the enable line.

LCD Read/Write

The R/W line determines whether a read or write to the LCD takes place. If R/Wis high (R/W=1) the contents of LCD RAM will be read and if R/W is low (R/W =0)the LCD RAM will be written. The R/W line along with the RS line must be set priorto issuing the enable pulse.

LCD Commands

LCD.LIB has predefined command equates, shown below. These equates arederived from the LCD Controller Commands table at left. To send a command to theLCD, load W with the command equate and CALL LCD_Reg. LCD_Reg controlsthe RS and R/W lines, and pulses the enable to complete the command.

LCD.LIB is the subroutinelibrary that controls theLCD. Its use is describedlater in this chapter.

Page 116: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

116 ©1998 Sirius microSystemsMicrochip Code

LCD_Init ;LCD initialization instructions from the Optrex data book.;Sets LCD functions for DMC16207 display, performs soft-;ware reset, clears memory and turns the display on.

MOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCDCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDFunction ;Load W with initialize 8-bit codeCALL LCD_Reg ;and send it to LCDCALL Delay_5ms ;...and wait

LCD Initialization

Before the LCD can be used, the LCD controller (the HD44780 on the LCD)must be initialized for the correct display format. We’ll configure the display on thePIC-MDS to use 8-bit data, two display lines, and a 5X7 character matrix. TheLCDFunction equate of 38h configures the LCD for these settings. This value isderived from the LCD Controller Commands chart, under the Function Mode com-mand.

Initialization must follow a specific order, which is shown below in pseudo-code.Calling LCD_Init in LCD.LIB does this for you.

LCD_InitSend LCDFunction data (38h) to LCDpulse the LCD enable linewait 5 ms

Send LCDFunction data (38h) to LCDpulse the LCD enable linewait 5 ms

Send LCDFunction data (38h) to LCDpulse the LCD enable linewait 5 ms

Send LCDFunction data (38h) to LCDpulse the LCD enable linewait 5 ms

Send LCDOn data (C0h) to LCDpulse the LCD enable line

Send LCDCLR data (01h) to LCDpulse the LCD enable line

Send LCDInc data (06h) to LCDPulse the LCD enable line

Return

The first part of the LCD_Init subroutine is shown below:

If you use other types ofLCD displays based on theHD 44780 controller, or ifyou want to use the LCD in4-bit mode, you will needto modify the LCDFunctionequate. Refer to theLCD4BIT.LIB library filefor details.

LCD Initialization

The LCD controller is resetin software by threesuccessive writes of 38h.The LCD controller shouldautomatically be reset onpower-up. We’ve includedthe software reset just incase the power supply risetime does not meet thecontroller reset require-ments.

The fourth 38h sets theLCD function register. Thenext three writes turn onthe LCD display, clear thedisplay, and set the cursorinto increment mode. TheLCD is now ready for use.

From LCD.LIB

We will represent calledlibrary routines as greyed-out text to indicate that thecode can be found in‘.LIB’ files.

Page 117: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

117Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

You may have noticed two major differences when comparing the library codewith the pseudo-code. First, the LCDInit constant is actually the same as theLCDFunction constant. They have been equated separately so that the LCDFunctionconstant can be changed for other display types without changing the initializationcode.

Next, two slightly different routines, LCD_Reg and LCD_Reg_Init, are used topulse the enable line of the LCD controller after writing the LCD command. LCD_Regchecks the LCD controller’s busy flag before enabling the command write and can-not be used during initialization. LCD_Reg_Init ignores the state of the LCD busyflag during a software reset, blindly performing writes. After 5ms, the LCD control-ler is ready to receive the next initialization command.

LCD Display Addressing

Each line of the LCD display has forty characters of Display Data RAM(DDRAM) associated with it. The forty RAM locations are organized as a circularbuffer so that the last location wraps around and ends up beside the first. Of theseforty characters, sixteen are visible in the display window.

After the LCD is initialized by calling LCD_Init, the first character that is writ-ten to the LCD is placed into DDRAM at location 80h.

After writing one character, the DDRAM address increments to 81h automati-cally, since LCD_Init sets Entry Mode to increment. Subsequent characters fill suc-cessive locations up to A7h (the 40th position) and eventually wrap around to C0h onthe second line. Remember that display locations past 8Fh are not visible on a sixteencharacter display. To make these characters visible, the display contents can be shiftedleft or right. Moving the equates LCDLeft or LCDRight into W and issuing a CALLto LCD_Reg shifts the display one position left or right. The diagram on the nextpage illustrates the result of a display shift to the left.

;Change the constant in the next line to set how the displa;is activated. eg. LCDOn, CursOn, CursBlink. The Constant i;from the LCD software commands, above.

MOVLW LCDOn ;Command for display on & cursor of

CALL LCD_Reg ;Send it to LCDMOVLW LCDCLR ;Load W with clear LCD codeCALL LCD_Reg ;and send it to LCDMOVLW LCDInc ;Load W with increment mode codeCALL LCD_Reg ;and send it to LCDRETURN

LCD Character Position (DDRAM Address)7 156 145 134

Visible Display Window

123 112 101 98 16 174039 18

Sixteen characters arevisible in a 2X16 display. Ifwe had a 2X20 display, thefirst 20 characters(DDRAM addresses 80h to93h) would be visible.Larger displays use thesame DDRAM addresses.

Page 118: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

118 ©1998 Sirius microSystemsMicrochip Code

Notice that the display shift commands shift both lines of the LCD display in thespecified direction.

Absolute Addressing

Characters can be written to specific LCD locations (DDRAM Addresses) usingthe DDRAM Address command. The LCDLine1 and LCDLine2 equates incorporatethe DDRAM Address command. The default position of LCDLine1 and LCDLine2is at the beginning of DDRAM.

By adding an offset value of between 00h and 27h to the LCDLine1 and LCDLine2equates, characters can be placed anywhere in DDRAM. For example, to display acharacter at the very last position on line 2 of the LCD, you would move the equateLCDLine2 to W, add 0Fh to W, and then issue a call to LCD_Reg.

Relative Addressing

Movements can be made to the left or right of the current cursor position usingthe CURSLeft and CURSRight commands. Cursor refers to the current DDRAMlocation, and can be indicated on the LCD by an underscore ‘_’ or a blinking block ifthe cursor is on. Sending the CURSOn command displays the cursor as an under-score, and sending CURSBlink activates the blinking cursor.

Cursor movement occurs regardless of whether the cursor is on, off or blinking.Each time the CURSLeft or CURSRight command is sent, the cursor moves oneposition to the left or right.

Displaying LCD Characters

The program ASCII.ASM displays the LCD character corresponding to a threedigit value (0-255) entered from the keypad. ASCII.ASM demonstrates LCD initiali-zation, LCD command writes, LCD character writes, absolute cursor positioningand the auto cursor increment mode.

ASCII.ASM can be used to view all of the characters the LCD is able to display.Codes 032-127 display the standard ASCII character set, and codes from 128-255show some Kanji, Greek, accents and other characters. Codes 0-7 display customcharacters, codes 8-15 repeat the custom characters, and codes 16-31 are blank.

Pull ASCII.ASM from the Pull-out Program References section as we dissect it.

Displaying LCDCharacters

A more efficient method ofdoing this is moving thecharacter position—in thiscase CFh—directly to Wbefore CALLing LCD_Reg.

Assemble and downloadASCII.HEX to aPIC16F84. Characterswill not display until allthree digits have beenentered.

LCD Character Position (DDRAM Address)7 156 145 134

Visible Display Window after Display Shift

123 112 101 98 16 1740 1918

Page 119: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

119Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

Let’s begin by examining the Equates section. Hundreds, Tens, and Ones storethe three digits that make up the character code. They also happen to be the variablenames required by DEC2BIN.LIB. The subroutine Dec_Bin, in DEC2BIN.LIB, con-verts the three decimal digits in Hundreds, Tens, and Ones to an equivalent binarynumber.

Counter1 and 2 variables are used by the LCD Delay_5ms subroutine. Counteris used to read a data table containing text for line 1. Key is used to hold the keyreturn code after a scan of the keypad. ASCII.ASM remaps the value in key so thatonly the digits 0-9 are entered from the keypad. Digit keeps track of how many digitsof the code have been entered.

After clearing some of the variables, GOTO Initialize jumps over the includedsubroutines. Initialize continues with CLRF Digit.

The LCD_Port and LCD_Init subroutines are parts of LCD.LIB. LCD_Portconfigures Ports A and B for use with the LCD. As seen earlier, LCD_Init initializesthe LCD (by sending the LCDFunction as outlined by the LCD_Init pseudo-code),clears the display, resets the cursor to the home position (position 1 of line 1), andsets cursor increment mode. Let’s take a closer look at LCD_Port.

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Other equatesCounter DS 1 ;LCD character counter

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

Key DS 1 ;Key return code variable

Digit DS 1 ;ASCII digit counter variable

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key return variableCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �DEC2BIN.LIB� ;Decimal to Binary conversion routinInclude �KEYPAD.LIB� ;Keypad scanning subroutine libraryInclude �LCD.LIB� ;LCD subroutine library

Initialize ;This subroutine initializes the LCD display and writes;a message on to line 1 and �=� on to line 2. The cursor;is turned on to indicate where input will be shown.

CLRF Digit ;Clear digit counterCALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Init ;Send first line

Page 120: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

120 ©1998 Sirius microSystemsMicrochip CodeDisplaying LCDCharacters

LCD_Port sets the lower three pins of Port A as outputs. ANDing the literal intoTRISA does this without disturbing the upper two pins of Port A. All of Port B isused as outputs to send data and commands to the LCD. (Remember, a call toLCD_Init, which we’ve already described, follows LCD_Port.)

Call Disp_Init, the last Initialize command, can now display the text ‘ASCIICode=Char.’ on the first line of the LCD.

The Disp_Init subroutine is basically the same as Get_Char in Key.ASM (seeChapter 10 for a more detailed explanation). The Counter variable points to theposition of the character in the Message data table. Each time the loop calls Message,Counter offsets the Program Counter to retrieve the next character from the table.

LCD_Port ;Initializes the Port B tristate buffers as outputs for;LCD data lines. Sets Port A to digital (on PIC16C71) and;sets the LCD Register Select, Read/~Write, and Enable;lines to outputs.

BSF RP0 ;Select memory register page 1

;the next two lines are for the PIC16C711 only and should b;removed for the PIC16F84 (PM produces an error when this;is assembled for the �84).

;MOVLW 03h ;1�s set Port A to digital;MOVWF ADCON1 ;Write W to ADCON1 (88h)

MOVLW 11111000b ;Set lower 3 bits of RA toANDWF TRISA ;digital output in TRISACLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0BCF LCDE ;Keep LCD Enable line offRETURN ;Ports are now set up for LCDFrom LCD.LIB

If you use LCD.LIB withthe PIC16C711, remove thesemicolons from thecommented-out code. The‘711 powers up with Port Ain analog mode. Beforeusing the LCD, Port A mustbe configured for digitaloutput.

Disp_Init ;Writes �ASCII Code=Char.� to the first line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counterGet_Char MOVF Counter,0 ;Get character offset into W

CALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use ORBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for the next character

Message ADDWF PCL ;Offset program counter by adding WRETLW �A� ;MessageRETLW �S�RETLW �C�RETLW �I�RETLW �I�RETLW � �RETLW �C�RETLW �o�RETLW �d�RETLW �e�RETLW �=�RETLW �C�RETLW �h�RETLW �a�RETLW �r�RETLW �.�RETLW 0 ;End of message

Page 121: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

121Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

RETLW returns the numeric value for the character in quotation marks in W. TheCALL LCD_Data instruction writes the character value in W to the current positionof the LCD DDRAM.

LCD characters are written to the display by placing the ASCII value on Port B,setting the LCDRS line, and pulsing the LCD enable line. Before writing a newcharacter, the LCD must have finished the last operation. CALL LCD_Check moni-tors the busy flag and returns when the LCD is not busy.

After the CALL to LCD_Data writes the character, Counter increments. If thereturned character is zero, BTFSC Z does not skip to CALL LCD_Data, but insteadreturns to the calling subroutine.

Using the technique of marking the end of the message with a specific charac-ter—zero in this case—allows this subroutine to be used for messages of varyinglengths. Zero is a good character to use as a marker since it sets the Z flag. Unfortu-nately, RETLW does not affect any flags. Thus, the returned character is first OR’edwith 00h because IORLW will set flags.

The Send_Equals routine positions an equals sign at line two, position eleven.Loading LCDLine2 loads the first DDRAM address of line two into W. Adding 0Ahto W increases the DDRAM address in W by 10. The call to LCD_Reg moves thecursor to DDRAM position CAh, the 11th position on the LCD.

LCD commands are written to the LCD by placing the command word on PortB, clearing the LCDRS line, and pulsing the LCD enable line. Once again, CALLLCD_Check ensures that the LCD has completed its last operation by checking thebusy flag.

Send_Equals finishes by loading W with the code for ‘=’ and the call to LCD_Datawrites this code to the current DDRAM address.

LCD_Data ;Load W with the ASCII character code to send to LCD.;LCD_Data outputs the character to the LCD and blips;the enable line with LCD_Enable to complete the send.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD on Port BCALL LCD_Check ;Check LCD busy flagBSF LCDRS ;Enter ASCII modeGOTO LCD_Enable ;Send ASCII character From LCD.LIB

For more detail, examinethe LCD.LIB file.

Send_Equals MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 0Ah ;and offset cursor to position 11CALL LCD_REG ;Send cursor position to LCDMOVLW �=� ;Load W with ASCII �=�CALL LCD_Data ;and send to LCD for display

LCD_Reg ;Load W with LCD software constant from table, above.;LCD_Reg outputs the command to the LCD and blips the;enable line with LCD_Enable to complete the command.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD reg. on Port BCALL LCD_Check ;Check LCD busy flagGOTO LCD_Enable ;Send register command

You can’t use the name‘Send=’ as a label, since‘=’ means EQUate.

From LCD.LIB

Page 122: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

122 ©1998 Sirius microSystemsMicrochip Code

Set_Cursor moves the current DDRAM address to position 7 of line 2 in thesame way the ‘=’ sign DDRAM address was set.

Cursor_On turns on the underscore cursor by loading the CursOn equate into Wand sending it to the LCD through the call to LCD_Reg. An underscore cursor is thedefault cursor used by LCD.LIB. To use the blinking cursor, replace CursOn withthe equate CursBlink.

After setting up the LCD, KB_Port is called to reconfigure the I/O ports for thekeypad.

The Main program routine retrieves and debounces keystrokes. The call toKB_Scan returns a value in Key. If Key equals zero, no key has been pressed, andGOTO Get_Key executes forming a wait loop.

Once a key has been pressed, Get_Key calls Delay_5ms four times to provide a20 ms debounce delay. LCD.LIB requires a 5 ms delay routine called Delay_5msanyway, and calling it four times provides 20 ms for the key switch contacts to settle.After the delay, KB_Scan is called again to obtain the now stable key return code.The Key code is loaded into W for remapping by the Key_Remap subroutine.

The reason for remapping the keypad is that a zero key value is needed. Keys areeasily remapped using a ROM data table. Remapping also eliminates key boundary

Displaying LCDCharacters

Set_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 06h ;and offset cursor to position 7

CALL LCD_REG ;Send cursor position to LCD

Cursor_On MOVLW CursOn ;Load W with cursor on command (0Eh)CALL LCD_REG ;and send to LCD

CALL KB_Port ;Configures Port B for keypad

; Old key from KB_Scan gets remapped to new key values:; +----+----+----+----+ +----+----+----+----+; | 1 | 2 | 3 | 4 | | 1 | 2 | 3 | 0 |; +----+----+----+----+ +----+----+----+----+; | 5 | 6 | 7 | 8 | | 4 | 5 | 6 | 0 |; +----+----+----+----+ ----> +----+----+----+----+; | 9 | 10 | 11 | 12 | | 7 | 8 | 9 | 0 |; +----+----+----+----+ +----+----+----+----+; | 13 | 14 | 15 | 16 | | 0 | 0 | 0 | 0 |; +----+----+----+----+ +----+----+----+----+

Get_Key CALL KB_Scan ;Get Key return codeMOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try again

CALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

CALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Key_Remap ;and Remap key codesMOVWF Key ;Save new Key code to key

Remember, KEYPAD.LIBprovides key codes from 1to 16, and a key code of 0indicates that no keys arepressed.

Page 123: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

123Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

checking in the program. The key values returned from the Key_Remap routine canbe directly input into the Hundreds, Tens and Ones variables without modification.

The Key_Remap data table works similarly to the Message data table. Note theNOP as the first entry. Even though a zero key value would never be passed toKey_Remap, we must account for a zero offset here so that the other Key valuesremap properly.

When the first key is returned, Digit contains the value zero. The Digit value isloaded into W for use in a jump table. A jump table is similar to a data table exceptthat instead of returning a value, it executes a GOTO based on the value in W. SinceW is zero the first time this table executes, the PIC will be redirected to the Digit1subroutine by the first GOTO.

Digit1 and Digit2 are similar in function. They reconfigure the PIC I/O ports forthe LCD, retrieve the Key value in order to save it in Hundred or Tens, and changethe Key value to its ASCII equivalent by adding 30h to it. CALL LCD_Data thendisplays this ASCII digit and moves the cursor to the next DDRAM address. Afterincrementing the Digit counter, GOTO Release waits for the key to be released.

Key_Remap ADDWF PCL ;Use old Key to offset PCNOP ;No Key=0 codeRETLW 1 ;old key 1 remapped to new key 1RETLW 2 ;old key 2 remapped to new key 2RETLW 3 ;old key 3 remapped to new key 3RETLW 0 ;old key 4 remapped to new key 0RETLW 4 ;old key 5 remapped to new key 4RETLW 5 ;old key 6 remapped to new key 5RETLW 6 ;old key 7 remapped to new key 6RETLW 0 ;old key 8 remapped to new key 0RETLW 7 ;old key 9 remapped to new key 7RETLW 8 ;old key 10 remapped to new key 8RETLW 9 ;old key 11 remapped to new key 9RETLW 0 ;old key 12 remapped to new key 0RETLW 0 ;old key 13 remapped to new key 0RETLW 0 ;old key 14 remapped to new key 0RETLW 0 ;old key 15 remapped to new key 0RETLW 0 ;old key 16 remapped to new key 0

MOVF Digit,0 ;Get digit count in WADDWF PCL ;and offset PC with digitGOTO Digit1 ;First time through, write HundredsGOTO Digit2 ;next, TensGOTO Digit3 ;then, Ones

This jump table is similarto the Case command insome programming lan-guages.

Digit1 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Hundreds ;and store in Hundreds variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCDINCF Digit ;Add one to digit counterGOTO Release ;Wait for user to release key

Digit2 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Tens ;and store in Tens variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCDINCF Digit ;Add one to digit counterGOTO Release ;Wait for user to release key

The NOP instruction isoccupies the memorylocation that represents theresult of adding 0 (from W)to PCL. Since W will be avalue from 1 to 16, theNOP is needed to offset thedata table.

Page 124: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

124 ©1998 Sirius microSystemsMicrochip Code

The Release subroutine reconfigures the I/O ports for keypad scanning beforeperforming a key scan. While a key is being pressed, the GOTO Wait line executes.When the key is released, another 20 ms debounce delay occurs. Without this delay,a key bounce on release would be interpreted as the next keystroke entered by theprogram.

Now that the first digit has been retrieved, stored in the Hundreds variable, anddisplayed on the LCD, GOTO Main starts the process again for the second digit.

The second digit is processed similarly, except that it is stored in the Tens vari-able. After returning to Main for the third digit, the Digit3 subroutine executes.

The third digit is saved to the Ones variable and is displayed on the LCD in thesame way as the first and second digits were. The Move_Cursor subroutine movesthe DDRAM address to point to position 13 on line 2 of the LCD so that the charac-ter just entered can be displayed on the opposite side of the ‘=’ sign.

When Dec_Bin is called, the binary digit values stored in Hundreds, Tens andOnes are converted into a single binary number which is returned in W. The call toLCD_Data displays the this character represented by this number on the LCD.

Before exiting the Digit3 routine, the Digit counter is reset and the cursor isrepositioned to the DDRAM address C6h (the Hundreds digit location). After Digit3finishes, execution falls through to the Release subroutine. After debouncing, execu-tion returns to Main so the next character code can be entered.

Digit3 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Ones ;and store in Ones variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCD

Move_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 0Ch ;and offset cursor to position 13

CALL LCD_REG ;Send cursor position to LCD

CALL Dec_Bin ;Converts Hundreds, Tens Ones to binCALL LCD_Data ;and display on LCD

CLRF Digit ;Reset digit counter

Reset_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 06h ;and offset cursor to position 7

CALL LCD_REG ;Send cursor position to LCD

Release ;This is the opposite of the first key check. It waits for;the Key code to be zero and pauses for the debounce delay.

CALL KB_Port ;Set Port B for keypad useWait CALL KB_Scan ;Scan keypad

MOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has bee releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5msGOTO Main ;Get next digit

Page 125: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

125Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

Creating Custom Characters

We now know how to display any of the ASCII, Kanji or Greek characters on theLCD. There are times, however, when other special characters are needed.CUSTOM.ASM demonstrates how to create custom characters, perform single char-acter cell animation, and scroll messages.

First, assemble and download CUSTOM.ASM to a PIC16F84. Once you seewhat it does, we’ll look at how custom characters are programmed.

CGRAM

ASCII data values 0-7 display custom characters defined in the CGRAM ad-dresses. CGRAM is used to store custom generated characters. You can program atotal of eight custom characters.

There are actually 64 CGRAM locations. Each custom character is stored ineight successive CGRAM locations. A CGRAM address command is made up ofthree fields as shown in the CGRAM Custom Character Programming diagram.

The first field (bits 7 and 6) contains 01 to denote the CGRAM addressing com-mand mode. CGRAM address bits 5, 4 and 3 designate the ASCII character codebeing programmed. These three bits accommodate the definitions for eight charactercodes (000-111). Finally, CGRAM address bits 2, 1 and 0 specify one of the eightrows of the character being defined (Character Row Select bits).

At each CGRAM address, datacorresponding to one line of the cus-tom character must be stored. Thecharacter chart at left shows how char-acter 0 (Truck1) in the program is de-fined.

Each character is a 5X8 cell. TheCharacter Row Select bits are used toselect the row being defined. The databased on the character bitmap mustbe written to the CGRAM address foreach row. In pseudo-code, this char-acter would be programmed as shown:

Load W with LCDCGRAM (CGRAM starting address - 01000000b)CALL LCD_Reg to write CGRAM address to LCD

Load W with character data for row 1 (00000000b)CALL LCD_Data to write data to CGRAM address 01000000b

Load W with character data for row 2 (00000011b)CALL LCD_Data to write data to CGRAM address 01000001b

.

.

.Load W with character data for row 8 (00000010b)CALL LCD_Data to write data to CGRAM address 01000111b

ASCIIChar.Code

CGRAMAddressMode

Char.RowSelect

CharacterBitmap

CGRAM Data bitsCGRAM Address bits7700

0

1

1

0

0

1

1

00

00

0

00

00

0

0

0

0

0

0

0

0

0

0

0

0

0

0

6600

1

0

1

0

1

0

1

01

11

1

11

11

0

0

0

0

0

0

0

0

0

0

0

0

0

0

5500

0

0

0

1

1

1

1

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

44 33 22 11 00

CGRAM Custom Character Programming

1

1 1

1

1 1

1

1

1

1 1

1

1

1

1

1

1

1

1

0

00

0

00

00

0

0

00

0 0

0

0

0

0

0

0

0

In CUSTOM.ASM, thisprocedure is accomplishedusing a ROM data lookuptable. Like DDRAM,CGRAM addresses auto-matically increment afterCGRAM is written. Ascharacter rows are written,CGRAM increments intothe next character.

Refer back to the LCDController Commandschart to see why bits sevenand six are 0 and 1.

Page 126: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

126 ©1998 Sirius microSystemsMicrochip Code

Pull-out and refer to the CUSTOM.ASM program as we describe it.

After the ports have been configured for LCD use and the LCD has been initial-ized, Prog_Character is called to program the custom characters.

MOVLW LCDCGRAM and CALL LCD_Reg set the LCD to the first CGRAMaddress. The Counter variable is used to point to and return the custom character rowdata from the ROM data table.

CALL Characters and CALL LCD_Data retrieves the current row data from thedata table and writes it to CGRAM. CGRAM automatically increments to the nextaddress. Counter is incremented by INCF and is used to determine when the end of

Creating CustomCharacters

Initialize ;This subroutine initializes the LCD display and programs;the custom characters by calling Prog_Character.

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Prog_Character ;Load LCD with custom characters

Prog_Character ;Loads the custom character data into the LCD Character;Generator RAM. CGRAM is ASCII characters 0-7. Each charact;is loaded as a bit-map, one line at a time. The cursor;auto-increments to the next CGRAM location after each;write.

MOVLW LCDCGRAM ;Send LCD CGRAM address (40h) toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Get_Char MOVF Counter,0 ;Get character offset into WCALL Characters ;use it to get character dataCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterMOVLW 64 ;Load W with number of char. bytesSUBWF Counter,0 ;and compare with CounterBTFSC Z ;by checking Z flagRETURN ;If Counter=64, we�re doneGOTO Get_Char ;Do it again for the next character

Characters ADDWF PCL ;Offset PC with Counter in W

Truck1 RETLW 00000000b ;Row 1, ASCII character 00RETLW 00000011b ;Row 2, ASCII character 00RETLW 00000011b ;Row 3, ASCII character 00RETLW 00001111b ;etc.RETLW 00001111bRETLW 00011010bRETLW 00000111bRETLW 00000010b

Truck2 RETLW 00001111b ;Row 1, ASCII character 01RETLW 00001111b ;Row 2, ASCII character 01RETLW 00001111b ;etc.RETLW 00001111b

.

.

.Man4 RETLW 00000000b ;Row 1, ASCII character 07

RETLW 00000000b ;Row 2, ASCII character 07RETLW 00000001bRETLW 00000011bRETLW 00000001bRETLW 00000011bRETLW 00000001bRETLW 00000000b ;Row 8, ASCII character 07

Page 127: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

127Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

MOVLW LCDLine1 ;Load W with Line 1 addressMOVWF Position ;Save W in Position registerCALL LCD_REG ;and send to LCD as commandMOVLW 04h ;Load W with Man1 Character codeMOVWF Counter ;and save in LCD character counter

Walk ;Makes a little man walk across the screen by successively;writing each of the 4 Man characters into the same cursor;position and then moving the cursor 1 position to the;right before repeating.

MOVF Counter,0 ;Get current Man CharacterCALL LCD_Data ;and send to LCDMOVLW CursLeft ;Load W with Cursor Left shiftCALL LCD_Reg ;command and send to LCDCALL Delay ;Wait a bitINCF Counter ;Increment to next Man CharacterMOVLW 08h ;Load W with number of last ManSUBWF Counter,0 ;and check for last countBTFSS Z ;by checking ZGOTO Walk ;If not at last Man, display next ma

MOVLW � � ;If at last Man, Load W with � �CALL LCD_Data ;to clear characterINCF Position ;Increment cursor position variableMOVLW 04h ;Load W with Man1 CharacterMOVWF Counter ;and save to character counterMOVLW 90h ;Load W with last visible positionSUBWF Position,0 ;and compare with PositionBTFSS Z ;by checking ZGOTO Walk ;If not at last position, do it agai

CALL Delay ;If done, wait before rolling Truck

CGRAM data has been reached, as well as to point to the next row data in the datatable.

MOVLW 64 loads W with the number of CGRAM addresses to be programmed.SUBWF Counter,0 subtracts W from Counter, leaving Counter unchanged. If theresult is zero, Counter equals 64 and CGRAM is programmed. Otherwise, BTFSC Zskips the RETURN and the next character is programmed into CGRAM.

After the Prog_Character routine completes, both W and the Position variableare set to 80h by the LCDLine1 equate. Position is used to keep track of the DDRAMaddress—the character position of the man on the display. Calling LCD_Reg sets theLCD to line 1, position 1. Then the ASCII value of the first Man character (04h) isloaded into the Counter variable.

The Walk routine successively writes each of the four Man characters into oneDDRAM address to create an animation. Then, the current DDRAM address is clearedand the four Man characters are written to the next DDRAM address. The result isthe appearance of motion within each character position, and also across the LCD.

MOVF Counter,0 and CALL LCD_Data move the ASCII code of the currentMan character to the LCD display. MOVLW CursLeft and CALL LCD_Reg movethe cursor back to the last DDRAM address so the next Man character can overwritethe first. A nested delay loop is used to keep the current Man character on the displaylong enough for you to see it.

The Man 1-4 charactershave been programmed asASCII characters 4-7.

64 is the number of charac-ter rows in the data table.

Page 128: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

128 ©1998 Sirius microSystemsMicrochip Code

Next, Counter is incremented and compared with 08h. If Counter is not equal to08h, the four Man characters have not been displayed and the GOTO Walk is ex-ecuted. If Counter equals 08h, all four Man characters have been displayed, and thecurrent position must be cleared.

MOVLW ‘ ’ and CALL LCD_Data write a space character to clear the celladdress. MOVLW 04h and MOVWF Counter reset Counter to ASCII code 04h—the first Man character.

INCF Position updates the position counter in preparation for a check to see ifthe end of the LCD screen has been reached. While Position is less than 90h, theGOTO Walk command executes, continuing the loop that displays the four Mancharacters in the next DDRAM cell. When Position reaches 90h, the Man has reachedthe end of the screen and a short delay occurs before the Roll routine executes.

In Roll, the LCDLeft command is used to scroll the entire DDRAM contentsfrom right to left generating the illusion of motion. Also of note is that the Truckcharacters are written off the visible display screen (locations 90h to 93h) and arescrolled into the visible window. Since DDRAM is configured in a circular fashion,the Truck drives by every forty display shifts.

The Counter variable is used to hold the ASCII character code to be displayed.Counter is cleared to start at ASCII character 00h—the front of the Truck from theCGRAM Custom Character Programming chart. The ASCII code is moved into Wand CALL LCD_Data places the first Truck character at the current DDRAM loca-tion (90h from the end of the Walk subroutine). The LCD DDRAM pointer auto-matically increments to the next address. Counter is incremented and checked beforethe next ASCII character, Truck2, is written to DDRAM.

After all four Truck characters have been written to DDRAM, the :Loop subrou-tine shifts the DDRAM contents left by writing the LCDLeft equate as a command.A nested delay loop separates successive shifts and completes the illusion of motion.

Notice the colon (:) in front of the :Loop label. The colon denotes that :Loop is alocal label. Both this :Loop and :Next belong to the Roll routine.

Roll ;Scrolls a Truck back across the screen continuously by;writing the 4 Truck characters off the screen (cursor was;left at position 90h by Walk) and then scrolling the;screen to the left. Since the display was cleared earlier;you will see only the Truck. The line length is 40 chars.;Every 40 display shifts, the Truck comes around again.

CLRF Counter ;Clear character counter variable:Next MOVF Counter,0 ;Load W with counter

CALL LCD_Data ;and send character to LCDINCF Counter ;Increment Counter registerMOVLW 04h ;Load W with number of Truck chars.SUBWF Counter,0 ;and compare with counterBTFSS Z ;by checking ZGOTO :Next ;If not done, send next Truck char.

:Loop MOVLW LCDLeft ;If done, load W with LCD shift leftCALL LCD_Reg ;command and send to LCDCALL Delay ;Wait a bitGOTO :Loop ;Keep scrolling the display

The :Next loop could havebeen replaced by fourindependent MOVLW andCALL LCD_Data opera-tions. This would havetaken about the sameamount of PIC programmemory.

The Walk routine exitswhen the DDRAM addressincrements to 90h.

Page 129: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

129Chapter 12 Using

the LCD Display©1998 Sirius microSystems Microchip Code

Delay ;Delay between Man & Truck movements

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;256 more timesRETURN

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

The Delay and Delay_5ms subroutines also include :Loop labels. The PM as-sembler associates each :Loop label with the routine in which it resides. You can re-use local label names, and as long as they are placed in separate routines, they won’tbe mistaken for one another when they are called.

Chapter Summary

LCDs have a number of features dependent on their internal controller. In orderto use LCDs you need to know the commands necessary to operate the LCD control-ler.

In the PIC-MDS, three Port A lines connect to the LCD control lines. Port Bconnects to the LCD data bus. LCD.LIB contains the subroutines which configurethe ports, intitialize the display, and write commands and data to the LCD.

The LCD displays a window of 16 characters in a 40 character long circularbuffer. This DDRAM buffer is addressable and can be shifted left or right to providetext scrolling.

Eight custom characters can be programmed into the LCD CGRAM.

Not all assemblers supportlocal labels.

Page 130: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

130 ©1998 Sirius microSystemsMicrochip Code

After you have read and fullyunderstood this entire chapter,you’ll find your brain has ex-panded to approximately fivetimes its normal size.

Questions

1. What is the difference between absolute and relative character addressing?

2. How many custom characters can be programmed into the LCD CGRAM?

3. Describe the function of the three LCD control signals.

4. How is it possible for the LCD to share Port B with the keypad and LEDs?

Assignment

1. Read the LCD.LIB include file and describe the function of each subroutine.

2. In pseudo-code, list the steps required to display the words ‘Hello World!’ onthe LCD.

3. Modify the program ASCII.ASM so that one key backs the cursor up by oneposition to fix entry mistakes.

4. Modify ASCII.ASM to be a decimal to binary conversion calculator. Insteadof displaying the ASCII character equivalent to the digits entered, display thebinary equivalent of the three digits. eg. entering 142 displays 10001110

5. Write a program that scrolls a message across the LCD display.

6. Program a set of custom characters to provide a vertical bargraph display inone character position of the LCD. For testing, entering the numbers 1-8 on thekeypad should indicate eight different levels on the bar graph.

Page 131: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

131Chapter 13

Using the PIC16F84Data EEPROM

©1998 Sirius microSystems Microchip Code

13 Using the PIC16F84Data EEPROM

One of the unique features of the PIC16F84 is its internal data EEPROM. The64 bytes of EEPROM can be used to store data that must be retained while power isoff such as passwords, operating defaults, tuning parameters or current operatingmodes. In contrast, the RAM registers lose their contents when power is off.

For example, a PIC16F84 can be used to replace the mechanical timer in a wash-ing machine. During the operation of the washing machine, the data EEPROM canbe programmed with the current operating cycle: wash, rinse or spin. If power failsduring the rinse cycle, the PIC16F84 in the washing machine will know enough tocontinue the rinse cycle when power returns, closely emulating a mechanical timer.

Using the PIC16F84 Data EEPROM

The PIC16F84 data EEPROM is not accessed in the same way as a file register.Instead, four file registers—EEDATA (08h), EEADR (09h), EECON1 (88h) andEECON2 (89h)—control access to the EEPROM.

EEADR is the data EEPROM address pointer and holds a value representingone of the sixty-four possible storage location addresses. EECON1 contains flags

These four file registerscontrol access to the dataEEPROM, here.

Page 132: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code132

that control EEPROM reads (RD) and writes (WR), along with the write enable(WREN), write error (WRERR), and interrupt flag (EEIF) bits. EEDATA containsthe data to be written to, or the data previously read from the EEPROM addresspointed to by EEADR. EECON2 is used during EEPROM writes.

When the PIC16F84 is first powered up, the WREN bit is cleared, disablingwrites to data EEPROM. The WREN bit must be set before EEPROM writes canplace. This protects the EEPROM contents during power up. To safeguard your datafrom unwanted changes during a power down, brown-out or software failure, clearthe WREN bit after storing your data. EEPROM writes also require that a specificsequence of bytes is written into EECON2 (see page 34 of the PIC16F8X data sheets).

EEPROM writes typically take 10 ms—or 25,000 processor cycles at 10 MHz.Writing successive values into the data EEPROM requires that you either poll theEEIF or WR bits, or use interrupts in your EEPROM write routine.

Reading From and Writing To the Data EEPROM

The program NVMEM.ASM displays the contents of the first four data EEPROMlocations and prompts the user to enter a four-digit code. This code is stored in thefirst four data EEPROM locations before a power down message appears on theLCD display. After removing and reapplying power the program runs again, display-ing the previously entered four-digits. NVMEM.ASM demonstrates how values canbe saved and restored despite power interruptions.

Pull NVMEM.ASM and EEPROM.LIB from the Program References section.

The Counter variable contains the offset used to retrieve characters from the datatables in the Disp_Line1, Disp_Line2 and Disp_Done subroutines. Counter1 andCounter2 are used in the 5 ms delay loop required by LCD.LIB. The Key variablecontains the key return code used by KEYPAD.LIB.

After initializing the Key and Counter variables and resetting the program Ori-gin to 0005h, the EEPROM, KEYPAD and LCD libraries are included.

EEPROM.LIB takes care ofall of these details.

;Hardware Equates

ORG 0Ch ;Start of File register area

Counter DS 1 ;LCD character counter

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

Key DS 1 ;Key return code variable

Include �EEPROM.LIB� ;EEPROM subroutine libraryInclude �KEYPAD.LIB� ;Keypad scanning subroutine libraryInclude �LCD.LIB� ;LCD subroutine library

Reading From andWriting To the DataEEPROM

Page 133: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

133Chapter 13

Using the PIC16F84Data EEPROM

©1998 Sirius microSystems Microchip Code

Program initialization continues by calling the subroutines necessary to initializethe LCD. Disp_Line1 displays the message “Old Data: ” on line one of the LCD.

Disp_Line1 retrieves characters stored in the program memory by using a datatable read. The Counter variable holds the character offset for the Message1 datatable. The :Get_Char loop retreives one character at a time from Message1, sends thecharacter to the LCD for display, and increments the Counter variable before retriev-ing the next character. The loop exits with a RETURN when a “0” is read from thedata table.

The Send_Old routine reads the data from the first four EEPROM addresses.The ASCII characters equal to each data value are displayed. If the EEPROM in the

Initialize ;This subroutine initializes the LCD display and writes;a message on to line 1 and �=� on to line 2. The cursor;is turned on to indicate where input will be shown.

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Line1 ;Send first line message to LCD

Disp_Line1 ;Writes �Old Data: � to the first line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counter:Get_Char MOVF Counter,0 ;Get character offset into W

CALL Message1 ;use it to get characterIORLW 00h ;RETLW won�t affect flags, use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO :Get_Char ;Do it again for the next character

Message1 ADDWF PCL ;Offset program counter by adding WRETLW �O� ;Message1RETLW �l�RETLW �d�RETLW � �RETLW �D�RETLW �a�RETLW �t�RETLW �a�RETLW �:�RETLW � �RETLW 0 ;End of message

This structure is introducedand described in detail inChapter 10.

Send_Old ;Reads EEPROM addresses 0-3 and writes the contents to the;LCD display.

CLRF EEADR ;Select EEPROM address 00:Loop CALL EE_Read ;Call EE_Read to place data into

MOVF EEDATA,0 ;EEDATA, and read EEDATA into WCALL LCD_Data ;Copy W to LCD DDRAMINCF EEADR ;Increment to next EEPROM addressMOVLW 04h ;Load W with number of data bytesSUBWF EEADR,0 ;and compare with EEADRBTFSS Z ;by checking ZGOTO :Loop ;If not at EEADR 04, get next data

Line2 MOVLW LCDLine2 ;Load W with line 2 DDRAM addressCALL LCD_Reg ;and write to LCDCALL Disp_Line2 ;Send second line message to LCD

Page 134: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code134

PIC16F84 has never been programmed, you will likely see four blocks which repre-sent the character equal to the value 255. CLRF EEADR resets the EEPROM ad-dress pointer to 00h. CALL EE_READ reads the contents of the location specifiedby EEADR and copies the contents into EEDATA.

Reading data from the EEPROM requires that EEADR contains the address tobe read and is completed by setting the RD bit in EECON1. The contents of theEEPROM location are transferred to the EEDATA register and can be read by thenext program instruction. The PIC16F84 automatically clears the RD bit in prepara-tion for the next read.

Following the RETURN in EE_Read, MOVF EEDATA,0 transfers the data readfrom the EEPROM into W so that CALL LCD_Data can display a character equalto its ASCII value. EEADR is then incremented and compared with 04h, causing thefirst four locations (00h to 03h) to be read. If EEADR is less than 04h, the result ofthe SUBWF EEADR,0 instruction is not zero and the BTFSS Z does not skip theGOTO :Loop. Therefore, while EEADR equals 0, 1, 2 or 3, the GOTO :Loop in-struction executes and the value returned in EEDATA is displayed. After the fourlocations have been displayed, the Line2 routine displays the message “New Data: ”on the second line of the LCD.

The Disp_Line2 subroutine is a copy of the Disp_Line1 subroutine, but uses theMessage2 data table.

After the message “New Data: ” has been displayed, the cursor is turned on bythe MOVLW CursOn and CALL LCD_Reg instructions. The CursOn commandactivates the underscore cursor at the current CGRAM address—which is always

All new PIC16F84 proces-sors have FFh in theEEPROM. The assemblercan set the contents of theEEPROM at programmingtime. See Appendix C forinformation. EE_Read ;Sets the RD bit in EECON1 to read the contents of EEADR

;into EEDATA.

BSF RP0 ;Select memory register page 1BSF RD ;Set the EECON1.RD bit to readBCF RP0 ;Return to memory register page 0RETURN

MOVLW CursOn ;Load W with Cursor On commandCALL LCD_Reg ;and write to LCD

Get_New ;Wait for key presses and after a debounce delay stores th;ASCII value of the current key codes in EEPROM memory fro;address 0-3.

CLRF EEADR ;Reset EEADR to the beginningCALL KB_Port ;Configure Port B for keypad

Get_Key CALL KB_Scan ;Get Key return codeMOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try againCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

CALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Key_Remap ;and Remap key codes

From EEPROM.LIB

Reading From andWriting To the DataEEPROM

Page 135: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

135Chapter 13

Using the PIC16F84Data EEPROM

©1998 Sirius microSystems Microchip Code

the address after the last character written. In this case, the cursor appears in thesecond space after the colon, since the last character of the message is a space.

CLRF EEADR resets the EEPROM address pointer to zero in preparation forentering and storing the four new character values. CALL KB_Port prepares Port Bfor the matrix keypad and CALL KB_Scan returns the key code in Key.

MOVF Key,0 transfers the key code to W and updates the Z flag. If the value ofKey is zero, the BTFSC Z instruction does not skip the GOTO Get_Key instructionand the process loops until a key is pressed.

When a key is pressed, the four CALL Delay_5ms instructions provide a 20 msdelay for the key to settle so it is not bouncing when read the second time. Instead ofwriting a 20 ms delay routine, we chose to call the Delay_5ms routine required byLCD.LIB four times.

Once the key has settled, it is re-read and remapped to an ASCII value by theKey_Remap subroutine.

The Key_Remap subroutine is a data table that changes keycodes to ASCIIvalues before they are stored in the EEPROM. This way, the EEPROM holds datathat can be immediately displayed on the LCD without requiring conversion.

The remapped key value is stored in the EEDATA register by MOVWF EEDATA.The CALL to EE_WRITE stores the contents of the EEDATA register into theEEPROM location pointed to by EEADR. The first time through, EEADR will be00h since it was cleared at the start of the Get_New routine.

Key_Remap ;Changes key codes into ASCII values.

ADDWF PCL ;Use old Key to offset PCNOP ;No Key=0 codeRETLW 30h ;key 1 remapped to ASCII 30h �0�RETLW 31h ;key 2 remapped to ASCII 31h �1�RETLW 32h ;key 3 remapped to ASCII 32h �2�RETLW 33h ;key 4 remapped to ASCII 33h �3�RETLW 34h ;key 5 remapped to ASCII 34h �4�RETLW 35h ;key 6 remapped to ASCII 35h �5�RETLW 36h ;key 7 remapped to ASCII 36h �6�RETLW 37h ;key 8 remapped to ASCII 37h �7�RETLW 38h ;key 9 remapped to ASCII 38h �8�RETLW 39h ;key 10 remapped to ASCII 39h �9�RETLW 41h ;key 11 remapped to ASCII 41h �A�RETLW 42h ;key 12 remapped to ASCII 42h �B�RETLW 43h ;key 13 remapped to ASCII 43h �C�RETLW 44h ;key 14 remapped to ASCII 44h �D�RETLW 45h ;key 15 remapped to ASCII 45h �E�RETLW 46h ;key 16 remapped to ASCII 46h �F�

Key remapping is ex-plained in more detail inthe ASCII.ASM programfound in Chapter 12.

MOVWF EEDATA ;Save new Key code in EEDATACALL EE_Write ;Write key data to current EEADRCALL EE_Wait ;and wait for write to finish

CALL EE_Read ;Read current EEADR to check;that EEDATA was written properly

CALL LCD_Port ;Configure Ports for LCDMOVF EEDATA,0 ;Get saved Key code from EEPROMCALL LCD_Data ;and display on LCD

Page 136: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code136

EE_Write ;Writes the contents of EEDATA to EEADR as specified in;the PIC16F84 data sheets after enabling WREN. After;writing the data, WREN is cleared, disabling accidental;writes.

BSF RP0 ;Select memory register page 1BSF WREN ;Enable EEPROM writesMOVLW 55hMOVWF EECON2 ;Write 55h to EECON2MOVLW 0AAhMOVWF EECON2 ;Write AAh to EECON2BSF WR ;Set EECON1.WR bitBCF WREN ;Disable any further writesBCF RP0 ;Return to memory register page 0RETURN

EE_Write must first enable EEPROM writes by setting the WREN (WRiteENable) bit. The contents of EEDATA will be written into the EEPROM addressspecified by EEADR by setting the WR (WRite) bit . On power-up, the WREN bit iscleared, preventing unwanted EEPROM writes.

However, before the WR bit can be set—to write EEDATA into the EEPROM—a unique pattern of bits must be written to EECON2. See page 34 of the PIC16F8Xdata sheets for more detail. Following this peculiar initialization of writing 55h and0AAh to EECON2, BSF WR initiates the internal PIC16F84 write sequence. Thewrite sequence can take up to 10 ms to complete. When the internal sequence iscomplete, the contents of EEDATA have been transferred to the address in EEADR,and the PIC clears the WR bit and sets the EEIF bit.

After initiating the write using BSF WR, BCF WREN disables further EEPROMwrites, safeguarding the data from being overwritten by program errors, brown-outsor erratic behaviour on power-down. Even though the write sequence initiated byBSF WR may not be complete, it is safe to disable further EEPROM writes.

Since the RETURN from EE_Write occurs before the internal EEPROM writesequence is complete, subsequent EEPROM writes cannot occur until the previouswrite has finished. A wait loop is provided by EE_Wait.

The completion of an EEPROM write is indicated by the PIC clearing WR andsetting EEIF. EE_Wait monitors the EEIF interrupt flag bit. Before the next writecan take place, the EEIF flag must be reset by software. A program could also moni-tor the WR bit, since the WR bit is cleared automatically after the write sequencefinishes.

Following the RETURN from EE_Wait, the CALL to EE_Read retreives therecently written data from the EEPROM to verify that the value of the key press isstored properly. Although the program does no real checking, reading back the

EE_Wait ;Wait for an EE_Write to finish by checking the EEIF;flag bit in EECON1.

BSF RP0 ;Select memory register page 1:Wait BTFSS EEIF ;Check EEIF for a high (1=finished)

GOTO :Wait ;If low, wait for EEIF to go highBCF EEIF ;Clear EEIF after write is doneBCF RP0 ;Return to memory register page 0RETURN

From EEPROM.LIB

From EEPROM.LIB

Reading From andWriting To the DataEEPROM

Page 137: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

137Chapter 13

Using the PIC16F84Data EEPROM

©1998 Sirius microSystems Microchip Code

EEPROM data allows you to verify the keypress. In this case, the recently writtenvalue is displayed on the LCD by CALL LCD_Port, MOVF EEDATA,0 and CALLLCD_Data.

Like the key press code, the key release code waits for the key to settle when youremove your finger from the keypad. The only change from the key press code is theBTFSS Z which causes the loop to wait until the key is released. Once the key isreleased, 20 ms is provided for settling time by calling Delay_5ms four times.

At this point, the first value has been entered from the keypad, saved in theEEPROM, read from the EEPROM, and displayed on the LCD. The EEADR regis-ter is now incremented by INCF EEADR so that the process can repeat for the nextthree characters.

Until four characters have been entered, MOVLW 04h, SUBWF EEADR,0 andBTFSS Z cause the execution of GOTO Get_Key to repeat the key scanning, storing,retrieval, and display process. When the fourth value has been retrieved via the GOTOGet_Key instruction, the result of SUBWF EEADR,0 will be zero and the zero flagwill be set. The BTFSS Z will then cause GOTO Get_Key to be skipped, and the re-maining commands set up the LCD and call Disp_Done to display the message “Powerdown now.”. The SLEEP command at the end of the main line code places thePIC16F84 into low power sleep mode.

The result is that the NVMEM.ASM program has now placed four new values,representing the four keys pressed on the keypad, into the internal EEPROM. Re-moving power from the microcontroller will not erase these values. Try it and see.

Chapter Summary

The internal EEPROM can retain its data while power to the PIC is off. The 64bytes of EEPROM data are accessed using the EEDATA and EEADR registers alongwith EECON1 and EECON2. EECON1 contains control, flag and interrupt bits.Writing 55h and AAh to EECON2 in the manner specified by microchip (pg. 34 ofthe PIC16F8X data sheets) performs EEPROM writes.

CALL KB_Port ;Set Port B for keypad useWait CALL KB_Scan ;Scan keypad

MOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has been releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

INCF EEADR ;Increment to next EEPROM addressMOVLW 04h ;Load W with number of data bytesSUBWF EEADR,0 ;and compare with EEADRBTFSS Z ;by checking ZGOTO Get_Key ;If not at EEADR 04, get next dataCALL LCD_Port ;Reconfigure ports for LCDMOVLW LCDLine1 ;Load W with line 1 DDRAM addressCALL LCD_Reg ;and write to LCDCALL Disp_Done ;Display done messageSLEEP

Remember, all of this isstill part of the writesequence initiated abouttwo pages back.

You may have noticed thatDisp_Done is slightlydifferent from other datatables. It uses a techniqueexplained in Chapter 14that overcomes memorypage boundry problemsthat would otherwiseprevent this code fromworking.

Page 138: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code138Questions

Questions

1. Examine the PIC16F8x data sheets to determine how long data will remain inthe Data EEPROM.

2. List three applications that would benefit from the use of the Data EEPROM.

3. How much time, and how many clock cycles, does it take to store one byte inthe Data EEPROM? Assume a clock speed of 4 MHz.

Assignment

1. Using pseudo-code or a flow chart, describe the operation of an interrupt serv-ice routine that stores successive bytes of data after waiting for the previouswrite to finish.

2. Write the program for a programmable combination lock that stores the passcode in the Data EEPROM. Use a 5-digit pass code to open or close the lock.Assign one key on the keypad to change the pass code only when the lock isunlocked. Display the state of the lock using either an LED or the LCD.

Page 139: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

139Chapter 14

Troubleshooting©1998 Sirius MicroSystems Microchip Code

14 Troubleshooting

By this time you probably have the necessary skills to write reasonably complexprograms. This chapter will help you develop the skills needed to troubleshoot them.

Identifying and Isolating Faults

The key to troubleshooting your software is identifying and isolating faulty sec-tions of code. There are a number of techniques useful for identifying, narrowingdown and isolating faults. However, no one technique works all of the time. Each ofthe techniques explained below will help you to identify and isolate faults.

Validating Your Hardware

It makes no sense to troubleshoot software if your problem is in hardware. Usinga development system such as the PIC-MDS gives you the advantage of knowingthat the built-in hardware is at the very least wired correctly (really, we’ve tested it!).What’s more, the included software routines will let you verify the operation of thePIC-MDS hardware.

There comes a time, however, when you must strike out into uncharted territoryand interface your PIC-MDS to new hardware. Before connecting new hardware tothe PIC-MDS, there are a number of points to keep in mind.

I/O Requirements

Before starting to troubleshoot software, make sure that input devices providesignals at the proper level—a logic 0 should be from 0 V to approximately 0.8 V, anda logic 1 should be from approximately 2 V to 5 V. At the very least confirm thepresence of signals by monitoring the LEDs on the PIC-MDS. Better still, confirmsignal presence, amplitude and waveform using a voltmeter, logic analyser, or oscil-loscope.

Page 140: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code140

Test and examine all output circuitry to ensure that each PIC pin is not sinkingmore than 25 mA or sourcing more than 20 mA. Also, keep in mind that Port A cansink a maximum of 80 mA and can source a maximum of 50 mA. Likewise, Port Bcan sink a maximum of 150 mA and source a maximum of 100 mA. Lastly, theoverall power dissipated by the PIC16F84 cannot exceed 800 mW.

Shared I/O Lines

On the PIC-MDS, RA.2 and RA.3 are used to enable the LCD and SerialEEPROM, respectively. Any external devices that enable either one of these twolines will cause unpredictable results on any of the lines connected to the LCD orSerial EEPROM. Since the LCD connects to all of Port B as well as three out of thefive Port A pins, enabling it inadvertently can cause problems. Always disable theLCD and serial EEPROM if you’re not using them.

Since the keypad keys are normally open, they are, in essence, disconnected fromthe PIC-MDS, if not pressed. If pressed, a key will short one of the four row lines toone of the column lines on Port B. Resistors have been added to ensure that shortcircuit conditions do not occur. Nevertheless, your code might fail if someone were topress a key and inadvertently supply an input from a keypad row line to a keypadcolumn line rather than obtaining its input from an external source. If you’re going toobtain input from Port B, make sure users are not prompted to use the keypad. If youwish to use the keypad and need to obtain external input, you may use only Port A.0,1, or 4. Or, use half of the keypad thereby freeing up half of the Port B lines.

Similarly, while scanning for a key press, half of Port B is set to output and halfto input. Make sure that devices connected to Port B outputs can have their linestemporarily scanned and that Port B inputs are disconnected (i.e. placed into highimpedance or disabled). Again, if this presents a problem, use Port A.0, 1, or 4. Foran example of how to share the keypad and LCD on Port B see ASCII.ASM asdiscussed in Chapter 12.

If your application requires you to use your own hardware design, use a designsimilar to that of the PIC-MDS whenever possible—you know it works, and thelibrary routines will save you a lot of time in developing software.

“Playing” the Computer

Once you are certain that your faults lie in software, you can begin to examineyour code line by line. “Playing” the computer involves recording the state of eachregister as you determine the results of each instruction. Start with a print out of yoursource code and a blank piece of paper. Use the paper to record register contentsbefore and after each instruction. Don’t take anything for granted—use the instruc-tion descriptions in the Data Sheets to determine the result of each instruction and thestate of any affected flags.

As you can imagine, playing the computer is very time consuming. You wouldnever want to simulate the execution of your entire program, only those sections thatyou believe may be faulty. Use some of the techniques which follow to narrow yourtroubleshooting to specific sections of code.

Refer to the schematic inchapter 4 for details.

All owners of the PIC-MDSare permitted to use thePIC-MDS circuitry shownin Chapter 4 and thelibrary routines includedon disk in their microcon-troller designs.

Validating YourHardware

Page 141: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

141Chapter 14

Troubleshooting©1998 Sirius MicroSystems Microchip Code

Displaying Intermediate Values

If at all possible, use the built-in LEDs or LCD display on the PIC-MDS tomonitor relevant register, port or bit values. Often, faulty code produces unexpectedregister values and program branches. One method to verify that your program isoperating correctly up to a specific point is to insert code which writes the contents ofa register out to the LEDs and then puts the microcontroller to SLEEP.

Using the LEDs is simple and quick. Make sure that you set Port B to output (ifnecessary), move the contents of the register that you are interested in examining toW, then copy them to Port B before issuing a SLEEP instruction to halt execution atthis point. If the LEDs display the expected result, the program is functioning cor-rectly up to this point. You can then remove or comment out this code and placesimilar display code further down in your program.

The LCD allows you to display the contents of many more registers than theLEDs, but has the drawbacks of increased code complexity and the corruption of theW and Status registers. If the contents of W, or for that matter any registers, areimportant, save them in temporary file registers before accessing the LCD routines.Also, remember that values sent to the LCD are displayed as their equivalent ASCIIcharacter. At the risk of further increasing code complexity, you can convert valuesto decimal digits (using BIN2DEC.LIB), and add 30h to each digit to convert them toASCII digits.

External Triggers

Monitoring an unused I/O pin configured as a hardware flag or trigger can tellyou two things. By setting an output pin high at the start of a subroutine and clearingit at the end of the subroutine you have a way of determining not only that the subrou-tine executes, but also how long it takes to execute, and whether execution is consist-ent. For long subroutines you can see this by using an LED connected to a port pin,but for short subroutines you will obviously need an oscilloscope or logic analyser.

These external flags or triggers can also be used to provide a reference by whichto monitor other signals. This is especially useful for triggering oscilloscopes or logicanalysers when monitoring external signals like serial data streams.

Commenting Out Code

When a program appears to do nothing, a common cause is an undesired branchout of the main program flow. This may be caused by an error in your branch logic,or a computed GOTO over a memory page boundary—this is explained later in thisChapter. If you comment out or branch over suspect code and program flow returns,then the bypassed code is most likely at fault.

Commenting out existing routines and placing alternative routines after them isan easy way to evaluate the effects of program modifications.

In almost all cases, usingthe LEDs will be simpler.

Some people like to usedifferent cases or tab stopsto indicate modified code.

Page 142: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code142

Isolating Faults within Subroutines

Once you have an indication that a particular subroutine is faulty, much of thework of troubleshooting is already finished, although you’ll find that isolating andfixing the fault within a subroutine will take the majority of your time. To isolate thefault within a subroutine, use the techniques already discussed. Playing the computeris much easier when you’re not trying to simulate the operation of your entire pro-gram. Similarly, commenting out code, displaying intermediate values, and settingexternal triggers will all help you in debugging your routine.

Another item to bear in mind is the validity of the data being fed to the subrou-tine. If a subroutine is being fed erroneous data by a previous routine, its results willalso be in error. To determine if this is occurring, temporarily force load any variableregisters used by the subroutine before the subroutine executes. This way, you knowthat at the very least the starting data is valid.

Taking Breaks and New Approaches

Never underestimate the benefit of a good stretch, coffee break, lunch break, napor vacation as a troubleshooting tool. You may find that your subconscious mind willcome up with the solution if given a bit of time. More often, looking at your problemin a new way will lead you to the correct solution.

One of the best ways of uncovering bugs is to try to explain the operation of yoursoftware to a colleague. This approach forces you to systematically break down andjustify your code and logic. If your unfortunate victim is still paying attention, theymay question your logic and assumptions to reveal your error. Most often, simplyexplaining your code (and the errors within) will allow you to recognize the fault.

Memory Page Boundaries

The mid-range PIC microcontrollers use a 13-bit address space capable of ad-dressing 8k X 14 bits of program memory. Since the PIC uses 8-bit wide data regis-ters, the program counter is divided into two parts, PCLATH and PCL. PCL, or theprogram counter low byte, specifies a range of 256 memory addresses representingone memory page. PCLATH, or the program counter high latch, is a 5-bit registercontrolling the active memory page. The actual address specified by the programcounter is written as PCLATH:PCL and is the combined 13 bit address of PCLATHand PCL. For example, if PCLATH contained 03h, and PCL contained 10h, theresultant program counter value would be 310h. On the PIC16C711 and PIC16F84,only the first 1k addresses are implemented—equivalent to 4 memory pages.

Memory page boundaries occur whenever PCL rolls over from FFh to 00h andcan present a problem during a table read when using the ADDWF PCL instruction.ADDWF is known as a computed GOTO and is used by the data table read code inprevious chapters. The problem occurs only when the ADDWF PCL instruction is inone memory page, and the result of the computed GOTO lies in the next memorypage. Adding an 8-bit value to PCL will not cause PCLATH to increment if PCL

Isolating Faultswithin Subroutines

Page 143: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

143Chapter 14

Troubleshooting©1998 Sirius MicroSystems Microchip Code

rolls over. The result is that the computed GOTO still points within the current memorypage, and not to the next page as it should. Fortunately, all other GOTOs and branchescorrectly modify PCLATH so that the correct address is selected.

This precise problem occurs in the NVMEM.ASM program within theDisp_Done subroutine. Disp_Done uses a table read to display the message “Powerdown now.” on the LCD.

Notice in the list file generated by the assembler that the Message3 data tablestraddles a page boundary—addresses 00FF - 0100h. Compare this code withDisp_Line1 or Disp_Line2 in NVMEM.ASM and you will see that this table doesnot use the ADDWF PCL instruction to compute the GOTO. Instead, this subroutinedetermines whether or not to increment PCLATH by adding the offset to the table’sstarting PCL value and checking for an overflow via the Carry bit. If an overflowoccurs, then a page boundary has been crossed within the table and the PCLATHregister must be incremented.

Notice that the above table read code will work in any memory page because theupper five bits of the table address are loaded into PCLATH before computing theGOTO. In contrast, an ADDWF PCL instruction that results in PCL rolling overleaves PCLATH unchanged. Therefore, a computed GOTO using ADDWF PCLacross a page boundary results in the execution of instructions within the same pageas the ADDWF PCL instruction—not the next page as expected.

To overcome memory page boundary problems with data tables, either use codethat checks for and corrects page crossings (as in the example above), or make surethat your data tables and ADDWF instructions are in the same memory page—checkthe .LST file and use NOP instructions or rearrange code as necessary.

238 00E7- Disp_Done ;Writes �Power down now.� to the first line of the LCD239 ;display using LCD display library (LCD.LIB).240241 00E7- 018C CLRF Counter ;Reset character counter242 00E8- 3000 :Get_Char MOVLW HI Message3 ;Move the High Byte of Message3243 ;location into W244 00E9- 008A MOVWF PCLATH ;and Move it into PCLATH245 00EA- 30F6 MOVLW Message3+1 ;Move message address + 1 into W246 00EB- 070C ADDWF Counter,0 ;Calculate offset address and247 00EC- 1803 BTFSC C ;see if it overflows248 00ED- 0A8A INCF PCLATH ;If so, increment PCLATH249 00EE- 20F5 CALL Message3 ;Jump to the data table250251 00EF- 3800 IORLW 00h ;RETLW won�t affect flags so use O252 00F0- 1903 BTFSC Z ;check for end of message253 00F1- 0008 RETURN ;and finish if done254 00F2- 205A CALL LCD_Data ;If not done, send character to LC255 00F3- 0A8C INCF Counter,1 ;Add 1 to Counter256 00F4- 28E8 GOTO :Get_Char ;Do it again for the next characte257258 00F5- 0082 Message3 MOVWF PCL ;W contains low program counter259 ;byte and points to next location260 ;plus Counter offset261 00F6- 3450 RETLW �P�262 00F7- 346F RETLW �o�263 00F8- 3477 RETLW �w�264 00F9- 3465 RETLW �e�265 00FA- 3472 RETLW �r�266 00FB- 3420 RETLW � �267 00FC- 3464 RETLW �d�268 00FD- 346F RETLW �o�269 00FE- 3477 RETLW �w�270 00FF- 346E RETLW �n�271 0100- 3420 RETLW � �272 0101- 346E RETLW �n�273 0102- 346F RETLW �o�274 0103- 3477 RETLW �w�275 0104- 342E RETLW �.�276 0105- 3420 RETLW � �277 0106- 3400 RETLW 0 ;End of message

This table read code allowsdata tables to be placedanywhere in memory, evenacross page boundaries.

Page 144: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code144

A/D Converter Troubleshooting

The PIC16C711 Port A.0-3 lines can be set as digital I/O or analog inputs for theinternal A/D converter. When using a Port A pin as both an analog input and a digitaloutput, you must keep the following points in mind. Enabling A/D operation on aPort A pin does not configure the pin as an input. Before using a Port A output pin asan A/D input, the pin must first be configured as an input, then an A/D input. Yourcode may sometimes work without first configuring Port A pins as inputs because atpower up all PIC I/O lines are set to input.

Simulators and Emulators

There are programs available that will simulate the operation of your program.Simulators are computer programs that can step through code, instruction by in-struction, while displaying the contents of registers, I/O latches, and memory. Obvi-ously, simulators are extremely useful in debugging as they can play the computerfar better and faster than you could. The disadvantage of simulators is that they donot run your code in real time, and, being inside your computer, have no way ofinteracting with I/O devices that you may want to use with your microcontroller.

Emulators, on the other hand, do not suffer the limitations of simulators. Emula-tors incorporate circuitry that replaces the PIC in your target system. They run yoursoftware program in your hardware in real time. Furthermore, they allow you to stopthe execution of your program and examine registers and memory at any point. Theironly disadvantage is high cost.

Programming for Easy Troubleshooting

There are a number of programming techniques that make troubleshooting easier.By now, the benefit of using and reusing tested and proven subroutine libraries shouldbe apparent. Why keep reinventing the wheel when simply adapting existing code tofit your application is a better alternative. The following suggestions will help you indeveloping your software.

Plan, Plan, and Plan

Before you begin any programming task, make sure that you understand exactlywhat the program needs to do. Pay particular attention to any hardware devices thatthe microcontroller will need to interact with. Having specification sheets for anydevices that you will be interfacing to is very useful.

Use pseudo-code and flowcharts to outline the program’s structure and break theprogram into identifiable and manageable tasks.

Code and Debug Individual Program Tasks

After identifying program tasks, write the code for each individual task and verifythat it works as expected. Then, join interdependent tasks into larger code segments.A psychological benefit of this approach is that you meet with small successes often.Bringing small successes together ensures larger successes.

Some simulators usestimulus files to emulateexternal hardware signals.

A/D ConverterTroubleshooting

Page 145: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

145Chapter 14

Troubleshooting©1998 Sirius MicroSystems Microchip Code

Modularize Your Code

When writing your software routines, keep in mind that you may wish to usethem in other programs or with similar hardware. Writing program subroutines toincorporate similar structures, as well as using similar entry and exit parametershelps to improve the understanding of your programs. Easily changeable variables,defines in the equates at the beginning of the program, make for minor code changeswhen adapting your subroutines for different hardware.

Comments

Good comments do not explain what the instructions are doing as much as theyexplain how and why the instructions in a routine are being used together. Subrou-tines are often preceded by extensive comments that explain the purpose of the sub-routine, important registers, registers modified, calling protocols and variables.

Another good use of comments is to record the revision history of your program.Use comments to keep track of which routines are working and debugged, any rou-tines that were modified to accommodate hardware changes, and work yet to bedone. Heed this advice and your successors will profusely praise your programmingprowess!

Chapter Summary

Effective troubleshooting entails systematically isolating and identifying pro-gram or hardware faults. Various techniques such as validating your I/O hardware,simulating program execution, halting program operation at specific points and dis-playing intermediate values help in uncovering program flaws.

Writing code in a manner that simplifies testing and debugging lessens the needfor troubleshooting. Planning ahead, and writing code in manageable sections helpsto ensure working code.

Be aware of unique hardware dependencies that may affect the operation ofyour software—the memory page boundary and A/D configuration are examples.

Page 146: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code146

Questions

1. What is the central philosophy of troubleshooting?

2. Why halt the program when displaying intermediate values?

3. When would it be desirable to use the LCD to display intermediate values?

Assignment

1. Take any existing program of your own (working or not) and add code todisplay intermediate values in at least three different places.

2. Use an external trigger and an oscilloscope to time the execution of a subrou-tine in one of your programs.

Mr. Bugs Quasher was particularly good atdebugging code using the “playing the computer”troubleshooting technique.

Questions

Page 147: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

147Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

15 RS-232 SerialCommunication

The RS-232 serial communication standard has attained widespread use andmany devices can transfer data or be controlled using RS-232 signals. Typical de-vices include: computers, printers, plotters, modems, bar-code readers, operator in-terface terminals, motor controllers, data loggers, LCDs, GPS receivers, millingmachines, PLCs and many more. This chapter will demonstrate how to send andreceive RS-232 serial data.

RS-232 Basics

The RS-232 standard specifies the connector type, handshaking protocols andelectrical characteristics for a serial communications link. The traditional RS-232connector is a 25-pin DB-25, although recently the 9-pin DB-9 connector has be-come common on PCs. The PIC-MDS has a 3-pin header that you can connect toeither a DB-9 or DB-25 connector as required. One pin transmits serial data, anotherpin receives serial data, and the third pin is a signal ground. Most RS-232 devicescan be configured to communicate using only these three lines. Below is a diagramshowing how to connect a DB-25 or DB-9 connector to the PIC-MDS 3-pin header.

Depending on the device orcommunication softwareused, you may only need toconnect Transmit Data,Receive Data and SignalGround. The other wiressimulate hardwarehandshaking for devicesthat require it.

Page 148: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code148

Handshaking can be used to start or stops the flow of data. Handshaking isnecessary if a device cannot finish processing a character before the next characterarrives. The RS-232 standard specifies hardware handshaking, but handshaking canbe implemented using either hardware or software techniques. Hardware handshakinguses a number of the signal lines on the previous page to coordinate data flow and isusually implemented using a dedicated UART or serial communications interface.

Software handshaking relies on the transmission of special XON (Transmit on)and XOFF (Transmit off) characters, which are sent and received using just thetransmit and receive data lines. Therefore, a full-duplex, controlled serial communi-cations link can be established using only three lines—transmit, receive and ground.This makes software handshaking relatively easy to implement.

The RS-232 transmit and receive examples in this Chapter demonstrate serialcommunication without handshaking. Handshaking is usually not necessary whentransmitting small amounts of data, or when the data can be processed at high speeds.

The RS-232 electrical signal is bipolar, unlike the unipolar 5 V TTL level sig-nals used by most computer systems. RS-232 voltage levels are also opposite totheir equivalent TTL logic levels. For this reason, the PIC-MDS is equipped with aMAX232 level translator (see the schematic in Chapter 4). The diagram below showsthe same RS-232 data frame as both TTL and RS-232 signal levels.

An RS-232 data frame consists of a start bit, a number of data bits, an optionalparity bit, and a stop bit. Most modern RS-232 devices communicate using eightdata bits, no parity, and one stop bit—otherwise known as 8n1.

Note that the TTL logic level during the idle time between frames is 5 V. Thestart bit is always a logic 0, making it easy to determine when a frame begins. Evenwhen frames follow one another, with no idle time, the logic 1 stop bit ensures therewill be a high to low transition to mark the start of the next frame. After the start bit,the data bits are sent in least-significant to most-significant bit order.

RS-232 Basics

UART stands for UniversalAsynchronous ReceiverTransmitter, and is an ICdedicated to serial I/O.

The serial ports on somePC’s will accept 5 V as aspace, and 0V as a mark,eliminating the need for adedicated level translatorsuch as the MAX232. Theclamping diodes on thePIC I/O pins allow RS-232levels to be input directlyas long as a series limitingresistor is used, againeliminating the need for alevel translator. However,in both cases, the logic ofthe TTL waveform must bereversed.

Page 149: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

149Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

Receiving RS-232 Data

Since serial data bits are sent sequentially, receiving the data correctly is a matterof sampling the data bits at the correct times. The serial signal’s bit per second (bps)rate can be used to calculate the bit time, or the duration of each bit. The default datarate used by the RS-232 library programs is 9600 bps. We can calculate the bit timeas follows:

Once the bit time is known, receiving RS-232 data can be described by the fol-lowing pseudo-code:

Wait for the receive data line to drop lowWait ½ bit timeIs receive data line still low? (Is it a Start bit or noise?)If not, low pulse was noiseIf low, wait 1 bit timeSample data bit 0Wait 1 bit timeSample data bit 1

:Wait 1 bit timeSample data bit 7Wait 1 bit timeIs receive data line high? (Stop bit)If not, a framing error has occurredIf high, data received

Examine the timing diagram, below, for a visual representation of the samplepoints used to receive RS-232 data: (Shown in postive logic or TTL form.)

The RS-232 receive andtransmit library filessupport all common bpsrates.

The transmitted charactershown here is 41h, or theASCII character ‘A’.

Page 150: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code150

The RECV232.ASM program uses RS232RX.LIB to receive serial charactersand display them on the first line of the LCD. To test this program, use a terminalprogram on a personal computer connected to the PIC-MDS by a cable as describedearlier. Also, ensure that JU5 is on the Rx setting.We’ll examine the program begin-ning with the hardware equates.

The CharAddress, CharCounter and LCD_Length variables are used by the LCDscrolling routines. These variables, described later, allow the first 16 characters re-ceived to fill the LCD. Subsequent serial characters cause the previously receivedcharacters to scroll across the display from right to left. Counter1 and Counter2 areused by LCD.LIB to provide the 5 ms LCD initialization delay.

The RS232RX.LIB subroutine library requires the Counter, BitCounter andReceive variables. Counter is used to generate bit time delays and BitCounter keepstrack of the number of received bits. Received data bits are shifted through the Re-ceive register. After eight bits are received, the Receive register contains the trans-mitted character.

At the start of the program, the LCD is initialized and cleared. The CALL toReceive_Port uses RS232RX.LIB to set RA.4 for serial input.

The Receive_Port subroutine sets TRISA.4 using an OR operation that leavesthe other TRISA bits unchanged.

;Hardware Equates

ORG 0Ch ;Start of File register area

;Counter equatesCharAddress DS 1 ;Holds current LCD DDRAM addressCharCounter DS 1 ;Counts characters before scrollCounter1 DS 1 ;Delay counter for Delay_5msCounter2 DS 1 ;Delay counter for Delay_5ms

;Equates required by RS232RX.LIBCounter DS 1 ;Bit delay counterBitCounter DS 1 ;RS232 bit counter registerReceive DS 1 ;Received byte storage register

;Other equatesLCD_Length EQU 16 ;Number of characters per LCD line

ORG 00h ;Start program at Reset Vector

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Receive_Port ;Set RA.4 for serial input

Receive_Port ;Sets PORTA.4 to input. Make sure PIC-MDS JU5 is set to Rx

BSF RP0 ;Select memory register page 1MOVLW 00010000b ;Load W with bit to make RA.4 inputIORWF TRISA ;and OR with Port A tristate reg.BCF RP0 ;Return to memory register page 0RETURNFrom RS232RX.LIB

Make sure your terminalprogram is transmitting at9600 bps, 8 data bits, noparity and 1 stop bit—8n1.

Receiving RS-232Data

Page 151: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

151Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

After the include statements for the LCD and RS232RX library files, the Initial-ize routine begins. Initialize loads the CharCounter variable with LCD_Length (16in this case) and then decrements CharCounter by 1 so that display scrolling beginsafter 15 characters have been received.

Next, the LCD cursor is enabled in blinking mode, and the LCD DDRAM ad-dress is set to the first character of line 1. The CharAddress variable also holds thecurrent LCD address, so that it can be used to reset the DDRAM address after fortycharacters have been received. Saving CharAddress in a memory register frees theprogram from having to interrogate the LCD to determine the current character ad-dress.

The Main subroutine calls Receive_Wait in RS232RX.LIB. Receive_Wait waitsfor a start bit and attempts to grab one serial character. It is important to note thatReceive_Wait does not return to the calling program until either a serial character isreceived, or a false Start bit occurs—indicating a glitch on the RS-232 line. If aserial error occurs, the Receive register is reset. The MOVF Receive,0 and BTFSCZ instructions checks for this zero condition and a return to Main executes if thereceive register is zero.

The two instructions of Receive_Wait simply wait for the RS-232 signal linedrop low. Receive_Data, which follows on the next page, samples the RS-232 data.

GOTO Initialize ;Jump over interrupt vector

ORG 05h ;Program starts after interrupt vec

Include �LCD.LIB� ;LCD subroutine libraryInclude �RS232RX.LIB� ;RS-232 receive library

Initialize ;Prepare character counters and LCD for data

MOVLW LCD_Length ;Load W with number of LCD characteMOVWF CharCounter ;and save in CharCounter then subtrDECF CharCounter ;1 to account for 0 position

MOVLW CursBlink ;Load W with constant to blink cursCALL LCD_Reg ;and write to LCD as a command

MOVLW LCDLine1 ;Load W with DDRAM address of lineMOVWF CharAddress ;and save in CharAddress variableCALL LCD_Reg ;before writing it to the LCD

Forty characters is thelength of the LCD DDRAMbuffer. See Chapter 12 formore information.

Main ;Receive serial characters in Receive buffer

CALL Receive_Wait ;Wait for and receive one serial by

MOVF Receive,0 ;After receiving, check character fBTFSC Z ;an error (Receive=00h)GOTO Main ;If no character, wait again

Receive_Wait ;Wait for PortA.4 to change from high to low indicating th;start of serial data.

BTFSC Serial_Input ;Check serial input pinGOTO Receive_Wait ;If high, wait for low

From RS232RX.LIB

Page 152: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code152

The first two instructions load the BitCounter variable with the number of databits that will be received—typically 8. Then, the BitDelay subroutine is called toprovide a delay of ½ bit time. The variable Half_Bit is defined in the Software Equatessection of RS-232RX.LIB. The PM assembler supports in-line math operators, mak-ing it easy to define Half_Bit from Bit_Time:

After returning from the BitDelay subroutine, the serial input pin is checkedagain to ensure that it is still low, signifying a valid Start bit. If not, the program goesto the Receive_Error subroutine.

Once a valid Start bit is received, BitDelay is called again with a full Bit_Timevalue in W. When BitDelay finishes, the PIC is ready to sample bit 0. The next fourlines sample Serial_Input and set or clear the Carry flag depending on the state of thepin defined by Serial_Input. These four lines always take four clock cycles to ex-ecute, regardless of the state of Serial_Input. This coding prevents cumulative timingerrors.

After the Carry flag has been set or cleared according to value sampled, RRFReceive rotates the Carry bit into the upper bit of the Receive register.

BitCounter keeps track of the bits remaining to be received. The process repeatsin a loop until BitCounter is zero and all eight bits have been received. After anotherBit_Time delay the Stop bit is sampled. The Receive_Wait subroutine returns unlessa Stop bit does not occur, in which case a receive error is generated.

Receive_Data ;After PortA.4 drops low, test for a start bit by delaying;for half the Bit_Time and then checking PortA.4 for the lo;start bit. Then wait for the Bit_Time and read each bit in;Carry. Rotate Carry into the Receive byte and repeat the;delay, Carry and rotate until eight DataBits have been;received. The Receive register stores the received byte. I;framing error occurs (only a simple check for a stop bit i;done) the contents of the Receive regsiter will be 00h and;the Receive_Data routine will return with 00h in W.

MOVLW DataBits ;Load W with number of data bitsMOVWF BitCounter ;and save in BitCounter registerMOVLW Half_Bit ;Load W with half of bit delay timeCALL BitDelay ;and wait for 1/2 bitBTFSC Serial_Input ;Check for low start bit againGOTO Receive_Error ;If high, error occurred-exit with

:Next_Bit MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until middle of next bitBTFSS Serial_Input ;Check serial input pin for 1BCF C ;If serial input is 0, clear CarryBTFSC Serial_Input ;Check serial input pin for 0BSF C ;If serial input is 1, set CarryRRF Receive ;Rotate Carry into received data byDECFSZ BitCounter ;Decrement bit counter & check forGOTO :Next_Bit ;If not 0, get the next bit

MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until middle of stop bitBTFSS Serial_Input ;Check for high stop bitGOTO Receive_Error ;If low, we have a framing errorRETURN ;Otherwise return

From RS232RX.LIB

Assigning the labelReceive_Data to a sectionof the Receive_Waitsubroutine makes it easierto adapt the RS232RX.LIBsubroutines for interrupts.The serial input pin RA.4can be configured togenerate an interrupt onthe falling edge of the RS-232 Start bit.

Bit_Time EQU 01Eh ;Serial Bit delay from table aboveHalf_Bit EQU Bit_Time/2 ;Half of the Bit delayFrom RS232RX.LIB

See Appendix C - PICMacro Assembler Refer-ence, Section 9, for moremath operators.

Receiving RS-232Data

Page 153: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

153Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

The Receive_Error section of the subroutine will execute if either the Start bit isnot low during its mid-point sample, or if the Stop bit is not high during its mid-pointsample. An invalid Start bit is probably due to induced noise on the RS-232 line,whereas an invalid Stop bit is probably due to incorrect baud rate or data lengthsettings. Either of these two conditions indicate that a framing error has occured andthat the received data is suspect. If this is the case, the receive buffer is cleared. Tocheck for an error, your program can check the Receive character for a zero onreturn.

After the Receive_Wait subroutine has received all eight bits of an RS-232 char-acter it places the received value into the Receive register. The LCD_Write section ofRECV232.ASM will display the character.

The first fifteen characters fill line one of the LCD. After the first fifteen charac-ters are sent to the LCD, each new character is followed by a command to scroll theLCD left so that the oldest characters scroll off the visible display. After forty char-acters, the LCD DDRAM buffer is full and must be reset to its starting value of 80h.The LCD_Write, Scroll, and Line_Reset subroutines perform these tasks.

LCD_Write moves the character from Receive to the W register and displays thecharacter by calling LCD_Data. INCF CharAddress keeps track of how many char-acters have been placed into the LCD DDRAM. Each line of the LCD has fortyDDRAM addresses and can hold forty characters. Remember from Chapter 12 thatthe first DDRAM location is 80h. After forty characters have been received anddisplayed, CharAddress will equal A8h. MOVLW 0A8h and SUBWF CharAddress,0checks that the DDRAM address is forty characters past 80h, at which point theLCD is reset to the start of DDRAM by GOTO Line_Reset.

Line_Reset scrolls the contents of the LCD left, and resets the DDRAM addressto 80h, so that it can again be filled with forty new characters.

We chose to return 00hbecause it’s easy to check.See the Main routine forthe error checking code.

LCD_Write ;Write the character in Receive buffer to LCD display

MOVF Receive,0 ;Move received character into W &CALL LCD_Data ;write to current DDRAM addressINCF CharAddress ;Add 1 to DDRAM address counterMOVLW 0A8h ;Load W with last DDRAM address +1SUBWF CharAddress,0 ;and subract from CharAddressBTFSC Z ;to see if 40 characters are fullGOTO Line_Reset ;If so, reset LCD to start of line

MOVF CharCounter,1 ;Check Character counter for endBTFSC Z ;of visible screen by checking ZGOTO Scroll ;If at end, scroll display leftDECF CharCounter ;If not, decrement CharCounterGOTO Main ;and wait for next character

Line_Reset ;If 40 characters have been written to DDRAM, scroll the;display contents left and reset DDRAM to line 1.

MOVLW LCDLeft ;Load W with LCD shift left commandCALL LCD_Reg ;and write to LCDMOVLW LCDLine1 ;Load W with first DDRAM addressMOVWF CharAddress ;and save in CharAddress registerCALL LCD_Reg ;before writing it to LCDGOTO Main ;Wait for more serial data

Page 154: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code154

If forty characters have not yet been displayed, the last five lines of LCD_Writedetermine whether or not to scroll the display. CharCounter keeps track of the re-maining character positions to be filled before scrolling is required. After the first 15characters, scrolling is required, CharCounter is 0, and Scroll executes for all subse-quent characters.

Transmitting RS-232 Data

Transmitting RS-232 data is relatively straightforward. As with RS-232 recep-tion, the bit time needs to be calculated from the serial bits per second rate. As shownin the diagram below, transmitting RS-232 signals involves setting a bit, waiting forthe bit time, sending the next bit, waiting, and so on until all bits have been sent:

The program XMIT232.ASM sends the message “Key XX Pressed” to the PIC-MDS serial output each time a key is pressed. XX is replaced by a number represent-ing the key pressed on the keypad. To test this program, connect the PIC-MDS to apersonal computer running a terminal program and make sure that JU5 is set to Tx.Use one of the serial cables described at the start of the chapter.

XMIT232.ASM uses three library files. KEYPAD.LIB scans the keypad andreturns a value from 1 to 16 representing which key was pressed—or 0 if no key waspressed. BIN2DEC.LIB is used to convert the value returned by KEYPAD.LIB tothree decimal digits.

Scroll ;Scroll display left to keep new characters in LCD window

MOVLW LCDLeft ;Load W with LCD shift left commandCALL LCD_Reg ;and send to LCDGOTO Main ;Wait for next character

Make sure your terminalprogram is set to receive at9600 bps, 8 data bits, noparity and 1 stop bit—8n1.

;Equates required by BIN2DEC.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Equates required by KEYPAD.LIB:Key DS 1 ;Key return code register

;Equates required by RS232TX.LIB:Counter DS 1 ;Serial bit delay counterBitCounter DS 1 ;RS232 bit counter registerTransmit DS 1 ;Transmit byte storage register

See Chapter 9 for moredetails on KEYPAD.LIBand BIN2DEC.LIB.

Transmitting RS-232Data

Page 155: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

155Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

RS232TX.LIB requires three variables. Counter is used to generate bit timedelays, BitCounter counts tranmitted bits, and Transmit is a register that holds thebyte to be transmitted.

XMIT232.ASM begins by calling Transmit_Port in the RS232TX.LIB libraryto initialize RA.4 as an output. Next, the call to KB_Port in KEYPAD.LIB initializesPort B to scan the keypad. GOTO Get_Key jumps over the interrupt vector and thelibrary include statements.

Similar to Receive_Port in RS232RX.LIB, Transmit_Port sets PortA.4 to out-put without modifying the settings of the other Port A pins. This is accomplished byANDing Port A with 00001111b.

The Get_Key routine uses KB_Scan to scan the keypad until a key is pressed.Once a key has been pressed, CALL Delay waits for the key to settle before anothercall to KB_Scan captures the key value. Since KB_Scan returns the key pressedvalue in the Key register, MOVF Key,0 copies the key code into W. The call toBin_Dec converts the binary key code into three decimal digits which are stored inthe registers Hundreds, Tens and Ones.

By adding 30h to the Tens and Ones registers, the numeric values stored in themare converted to their corresponding ASCII characters. This is done so that ASCIIcharacters, not binary numbers, are transmitted to the receiving serial terminal.

CALL Transmit_Port ;Configure PortA.4 as serial outputCALL KB_Port ;Configure Port B for keypad scanniGOTO Get_Key ;Jump over interrupt vector

Transmit_Port ;Sets PORTA.4 to output. Make sure PIC-MDS JU5 is set to T

BSF RP0 ;Select memory register page 1MOVLW 00001111b ;AND configuration byte with Port AANDWF TRISA ;tristate reg. to make RA.4 an outpBCF RP0 ;Return to memory register page 0BSF Serial_Output ;Set serial line highRETURN From RS232TX.LIB

Get_Key ;Wait for a key stroke, debounce it and convert it to thre;decimal digits.

CALL KB_Scan ;Get Key return codeMOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try again

CALL Delay ;Wait for key to settleCALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Bin_Dec ;and convert to decimal

Convert_ASCII ;Add 30h to offset the BCD numbers into ASCII.

MOVLW 30h ;Load ASCII offset into W andADDWF Tens ;add to Tens andADDWF Ones ;Ones registers to make ASCII numbe

Page 156: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code156

The Transmit_Key routine relies on Transmit_Data in RS232TX.LIB to sendcharacters for the word “Key ”. The ASCII value for each letter is generated by theassembler when the letter is enclosed in quote marks.

Transmit_Data begins by moving the character in W to the Transmit register.Next, the number of data bits to be transmitted is saved in the BitCounter register andthe serial output pin is set low to initiate the Start bit. The seven NOP instructionsadd a short time delay and are followed by a call to BitDelay in the :Next_Bit subrou-tine. BitDelay holds the Start bit low for one bit time. These NOPs plus the BitDelaysubroutine form the exact delay required for one bit.

The remainder of the :Next_Bit subroutine rotates the Transmit register right,cycling each bit into the Carry flag. The next four lines check Carry and set or clearthe Serial_Output pin depending on the state of Carry. These four lines always takefour clock cycles to execute, regardless of the state of Serial_Input. This codingprevents cumulative timing errors.

Transmit_Key ;Transmit the word �Key �

MOVLW �K� ;Load W with ASCII code for �K� andCALL Transmit_Data ;send out of serial port

MOVLW �e� ;Load W with ASCII code for �e� andCALL Transmit_Data ;send out of serial port

MOVLW �y� ;Load W with ASCII code for �y� andCALL Transmit_Data ;send out of serial port

MOVLW � � ;Load W with ASCII code for � � andCALL Transmit_Data ;send out of serial port

Transmit_Data Drop PortA.4 from high to low to indicate the Start Bit a;delay for one Bit_Time. Rotate the Transmit buffer right;into Carry and set or clear the serial output pin based on;Carry. Wait for another bit time and continue rotating and;transmitting until all eight bits have been sent. Finally,;send a stop bit.

MOVWF Transmit ;Save character in W to bufferMOVLW DataBits ;Load W with number of data bitsMOVWF BitCounter ;and save in BitCounter regsiterBCF Serial_Output ;Send Start bitNOP ;and pad routine to be same lengthNOP ;as :Next_Bit code so Bit_Time isNOP ;accurateNOPNOPNOPNOP

:Next_Bit MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait one bit durationRRF Transmit ;Rotate Transmit byte into CBTFSS C ;Check Carry for a 1BCF Serial_Output ;If C=0, clear serial outputBTFSC C ;Check Carry for a 0BSF Serial_Output ;If C=1, set serial outputDECFSZ BitCounter ;Decrement bit counter & check forGOTO :Next_Bit ;If not 0, get the next bit

MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until end of last bitBSF Serial_Output ;Set serial line high for Stop bitMOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait a bitRETURN

Transmitting RS-232Data

Page 157: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

157Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

DECFSZ BitCounter keeps track of how many bits have been transmitted andrepeats the :Next_Bit routine until BitCounter is zero. The next call to BitDelayholds the last data bit for one bit time. BSF Serial_Output sets the output pin high togenerate the Stop bit and the final call to BitDelay holds the Stop bit for just underone bit time.

Notice that NOPs are not needed to pad the Stop bit. Returning from theTransmit_Data routine, loading a new character into W, and calling Transmit_Dataagain takes five processor clock cycles—equivalent to 5 NOPs—and the Start bit isnot sent until after the fourth instruction in Transmit_Data. In total, this adds a nineclock delay to the BitDelay routine. When sending characters sequentially this pro-duces a Stop bit slightly longer than one bit time, allowing close to the maximumpossible serial throughput.

Once the letters “Key ” have been sent to your serial terminal, Transmit_Numsends the key code previously saved in the Tens and Ones registers.

Finally, Transmit_Mesg reads the Message data table to send the word “ Pressed”as well as a carriage return and line feed to the serial device attached to the PIC-MDS. CharCounter keeps track of the data table offset, and the end of Message ismarked by a zero byte. When the end of message zero byte is read from the datatable, BTFSC Z causes GOTO Wait to execute instead of being skipped.

The Wait routine loops until the key is released, indicated by Key being returnedas zero, and the subsequent delay ensures that any bounces on key release are ig-nored. After the delay, the program is ready to transmit the next key press.

Remember, Databits is usedto set BitCounter to thenumber of bits to betransmitted —typically 8.

Transmit_Num ;Transmit the two key return code ASCII digits.

MOVF Tens,0 ;Load W with ASCII Tens digit andCALL Transmit_Data ;send out of serial portMOVF Ones,0 ;Load W with ASCII Ones digit andCALL Transmit_Data ;send out of serial port

Transmit_Mesg ;Transmit the word � Pressed�, followed by the character;codes for carriage return (13) and line feed (10).

CLRF CharCounter ;Clear message character counterGet_Char MOVF CharCounter,0 ;Get current character count in W

CALL Message ;and retrieve message characterMOVWF Transmit ;Store returned character in TransmMOVF Transmit,1 ;and check transmit for end ofBTFSC Z ;message marker by checking ZGOTO Wait ;If message done, wait for key releCALL Transmit_Data ;If not, send current characterINCF CharCounter ;Increment the character counterGOTO Get_Char ;and get the next character

Data table reads were firstdescribed in Chapter 12.

Wait ;Wait until the user releases the pressed key.

CALL KB_Scan ;Scan keypadMOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has been releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay ;Wait for key to settleGOTO Get_Key ;Wait for next key

Page 158: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code158

Chapter Summary

RS-232 serial communication is a common way to transmit data between de-vices. Serial data is assembled into data frames consisting of one Start bit, the data,and one or more Stop bits. Serial data is transmitted sequentially at one of a numberof common bit rates, and usually as a reverse-logic, bipolar signal. Serial transcieverssuch as the MAX232 on the PIC-MDS automatically convert these signals to andfrom TTL logic levels.

The RS232RX.LIB and RS232TX.LIB progams implement simple serial recep-tion and transmission without handshaking. For a complete discussion of RS-232communications refer to the latest EIA RS-232 standard publication, or textbooksdealing with serial communication systems.

Chapter Summary

Page 159: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

159Chapter 15 RS-232

Serial Communication©1998 Sirius MicroSystems Microchip Code

Questions

1. What are the common serial bps rates?

2. In TTL levels, why is the Start bit always low?

3. Why does RS232RX.LIB sample the RS-232 input in the middle of a bit time?

4. You have designed a pressure monitoring sensor which must transmit 8 bits ofpressure data to a computer every 1 ms. What is the minimum common bpsrate needed.

5. How does RS232RX.LIB need to be modified if the MAX232 transciever isnot used. That is, assume the PIC is directly connected to the transmitting RS-232 device through a series resistor.

Assignment

1. Write a program to transmit a message repeatedly to a serial terminal at a bpsrate other than 9600 bps. Make sure that your message begins on a new lineeach time it is transmitted.

2. Write a program that will illuminate each of the eight LEDs in response to aunique ASCII character. For example, sending a “1” could light the LED onRB0.

3. Create a program that uses interrupts to receive RS-232 data. Use the negativegoing edge of the Start bit to initiate the interrupt.

4. Wire a 10kW ohm resistor in series with the serial output wire of a terminal toan available port pin on the PIC. Write a program that will use this pin toreceive serial characters, modify them by adding 1, and retransmit the modi-fied character back to the terminal forming a simple data encryption system.

Page 160: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius MicroSystemsMicrochip Code160Notes

Page 161: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 161Chapter 16

A/D Conversion

16 A/D Conversion

Up until this chapter, we’ve dealt with interfacing to binary digital devices. Ourworld, however, is an analog place where quantities such as voltage, liquid-level, ortemperature don’t have clearly defined points. In order to measure and work withanalog quantities in the PIC, they must first be converted to digital numbers. Ana-log-to-digital (A/D) conversion circuits add a whole new dimension to microcontrollerapplications. A microcontroller with an internal A/D converter can sense heat, light,sound level, position, resistance, voltage, current, or many other real-world signals.

The PIC16C711 is equipped with an internal 8-bit, 4-channel A/D converterthat allows it to convert an externally applied voltage between 0V and 5V into aneight-bit number from 00h to FFh. Using the PIC16C711 costs less than interfacingan external A/D converter to a microcontroller without an A/D such as the PIC16F84.The PIC16C711 with its built-in A/D converter also provides savings in code size,circuit board real-estate, and assembly costs.

This chapter will explore how to read, scale and display multiple analog voltagesset via the trim pots RA0 and RA1. Analog voltages received from these pots will bedisplayed on the LCD as numbers from 0 to 255. One channel will be converted to anumeric voltage and the other will be displayed as a bar graph on the LED display.

The PIC16C711 A/D Converter

The PIC16C711 has only one A/D converter that is multiplexed to four I/O lineson Port A as shown below:

One of the four analoginputs can be used as anexternal reference voltage(Vref), changing theconversion range to 0V andVref instead of 0V and 5V,effectively scaling theanalog conversion.

The channel select bits(CHS[1:0]) are part of theADCON0 (08h) register,and the port configurationbits (PCFG[1:0]) are partof the ADCON1 (88h)register.

Page 162: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code162

ADCON0 Register

The two channel select bits CHS1 and CHS0 are part of the ADCON0 (A/Dcontrol 0, address 08h) register and control which PIC I/O pin is connected to theinternal A/D converter. The other bits of the ADCON0 register are shown below:

The A/D converter is a successive approximation type and uses 10 clock cyclesto complete one conversion. Each conversion clock must take at least 2.0 ms andshould take no more than about 8 ms for best accuracy. The A/D converter clockselect bits (ADCS1 and ADCS0) select clock rate fed to the A/D converter. Theclock rate can be divided from the oscillator clock in increments of 2, 8 or 32, or befed from an internal RC oscillator as shown in the chart below:

In our example program, ADCS1 and ADCS0 are set to 10, providing a clockdivider of 32. Using a 10 MHz clock oscillator, we can calculate an appropriateclock source as shown:

The ADON bit can be used turn the A/D converter on or off. When the A/Dconverter is off, power is removed from the A/D converter circuitry, lowering thePIC’s current consumption. The A/D converter must be turned on, by setting ADON,before initiating a conversion.

The GO/~DONE bit start the conversion process and also indicates its comple-tion. Setting GO/~DONE starts the conversion, and this bit will remain high duringconversion. When the conversion is complete, GO/~DONE drops to zero.

ADIF is the A/D conversion complete interrupt flag bit. It gets set when theconversion is finished and must be cleared in software. Interrupt-driven operationallows the A/D conversion to take place in the background, or while the processor isasleep if RCOSC is set as the clock source. The A/D interrupt caused by the comple-tion of the A/D conversion will wake the processor from sleep.

The input sample is held onan internal hold capacitorduring conversion. Theminimum and maximumconversion clock timesensure that the holdcapacitor has had sufficienttime to fully charge beforeconversion and that thecharge does not leak offduring conversion.

ecruoSkcolC 0,1SCDA

T2 CSO 00

T8 CSO 10

T23 CSO 01

CSOCR 11

Do not set the GO/~DONEbit in the same instructionthat sets ADON.

ADCON0 Register

Page 163: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 163Chapter 16

A/D Conversion

ADCON1 Register

ADCON1 contains the two port configuration bits which select not only theinternal or external reference voltage, but also whether Port A inputs are analog ordigital. By default, Port A.0-3 pins are set to analog input on power-up. When usingthe LCD or Serial EEPROM library routines with the PIC16C711 it is important toexplicitly set the port configuration bits to digital mode. Note that this is not neces-sary when using the PIC16F84, as Port A can only be digital. The table below showshow PCFG1,0 set Port A pins to analog or digital and select the analog reference aseither VDD or an external reference applied to RA.3.

Measuring Voltage using the A/D Converter

The VMETER.ASM program uses the PIC16C711 as a voltmeter to measureand display the voltage supplied by potentiometers RA.0 and RA.1. VDD is used asVREF, the analog reference voltage.

For any voltage from 0V to 5V the binary value will be a corresponding numberfrom 00h to FFh, or from 0 to 255. VMETER.ASM displays the raw binary datameasured from each channel on line 1 of the LCD. Since most applications requiremore than just a raw number, VMETER.ASM demonstrates two methods of scaling.First, the RA.0 voltage is scaled in software from 0.00 to 5.00 and displayed on theLCD, representing the actual voltage from 0V to 5V. Second, the RA.1 voltage isscaled and is displayed as an 8-step bar graph on the LEDs.

Pull out the VMETER.ASM code as we examine it in detail.

The Hardware Equates section begins by setting aside memory locations neededby the included libraries and variables in VMETER.ASM. Of note are the equatesfor BIN2BCD.LIB.

0,1GFCP 0.AR 1.AR 2.AR 3.AR FER

00 golanA golanA golanA golanA V DD

10 golanA golanA golanA V FER 3.AR

01 golanA golanA latigiD latigiD V DD

11 latigiD latigiD latigiD latigiD V DD

A voltmeter to connected tomeasure the voltage ofRA.0 or RA.1 will not showthe same value as on thedisplay. RA.0 and RA.1serve double-duty as bothanalog inputs and asdigital outputs for the LCD.The meter will measure theaverage of the analog anddigital signals on thesepins.

;Equates used by BIN2BCD.LIB

HighByte DS 1 ;High byte of numberLowByte DS 1 ;Low byte of number

TenThous DS 1 ;Ten thousands BCD digitThouHund DS 1 ;Thousands & Hundreds BCD digitTensOnes DS 1 ;Tens and Ones BCD digitShiftCounter DS 1 ;Counter for BCD conversion shifts

The external referencevoltage applied to VREF

should be within 3V and 5V.For best accuracy, connecta dedicated voltagereference to this pin, notjust a resistor voltagedivider.

Page 164: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code164

BIN2BCD.LIB converts a 16-bit binary number (stored in the two registersHIGHBYTE and LOWBYTE) into a 5-digit BCD number. This 5-digit number isstored in three locations: TenThous, ThouHund, and TensOnes. The lower 4 bits(lower nybble) of TensOnes contains the least significant BCD digit, the upper nybblecontains the next most significant digit, and so on for ThouHund, and TenThous.

The Software Equates section defines constants that are used in the program.

Initialization begins at address 0000h and continues after the included libraryfiles. The LCD71.LIB subroutine library makes its first appearance here. Rememberthat the PIC16C711 powers up with Port A in analog input mode. LCD71.LIB is avariant of LCD.LIB where the LCD_Port subroutine configures Port A for digitaloutput. The Initialize routine continues by displaying static text on the LCD.

Main begins by calling the AD_Port initialization subroutine in ATOD.LIB.

AD_Port first sets RA.0 and RA.1 as input pins by ORing the literal 00000011bwith TRISA. Now that RA.0 and RA.1 are inputs, the MOVLW 02h into ADCON1sets RA.0 and RA.1 as analog inputs. Notice that these two steps set only RA.0 andRA.1 as analog inputs—the other Port A bits are left unchanged in case they werepreviously set as digital I/O. Finally, BSF ADON turns on the A/D converter inpreparation for a conversion.

The MOVLW ADLCK32 and CALL AD_Clock instructions load the clock di-vider selection bits ADCS0 and ADCS1. ATOD.LIB equates ADCLK2, ADCLK8,ADCLK32 and ADCLKRC to 2TOSC, 8TOSC, 32TOSC and RCOSC, respectively.

BIN2DEC.LIB convertedan 8-bit binary number intothree separate BCD digits.BIN2BCD.LIB converts a16-bit number into fiveBCD digits. BIN2BCD.LIBis used here becauseVMETER.SRC works withvalues larger than 8 bitswhen scaling voltages.

Main ;Configures A-D converter by initializing Port A to be;analogue intsead of digital, setting the clock divider,;and selecting the A-D channel.

CALL AD_Port ;Initialize A-D converter & Port A

AD_Port ;Initializes ADCON1 for analog input on RA0 and RA1 with;VDD as the voltage reference and turns A/D converter on.

BSF RP0 ;Select memory page 1MOVLW 00000011b ;OR this byte with TRISA to enableIORWF TRISA ;required analog pins as inputsMOVLW 02h ;Make RA0 and RA1 analog inputs byMOVWF ADCON1 ;writing this byte to ADCON1 (88h)BCF RP0 ;Back to page 0BSF ADON ;Turn A/D converter onRETURN

From ATOD.LIB

ATOD.LIB does not turn offthe A/D converter. For lowcurrent consumption youmay wish to turn the A/Doff after the conversion iscomplete (just remember toturn it on again for the nextconversion).

MOVLW ADCLK32 ;Get clock divider for high speedCALL AD_Clock ;from ATOD.lib and set A-D

AD_Clock ;Sets ACDS0 and ADCS1 bits in ADCON0 based on the number;in W. Load W with a clock divider constant from the;list, above. Read ADRES before calling AD_Clock.

MOVWF ADRES ;Use ADRES as temporary storageMOVLW 3Fh ;Load W with 0011 1111ANDWF ADCON0,1 ;AND with ADCON0 to clear high bitsMOVF ADRES,0 ;Get clock divider bits from ADRESIORWF ADCON0,1 ;OR with ADCON0 to set clock bitsRETURNFrom ATOD.LIB

Measuring Voltageusing the A/D

Page 165: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 165Chapter 16

A/D Conversion

The AD_Clock subroutine uses the A/D conversion result register, ADRES (09h),as a temporary register to store the clock divisor constant that was held in W whenAD_Clock subroutine was called. The W register is then available for the ANDLW3Fh operation that is needed to clear the ADCS0 and ADCS1 bits without affectingthe lower six bits. After clearing the two ADCS bits W is reloaded with the clockdivisor from ADRES before the IORWF ADCON0,1 operation which copies theADCLK32 constant into the ADCS0 and ADCS1 bits without corrupting the bottomsix bits in ADCON0. By using ADRES for temporary storage, the ATOD.LIB rou-tines use none of the standard RAM registers (0Ch to 2Fh) as variables.

Since we would like the first A/D conversion to retrieve the voltage supplied byRA.0, MOVLW ADCH0 and CALL AD_Channel select channel 0 as the A/D input.

Once again, ADRES is used to store W while an AND operation clears theCHS0 and CHS1 bits in ADCON0. After the contents of ADRES are reloaded intoW, they are ORed with ADCON0 to set the requested A/D channel. ATOD.LIBpredefines ADCH0, ADCH1, ADCH2 and ADCH3 as valid A/D inputs.

By this point, the A/D inputs have been configured, the A/D clock divisor hasbeen selected and the A/D channel has been chosen. Instead of initiating an A/Dconversion, the program first moves the contents of the Bargraph register to Port Band then calls a 5 ms delay routine. There are two reasons that this was done.

First, since Port B is shared with the LCD, LED flicker occurs whenever theLCD is accessed. In order to minimize LED flicker, writing the Bargraph value tothe LED before the CALL to Delay_5ms ensures that the LEDs will display undis-turbed for 5 ms. Second, the PIC-MDS has a 1kW resistor in series with thepotentiometers connected to RA.0 and RA.1. These resistors reduce the effects ofthe potentiometers RA0 and RA1 on Port A when it is used as a digital I/O port.Unfortunately, the resistors also increase the time constant of the internal hold ca-pacitor, increasing the time required to charge the capacitor to the input voltage. The5 ms delay (part of LCD71.LIB) provides more than enough time to charge the holdcapacitor, and is a convenient delay.

When the conversion isfinished, be sure to read thecontents of ADRES beforecalling the AD_Clock orAD_Channel subroutines.Both of these subroutinesuse ADRES for temporarystorage and will wipe outyour conversion result.

MOVLW ADCH0 ;Get channel 0 constant andCALL AD_Channel ;set A-D channel

AD_Channel ;Sets CHS0 and CHS1 bits in ADCON0 based on the number in;W when AD_Channel was called. Load W from channel constants;list, above. Read ADRES before calling AD_Channel.

MOVWF ADRES ;Use ADRES as temporary storageMOVLW 11100111b ;Load W with 1110 0111 andANDWF ADCON0,1 ;AND with ADCON0 to clear CHS0/1MOVF ADRES,0 ;Get channel select bits from ADRESIORWF ADCON0,1 ;OR with ADCON0 to set channel bitsRETURN From ATOD.LIB

MOVF Bargraph,W ;Display Bargraph value on LEDs whileMOVWF PORTB ;waiting for next conversion

Call Delay_5ms ;Wait for track & hold to settleCALL AD_Poll ;Start conversion, & wait until doneMOVF ADRES,W ;Load conversion result into W andMOVWF Analog0 ;save in Analog0 for voltage display

ADRES in the ’711 alongwith EEDATA and EEADRin the ’84 can be used asgeneral purpose RAMregisters.

The first time the Mainroutine runs, Bargraphcontains 00h. Subsequentloops through main willdisplay the bargraph valueequivalent to RA.1’ssetting.

Page 166: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code166

Once the 5 ms delay finishes, the CALL to AD_Poll initiates the conversion.

AD_Poll sets the GO/~DONE bit in ADCON0, and repeatedly loops until itgoes low approximately 3.2 ms later. When GO/~DONE goes low, the conversionresult is available in ADRES (09h).

For interrupt-driven operation you would only need to set the GO/~DONE bitafter enabling A/D interrupts (see Chapter 11). When the conversion is done, theADIF flag in ADCON0 is set, and your interrupt service routine can take over.

On return to VMETER.ASM, the result in ADRES is immediately stored inAnalog0 for later processing. Then channel 1 is sampled in the same way as channel0 using the following code.

After both channels have been sampled, the following code displays the rawvalue of channel 0 on the LCD.

First, the CALL to LCD_Port (in LCD71.LIB) reconfigures the analog inputpins on Port A to digital output pins in order to provide the LCD control signals.MOVLW LCDLine1+Ch0_Data loads W with the LCD line 1 starting DDRAMlocation and offsets it by the Ch0_Data software equate at the start of this program.This ensures that any LCD data is displayed after the “Ch0:” text.

After the CALL to LCD_Reg, the LED bar graph on Port B reflects the lastnumber sent to the LCD. The subsequent MOVF Bargraph,W and MOVWF PORTBrewrites the last Bargraph value to the LEDs.

Next, the value in Analog0 needs to be converted to three ASCII digits for dis-play. After moving Analog0 to the LowByte register, the CALL to Display_Numconverts the raw 8-bit result to ASCII and displays it on the LCD.

AD_Poll ;Sets GO_DONE bit in ADCON0 to start the A/D conversion;and keeps polling the bit until the conversion is;complete. Get the result of the conversion from ADRES.

BSF GO_DONE ;Start A/D conversion:Loop BTFSC GO_DONE ;Check GO_DONE for end of conversion

GOTO :Loop ;and keep checking until doneRETURNFrom ATOD.LIB

MOVLW ADCH1 ;Get channel 1 constant andCALL AD_Channel ;set A-D channelMOVF Bargraph,W ;Display Bargraph value on LEDs whileMOVWF PORTB ;waiting for next conversion

CALL Delay_5ms ;Wait for track & hold to settleCALL AD_Poll ;Start conversion, & wait until doneMOVF ADRES,W ;Load conversion result into W andMOVWF Analog1 ;save in Analog1

CALL LCD_Port ;Reconfigure Ports for LCD useMOVLW LCDLine1+Ch0_Data ;Send channel 0 data startingCALL LCD_Reg ;address to LCD as a commandMOVF Bargraph,W ;Display Bargraph value on LEDs whileMOVWF PORTB ;waiting for bcd conversionMOVF Analog0,W ;Load channel 0 result into W andMOVWF LowByte ;save into LowByte registerCALL Display_Num ;Let Display_Num display BCD digits

Measuring Voltageusing the A/D

Page 167: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 167Chapter 16

A/D Conversion

Before calling BIN_BCD (in BIN2BCD.LIB) the Display_Num subroutine clearsHighByte. As mentioned previously, BIN_BCD converts the 16-bit word stored inthe HighByte and LowByte registers into five BCD digits—necessary to representnumbers up to 65,535. Since we only need 8-bit quantities to represent the A/Dresult (0-255) we need to ensure that HighByte is clear. Later on, a call to BIN_BCDdoes put numbers into HighByte.

Once the conversion to BCD is complete, each of the three least significantdigits—hundreds, tens and ones—is processed in the same way. First, the BCD digitis extracted from the byte using an AND operation. For the Hundreds digit, stored inthe lower nybble of ThouHund, ANDLW 0Fh clears the upper nybble leaving justthe number of hundreds. Next, ADDLW 30h adds the ASCII offset to the number toconvert it to an ASCI code and finally, CALL LCD_Data displays the digit at thecurrent LCD DDRAM address. The routine returns control to Main once all threedigits have been displayed.

The next section of Main repeats the above process to display the raw channel 1conversion result on the LCD.

The code above displays the result of the channel 0 conversion as a voltage.This subroutine is very much like the routines that prepare the LCD to display theraw channel data. The LCD DDRAM address is loaded, and Bargraph updates theLEDs to overwrite the LCD command that would otherwise remain displayed on theLEDs. The CALL to Scale_Voltage converts the 0-255 result into a 0V - 5V value asshown in the source code on the next page.

Display_Num ;Converts the 8-bit A/D result to BCD and displays the;hundreds, tens and ones digits on the LCD at the current;LCD cursor address.

CLRF HighByte ;Clear HighByte before convertingCALL BIN_BCD ;result to BCDMOVF ThouHund,W ;Load thousands & hundreds digits inANDLW 0Fh ;W and clear thousands nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDSWAPF TensOnes,W ;Load tens & ones digit in reverseANDLW 0Fh ;and clear ones nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDMOVF TensOnes,W ;Load tens and ones digits inANDLW 0Fh ;W and clear tens nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDRETURN ;Return when done

MOVLW LCDLine1+Ch1_Data ;Send channel 1 data startingCALL LCD_Reg ;address to LCD as a commandMOVF Bargraph,W ;Display Bargraph value on LEDs whileMOVWF PORTB ;waiting for bcd conversionMOVF Analog1,W ;Load channel 1 result into W andMOVWF LowByte ;save into LowByte registerCALL Display_Num ;Let Display_Num display BCD digits

MOVLW LCDLine2+Ch0_Volts ;Send channel 0 voltage startingCALL LCD_Reg ;address to LCD as a commandMOVF Bargraph,W ;Display Bargraph value on LEDs whileMOVWF PORTB ;waiting for scalingCALL Scale_Voltage ;Convert Ch.0 result to voltage andCALL Display_Volts ;display the result on the LCD

SWAPF TensOnes,W notonly swaps the high andlow nybbles, but also loadsthe result into W.

Page 168: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code168

A value that varies from 0 to 250 is easier to work with than a value that variesfrom 0 to 255. Simply subtracting 5 from any conversion result limits the maximumvalue to 250, but introduces very large errors for small results. For example, for aconversion result of 10, subtracting 5 results in a 50% error. Obviously, for results of5 or less, the error would be unacceptably large. However, if we distribute the sub-traction as five individual subtractions of 1, spread out over the range of possiblevalues, we can limit the error to no more than 2%. The Scale_Voltage routinesequentially subtracts one from the conversion result for every multiple of 50 thatthe result contains (see the flowchart in the left margin).

Scale_Voltage starts by moving the analog result into W. SUBLW 250 subtractsW from 250 and clears C (the Carry/Borrow flag) if a borrow occurred. For exam-ple, if W was 255, the subtraction would require a borrow, and C would be cleared.BTFSS C checks the state of the Carry/Borrow flag and causes the DECF Analog0instruction to execute whenever a borrow occurs, subtracting one from Analog0.MOVF Analog0,W starts the same process again but with W being compared to200. In this way, any result over a multiple of 50 has one subtraction performed foreach multiple of 50. To see the subtraction take place, examine the LCD as you runVMETER.ASM. Turn the RA.0 potentiometer so that the raw data is less than 50,and slowly increase the potential on RA.0 watching the voltage on the LCD. Foreach increase in the raw data, the voltage increases by 0.02V. As you reach 50, thevoltage display is 1.00V. Increasing RA.0 to 51, the voltage still reads 1.00V, sincea subtraction has taken place. By further increasing RA.0 and you will be able to seethe subtraction take place at result values of 100, 150, 200 and 250.

Scale_Voltage ;Scales the result of the A/D conversion such that there are;only 251 states instead of 256. This way the result can be;multiplied by two to give a result from 0 to 500 representi;a voltage of between 0.00 and 5.00 volts. For display, a;decimal point is just inserted after the first digit by the;Display_Volts subroutine.

MOVF Analog0,W ;Load W with the A/D result andSUBLW 250 ;check if it�s greater than 225 byBTFSS C ;testing the Carry flagDECF Analog0 ;If so, subtract one from the resultMOVF Analog0,W ;Repeat the above process, comparingSUBLW 200 ;the A/D result with successivelyBTFSS C ;smaller valuesDECF Analog0MOVF Analog0,WSUBLW 150BTFSS CDECF Analog0MOVF Analog0,WSUBLW 100BTFSS CDECF Analog0MOVF Analog0,WSUBLW 50BTFSS CDECF Analog0

CLRF HighByte ;Clear HighByte register for multiplyMOVF Analog0,W ;Reload W with scaled result andMOVWF LowByte ;save result in LowByte registerBCF C ;Clear Carry before multiplying by 2RLF LowByte ;Shift LowByte left to multiplyRLF HighByte ;Shift Carry into HighByteCALL BIN_BCD ;and convert to BCDRETURN ;Return when done

This is one way to scale avoltage from a range of 0-255 to a range of 0-250.For more accuracy, youcan supply a calibratedreference voltage to RA.3(VREF) and configure theA/D to accept an externalVREF.

Measuring Voltageusing the A/D

Page 169: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 169Chapter 16

A/D Conversion

To complete the scaling to 5V, the analog result (0-250) is copied into LowByteand multiplied by two using the RLF LowByte instruction. The following RLFHighByte instruction rotates the C flag—containing LowByte’s most significant bitbefore its rotate—into HighByte in preparation for the conversion to BCD. Thecontents of HighByte and Lowbyte now hold a 9-bit number that ranges from 0 to500. To display the calculated voltage, the Display_Volts routine inserts a decimalpoint after the hundreds digit of the BCD result.

The Display_Volts routine works in the same way as Display_Num, other thanadding a decimal after the first number, and the letter ‘V’ after the last number.Adding ASCII characters is as easy as enclosing them in quotation marks. The as-sembler converts the letter within the quotes to its ASCII value for display.

The next part of the Main routine displays the RA.1 input as a bargraph. To dothis, the 8-bit conversion result is repeatedly divided by two in order to produce a 3-bit number. Since three bits corresponds to eight binary states, the three bit numberis used to light each of the eight LEDs according to a look-up table in Bar_Table.

The successive RRF Analog1 operations, above, perform the division by two.Since rotate operations are circular, and rotate bits through C and back into theregister, MOVLW 07h and ANDWF Analog1,W are required to clear the upper fivebits of Analog 1 before calling Bar_Table. In Bar_Table, an ADDWF PCL instruc-tion uses the 3-bit conversion result to offset the program counter, returning a con-stant that illuminates the appropriate segments of the LED bar.

Display_Volts ;Displays the result of the BCD scaled voltage as a decimal;number at the current LCD cursor address.

MOVF ThouHund,W ;Load thousands & hundreds digits inANDLW 0Fh ;W and clear thousands nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDMOVLW �.� ;Load W with ASCII code for �.�CALL LCD_Data ;and display on LCDSWAPF TensOnes,W ;Load tens & ones digit in reverseANDLW 0Fh ;and clear ones nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDMOVF TensOnes,W ;Load tens and ones digits inANDLW 0Fh ;W and clear tens nybbleADDLW 30h ;Add ASCII offset to generate numberCALL LCD_Data ;and display on LCDMOVLW �V� ;Load W with ASCII code for �V�CALL LCD_Data ;and display on LCDRETURN ;Return when done

RRF Analog1 ;Divide channel 1 result by 2RRF Analog1 ;again = divide by 4RRF Analog1 ;again = divide by 8RRF Analog1 ;again = divide by 16RRF Analog1 ;again = divide by 32MOVLW 07h ;Clear upper 5 bits of result byANDWF Analog1,W ;ANDing with zero, leave 3 bit resultCALL Bar_Table ;in W to look up 1 of 8 patterns

Bar_Table ADDWF PCL ;PCL=PCL+W to generate offsetRETLW 10000000b ;Bottom LED onRETLW 11000000b ;Bottom 2 LEDs ...

Like the Scale_Voltagesubroutine, the repeateddivision by two results in adecrease in conversionaccuracy. In this case theaccuracy decreases from 1part in 256 to 1 part in 8.

Page 170: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code170

Finally, after copying the LED bar graph constant to Port B, the bar graph con-stant is copied to the BarGraph register. As shown earlier, the BarGraph registerrefreshes the LEDs with the correct LED pattern after the LCD routine writes to PortB. Remember, the LEDs display all Port B activity and we try to minimize LEDflicker by overwriting the LCD commands as soon as possible.

Before the Main routine loops back to the beginning, there is a CALL toAD_Delay. This extra 25 ms delay gives the LCD some time to settle, and helps tominimize LED flicker.

Chapter Summary

Analog-to-digital conversion allows microcontrollers to measure and controlreal-world applications that supply a varying voltage to the processor. The A/D con-verter in the PIC16C711 will convert any voltage into an 8-bit number within two toeight microseconds. Up to four analog sources can be connected to Port A of thePIC16C711, and the single internal A/D converter can process the voltage on eachchannel independently.

For many uses, scaling is required to convert the A/D result into a more usefulform. Scaling usually results in a loss of conversion accuracy, which is typically notcritical for simple control tasks. Supplying the A/D converter with an external preci-sion reference voltage can eliminate the need for software scaling, improving con-version accuracy.

In the PIC-MDS, the Port A pins are shared between digital and analog devices.Resistors isolate the analog potentiometers from Port A, increasing the time con-stant required to charge the internal A/D hold capacitor. For high speed conversions,it is necessary to design a board that dedicates the Port A pins to the analog devicesconnected to them.

Although this chapter certainly gives you a start on A/D conversion, many vari-ables can affect the quality of a conversion result. Fortunately, there are many goodbooks and articles available that provide a more thorough look at A/D conversion.

Measuring Voltageusing the A/D

MOVWF PORTB ;Output LED pattern to LED barMOVWF Bargraph ;and to Bargraph register for update

CALL AD_Delay ;Wait to minimize display flickerGOTO Main ;and do it again

Page 171: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 171Chapter 16

A/D Conversion

Questions

1. What is the percentage accuracy of an 8-bit conversion? How does this com-pare to the percentage accuracy of a 4-bit conversion?

2. List the steps necessary to initialize the PIC16C711 for conversion with anexternal VREF. If only one analog input is required, can the remaining Port Apins be used as digital I/Os?

3. How would the use of a 4 MHz crystal affect the operation of the A/D con-verter? What about a 1 MHz crystal?

4. Calculate the maximum possible sampling frequency for a software loop thatconverts an input, compares the result with a threshold constant, and repeatsthe loop until the threshold has been exceeded. Assume 4 MHz operation.

5. A liquid level sensor returns an analog voltage from 0V to 5V correspondingto a liquid level from 0mm to 1000mm. Using the internal 8-bit A/D con-verter, what is the minimum resolution we could hope to achieve? What is themost likely practical resolution?

Poor Tony Spicuzzi spent 10 years and thousands of dollars refining “Spicuzzi’s Jacuzzi Temp-o-matic” temperature controller only to find out it can now be replaced with a $5.00 PIC.

Page 172: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code172

Assignment

1. Modify the VMETER.ASM program to update the bar graph and LCD only ifone of the analog voltages changes.

2. Write a program that displays the A/D result on the bar graph using 9 LEDs.

3. Create the flowchart for a program subroutine that would display the leadingzeros in the raw A/D result as blanks.

4. Write a program to display the voltage on one of the potentiometers as a per-centage, where 0% equals 0V and 100% equals 5V.

5. Write a program that flashes an alarm LED when an input threshold is ex-ceeded. Use one potentiometer to set the threshold value, and the other as theinput being checked.

Assignment

Page 173: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 173Chapter 17

Interfacting to aSerial EEPROM

The serial EEPROM, as its name suggests, is a nonvolatile electrically erasableprogrammable memory that is accessed serially. Although interfacing to a serialmemory is slower and somewhat more complicated than interfacing to a conven-tional memory, serial EEPROMs have the advantage of requiring very few signaland control lines. For example, a non-serial 256 X 8-bit memory would require eightaddress lines, eight data lines and a few control signals, easily exceeding the numberof I/O lines on a small microcontroller. The 93LC56 (256 X 8-bit) serial EEPROMon the PIC-MDS is an eight-pin chip that uses only three wires to interface to amicrocontroller.

The 93LC56 Serial EEPROM

The 93LC56 is one of a family of serial EEPROMs (SEEPROMs) manufac-tured by Microchip Technology, Inc. The 93LCxx family uses a 3/4-wire interfaceknown as Microwire®, and range in memory capacity from 128 X 8-bits to 512 X 8-bits. The schematic segment below shows the interface connection more clearly.

The 3/4-wires used inthe interface are pins 1-4.Chip select (CS) is broughthigh to select the device.Clock (CLK) is used tosynchronously clock datain and out of the serialEEPROM at a rate of up to2 MHz. Data in (DI) anddata out (DO) carry data inand out of the SEEPROMand can be tied together,hence the name 3/4-wire in-terface. Resistor R11 pre-vents a short circuit condi-tion during reads.

17 Interfacing to aSerial EEPROM

SEEPROM.LIB alsosupports the 512 X 8-bit93LC66 SEEPROM.

During reads, a dummy 0appears on DO while thelast address bit is beingclocked into DI. R11ensures that DI remainsvalid. See the 93LC56 datasheets for more informa-tion.

Page 174: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code174

The Serial EEPROM Data Frame

Storing or retrieving SEEPROM data requires the transmission of a data frameof either twelve or twenty data bits based on the type of SEEPROM instruction.

The serial data frame begins with a start bit (S). Unlike RS-232 serial communi-cation—asynchronous serial communication—the start bit does not signify the startof a timed data transmission. Instead, the SEEPROM uses synchronous communica-tion in which the start bit (applied to DI) must be held high during a rising clock pin(CLK) transition. The remaining frame bits are clocked in sequentially as shown.

OP1 and OP

0, the next two bits that are clocked in, are op-code bits that select

one of the SEEPROM instructions to be performed.

The X/A8 through A

0 bits specify the address on which the instruction should

act, and make up the rest of the non-data instruction frame. The nine address bitsallow for 512 address locations. Since the 93LC56 SEEPROM only has 256 addresslocations, the X/A

8 bit holds a dummy value in order to keep the data frame size

constant.

Finally, D7 through D

0 provide data if needed by the instruction, or represent

data clocked out of the SEEPROM during a Read.

Serial EEPROM Instructions

The 93LCxx family of SEEPROMs are controlled by seven instructions:

EWDS • Erase Write Disable, prevents any changes to the SEEPROM contentsand is the power-up default setting.

WRAL • Write All, fills all memory locations with the specified data.ERAL • Erase All, erases all memory locations.EWEN • Erase Write Enable, allows changes to the SEEPROM memory.WRITE • Writes the supplied data to the specified address.READ • Reads the data from the specified address.ERASE • Erases the contents of the specified address.

For data protection during power-up conditions, the default SEEPROM power-up state is EWDS. Before writing or erasing any data in the SEEPROM, an EWENinstruction must be issued. It’s highly recommended to finish a write with EWDS,which prevents any data modification during power-down or brown-outs.

Timing is not critical insynchronous communica-tion. In fact, you can stopthe clock in the middle of atransmission and continuelater—something thatwould guarantee data lossin asynchronous communi-cation.

WRAL, WRITE and READrequire a full instructionframe to be transmitted. Allof the other instructionsrequire a partial dataframe, since no data isrequired.

The 93LC56 SerialEEPROM

A READ operation obvi-ously involves receiving theData bits after transmittingthe first part of the frame.

Page 175: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 175Chapter 17

Interfacting to aSerial EEPROM

Using The SEEPROM

SEETEST.ASM is a utility to test and program 93LC56/66 SEEPROMs. It dis-plays a SEEPROM address and its contents on the top line of the LCD, and promptsfor the four buttons in the top row of the keypad on the bottom line of the LCD.Using the buttons you can increment or decrement the SEEPROM address, select aspecific address, or change the contents of any address. Assemble, download andrun SEETEST.ASM to try it out for yourself.

Pull out SEETEST.ASM as we explain its operation. To begin, lets examinesome noteworthy equates.

Addrh and Addrl, as the comments suggest, are registers used to hold the highand low address bytes of the current SEEPROM address. SEEPROM.LIB uses simi-lar equates, namely SEEAddrh and SEEAddrl. During SEEPROM access, the con-tents of the SEEAddrh and SEEAddrl registers are shifted out to the SEEPROMwith the result that after the shift, these registers no longer contain the original ad-dresses. Since the SEETEST program needs to know the current SEEPROM ad-dress (so that it can be incremented or decremented), and SEEAddrh and SEEAddrlare lost in the shift, Addrh and Addrl maintain a pointer to the current SEEPROMaddress.

The SEEClock register is used to count the number of data bits transmitted ineach serial frame. SEEData stores the data to be written to the SEEPROM or con-tains the data after a READ instruction.

The first part of the Update_Status routine displays the words “Addr:” and “Data:”on the top line of the LCD, and positions the LCD cursor after the word “Addr:” inpreparation for displaying the actual memory address. MOVF Addrh,W loads theupper SEEPROM address byte (in this case, 0, as Addrh was cleared during initiali-zation) into W. ANDLW 01h clears the upper seven bits of W, isolating the A8address bit. The call to Hex_Remap converts the value in W to a single ASCII char-acter code in preparation for the display of the first address digit on the LCD. TheCALL to LCD_Data displays the first digit of the SEEPROM address as a hexadeci-mal digit on the LCD.

Addrh DS 1 ;SEEPROM high address byteAddrl DS 1 ;SEEPROM low address byte

;Equates required by SEEPROM.LIB

SEEAddrh DS 1 ;SEEPROM high address byteSEEAddrl DS 1 ;SEEPROM low address byteSEEClock DS 1 ;SEEPROM clock counter registerSEEData DS 1 ;SEEPROM data storage byte

After every SEEPROMaccess, SEEAddrh andSEEAddrl are cleared bySEEPROM.LIB

Update_Status ;Displays the current SEEPROM address and data on the top li;of the LCD and the Menu options on the bottom line.

.

.MOVF Addrh,W ;Load W with high address byteANDLW 01h ;Clear upper seven bitsCALL Hex_Remap ;and convert to ASCII for LCDCALL LCD_Data ;and display on LCD

The Update_Status routineis the main programroutine in SEETEST.ASM.It always displays theaddress and the datastored in that address online one of the LCD, anddisplays the prompts online two of the LCD.

Page 176: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code176

The next lines of the program display the second hexadecimal address digitcontained in the upper nybble of Addrl. First, Addrl is copied into W with its upperand lower nybbles exchanged. Next, ANDLW 0Fh wipes out the top four bits, pre-paring the value for the call to Hex_Remap. Finally, CALL LCD_Data displays theASCII digit corresponding to the hexadecimal address’ second digit.

A similar process is used to display the last hexadecimal digit of the SEEPROMaddress. After these lines execute, the three digits of the current SEEPROM addresshave been displayed on the LCD. The next section of the code reads the SEEPROMand displays the contents of the current address on the LCD after the word “Data:”.

CALL SEE_Port readies the three I/O lines the PIC will use to communicatewith the SEEPROM. The I/O lines connecting to the SEEPROM chip select andclock are set to output, and the line connected to data is set to input.

As explained previously, Addrl and Addrh are copied into SEEAddrl andSEEAddrh in preparation for the read command. The read is initiated by passing theSEERead value (from the EQUates) through W to the SEE_Command subroutine.

The CALL to SEE_Command begins a process of parsing and shifting the serialdata frame to the SEEPROM. Remember that the SEEPROM data frame contains acommand op-code, address bits, and, if necessary, data bits. The SEEPROM re-sponds to seven command instructions, as shown in the chart on the next page.Notice that the serial data frame diagram shown earlier indicates that only two bitsare used to encode SEEPROM commands. Clearly, two bits are insufficient to en-code seven commands. The way in which the extra commands are encoded, as shownby the chart, is to extend the op-code bits whenever the op-code is 00. XOP

0 and

XOP1 represent the extended op-code bits.

SWAPF Addrl,W ;Switch Addrl nybbles and copy to WANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVF Addrl,W ;Load W with low address byte againANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

CALL SEE_Port ;Set up Port A for SEEPROM useMOVF Addrl,W ;Copy low address byte toMOVWF SEEAddrl ;SEEPROM low address byteMOVF Addrh,W ;Copy high address byte toMOVWF SEEAddrh ;SEEPROM high address byteMOVLW SEERead ;Send SEEPROM Read byte commandCALL SEE_Command ;to SEEPROM

In extended instructions,XOP

1 and XOP

0

overwrite the X/A8 and

A7 bits. Both instruc-

tions remain the sameoverall length.

If you find your brainswelling as it did in Chap-ter 12, remember that youdon’t need to know exactlyhow the subroutines workin order to use them. It’swhen you need to interfacethe PIC to a new peripheralthat you’ll need to figureout all of its idiosyncrasies.For those of you stillinterested, read on!

Using the SEEPROM

Page 177: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 177Chapter 17

Interfacting to aSerial EEPROM

Although the op-code is sometimes extended with two extra bits, the data frameitself cannot change in length. The extended op-code bits simply overwrite the ad-dress bits X/A

8 and A

7. Fortunately, the four commands encoded by extended op-

code bits are global commands and do not require a specific address. The remainingaddress bits are sent merely to maintain the required 12- or 20-bit data frame size.

The 7B bit in the chart represents the 7-bit address flag used only withinSEEPROM.LIB. When this bit is set, it indicates that extended op-code bits arepresent, and that only seven more dummy bits in the address field are needed tocomplete the 12- or 20-bit data frame. The 7B flag was added to make commandparsing within SEEPROM.LIB easier and is not transmitted to the SEEPROM.

Now that we know how op-codes encode the instruction sent to the SEEPROM,we’ll examine the SEEPROM.LIB code that assembles the data frame. The firstdata that will be displayed by SEETEST.ASM resides at address 000h. The code onthe previous page would have loaded SEEAddrh and SEEAddrl as shown below:

Recall from the previous page, that just before the Call to SEE_Command, Wwas loaded with the constant SEERead (C0h). The first instruction in SEE_CommandORs the SEERead constant into SEEAddrh, and the result is shown below the code.

S - Start bit OPn - non-extended op-code bits XOP

n - extended op-code bits

7B - 7-bit address flag X/A8 - dummy or A8 address bit A

7-A

0 - address bits

SEE_Command ;This subroutine parses the SEEPROM command op-code, compl..

IORWF SEEAddrh ;Store command to top bits of SEEAd From SEEPROM.LIB

IORWF copies W intoSEEAddrh without chang-ing the A

8 bit.

SEEPROM instructionformatting.

Page 178: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code178

The reason for copying the SEEPROM command into the top of the SEEAddrhregister may not be immediately apparent. Since only the least significant bit ofSEEAddrh is required to hold A

8, the remainder of the register is empty. We use the

upper four bits of SEEAddrh to build the first part of the serial data frame. Remem-ber, a SEEPROM transmission must be either 12- or 20-bits. The upper 4 bits ofSEEAddrh, plus all 8-bits of SEEAddrl complete a 12-bit data frame. A 20-bit frameadds eight more data bits, stored in SEEData. The only thing left to do, to make the

transmission of the start of thedata frame easier, is to move ei-ther A

8 to the upper nybble of

SEEAddrh, or to move the StartBit, and op-code bits to thelower nybble so that they caneasily be shifted in succession.Since moving A

8 requires only

the movement of one bit, notthree, we do just that. The endresult is illustrated at left:

The flowchart below shows how commands are decoded by SEE_Command inSEEPROM.LIB. In addition to decoding the instruction, SEE_Command also as-sembles the data in SEEAddrh and SEEAddrl in preparation for serially shifting thedata frame out to the SEEPROM. See the pull-out section for complete details.

There is actually anotherreason for moving A

8

instead of the other threebits. For extended op-codes, we can just add theextended bits after the op-code bits without worryingabout whether to shiftthree or five command bitsdown to beside A

8. But

then, having five commandbits requires that onlyseven address bits follow(to complete the 12-bitframe), complicating thingseven more. And, to confuseyou even further, none ofthis is actually done in thisorder. But, the flowchartwill give you an idea ofhow we figure out what thecommand is, and, since weknow the command, howmany bits to shift.

This flowchart shows theprocess of SEEPROMcommand decoding inSEEPROM.LIB.

Using the SEEPROM

Page 179: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 179Chapter 17

Interfacting to aSerial EEPROM

Calling SEE_Command not only parses the command and shifts out the serialdata frame, but also determines whether or not to use the SEEData register for Readsand Writes. If a Write or Write All command is sent, the contents of SEEData arealso shifted out by SEE_Command. In this case, however, the Read command in-structs SEE_Command to retrieve the data from the SEEPROM and shift it intoSEEDATA. Once the data from the requested address has been read into SEEData,the code below displays the contents of SEEData on the LCD.

Since the LCD and SEEPROM share some of the PIC’s PORT A lines it isnecessary to call LCD_Port before setting the LCD cursor position via the Call toLCD_Reg. Next, the two Data nybbles are displayed in the same way as the addressdigits were previously. Now, the line one address and data display is complete.

The next section of code displays the soft function key prompts on line 2 of theLCD by using a table read—the same manner in which messages have been dis-played in previous example programs. Then Port B of the PIC is set up for keypadscanning, and the returned key code is stored in the KeyTemp register. To finish theUpdate_Status subroutine, the constant 01h is stored in the Delay register. Delay isused to count loops for the pause between key repeats if a key is held down, and acount of 01h represents the short delay between repeats, not the initial long delay.

The Wait_for_Key subroutine checks for a key press in the top row of the key-pad. These are the keys corresponding to the soft-key prompts. If a key has beenpressed, Wait_for_Key first determines which key has been pressed. For the firsttwo keys, a check is made to determine if this is an initial press, or a key that hasbeen held from the previous operation. When the key is first pressed, the Delaycounter is set to 20h from 01h. Next, the Repeat_Delay subroutine is called to im-plement the key delay. In this case, the delay between an initial key press and thefirst repeat is thirty-two times longer than the delay between successive repeats.Following the key delay, the action corresponding to the key press—eitherincrementing or decrementing the SEEPROM address—is performed.

You do remember that thiswhole discussion startedbecause of a SEEREADinstruction about threepages back, don’t you?

CALL LCD_Port ;Set up Ports for LCD useMOVLW LCDLine1+Data ;Set LCD character position toCALL LCD_Reg ;start of data display areaSWAPF SEEData,W ;Switch nybbles of SEEPROM data to WANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVF SEEData,W ;Load W with SEEPROM data byteANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVLW LCDLine2 ;Send LCD line 2 character addressCALL LCD_Reg ;to LCD as a commandMOVLW Menu_Msg ;Load W with Menu message offsetCALL Disp_Message ;and call display message routine

CALL KB_Port ;Set Port B for keypad useCALL KB_Scan ;and scan keys for key pressMOVF Key,W ;Load Key return code into WMOVWF KeyTemp ;and save in temporary register

MOVLW 01h ;Copy short key repeat delay intoMOVWF Delay ;Delay register

Only the first two keys—”Dwn” and “Up”—implement key repeat. Theaction for the last two keysis described in the nextparagraph.

Page 180: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code180

The actions resulting from an “Sel” or “Chg” key press are only slightly differ-ent from the previously described key processing, with the difference being thatthese two keys do not implement a key repeat. Instead, pressing the “Sel” key entersa subroutine that allows a user to immediately enter an address by pressing threekeys, and pressing the “Chg” key allows a user to change the data at the currentaddress with the next two key presses. The program flow showing the process of keydetermination is illustrated in the following flowchart.

If the first key is pressed, the Addr_Down subroutine decrements the Addrlregister as long as its value is greater than zero. Likewise, the Addr_Up subroutineallows the second key to increment the SEEPROM address up to 1FFh.

The “Sel” soft key calls the Addr_Set subroutine. Addr_Set first displays ques-tion marks and a blinking cursor where the three address nybbles (about to be en-tered) are displayed. Next, the keypad is configured to obtain the three nybbles neededin order to define the new address. The subroutine then checks to see if the firstnybble is either a zero or a one, and loops until a zero or one is entered. Once thethree nybbles have been read from the keypad, their values are placed in the Addrhand Addrl registers. After waiting for the last key to be released, the key 3 decodingroutine returns program control to Update_Status, which displays the newly enteredaddress as well as the SEEPROM memory contents of this address on the display.

Key decoding flowchart.

Remember, SEEPROMaddresses fall within therange of 000h to 1FFh. Thefirst digit can only be zeroor one.

Using the SEEPROM

Page 181: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 181Chapter 17

Interfacting to aSerial EEPROM

The Data_Set routine behaves similarly to Addr_Set. The difference is that onlytwo digits are entered, representing the two data nybbles. The two digits entered bythe user are saved in the SEEData register and are written to the SEEPROM by thecode, below.

Writing data into the SEEPROM is just a bit more involved than reading data, ifonly because the SEEPROM must be write-enabled first. CALL SEE_Port configuresthe PIC to communicate with the SEEPROM. CALL SEE_Command transmits theSEEEWEN (SEEprom Erase/Write ENable) command, which must precede any eraseor write. SEEAddrl and SEEAddrh are loaded with the current SEEPROM addressfrom Addrl and Addrh, respectively. Remember that the addresses stored in Addrland Addrh are copied to SEEAddrl and SEEAddrh because once the data frame isshifted out, SEEAddrl and SEEAddrh no longer contain valid addresses. Since theSEEPROM is now write-enabled, with SEEAddrh and SEEAddrl loaded with theaddress to be written to, and with SEEData holding the data to be written, theSEEWrite command can now be issued. After the write command is complete, thefinal command to be sent is SEEEWDS (SEEprom Erase/Write DiSable). For maxi-mum data integrity, Microchip recommends that SEEPROM erase and write be disa-bled unless an erase or write is taking place.

After the write operation, program control is once again passed to theUpdate_Status routine. When Update_Status displays the current SEEPROM ad-dress and data, it actually re-reads the contents of the address just written in order toprovide verification that the data entered was correctly stored.

Chapter Summary

Serial EEPROMs are serially-accessed, non-volatile electrically erasable pro-grammable memories. Their advantage is the use of few I/O lines (typically three orfour), at the expense of a more complex software interface. The PIC-MDS supportsthe 93LC56 (256-byte) and 93LC66 (512-byte) Microwire® SEEPROMs.

93LCxx SEEPROMs are controlled by serially transmitting one of seven com-mands in the form of 12- or 20-bit data frames. SEEPROM commands allow for:

• erase/write enable and disable,

• write, read and erase of specific addresses,

• global write and erase of the entire SEEPROM.

The SEETEST.ASM program allows you to enter and verify data in every memorylocation of either the 256- or 512- byte SEEPROMs.

CALL SEE_Port ;Configure Port A for SEEPROMMOVLW SEEEWEN ;Send Erase/Write Enable commandCALL SEE_Command ;to SEEPROMMOVF Addrl,W ;Copy Addrl byte toMOVWF SEEAddrl ;SEEAddrlMOVF Addrh,W ;Copy Addrh byte toMOVWF SEEAddrh ;SEEAddrhMOVLW SEEWrite ;Send data write commandCALL SEE_Command ;to SEEPROMMOVLW SEEEWDS ;Send Erase/Write Disable commandCALL SEE_Command ;to SEEPROM

Page 182: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code182

Questions

1. What is the minimum amount of time in which a read can be performed?

2. Why are SEEPROMs said to use a 3/4-wire interface?

3. Examine the data sheets to find the typical length of time taken by an erase orwrite command. What is the maximum length of time for a write command?

4. At a typical write cycle time, and assuming that you perform successive writes,how long would it take to reach the specified endurance of the 93LC56?

Assignment

1. Modify CLOCK.ASM to store the current time whenever a key is pressed, oran I/O line activates. Store the time that each event occurs in successiveSEEPROM registers. Use SEETEST.ASM to examine the stored times.

Questions and As-signment

Interfacing devices like serial EEPROMs to the PIC can make you feel a bit likeyou’re being buried in mounds of new information. Without a good guide ordata sheets, you’ll feel like there are a few crabs in the mound with you!

Page 183: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 183Chapter 18

Watch Dog Timer

18 The Watch Dog Timer

Watch Dog Timers (WDT) are often a feature of microcontrollers used in real-time control systems. The main purpose of the WDT is to improve the reliability ofthe control software by providing a periodic time-out signal that is used to reset thePIC—as if the PIC were just powered-up. Instead of allowing the WDT to reset theprocessor, however, it is imperative that the software periodically resets the WDT inorder to continue normal program execution. If for some reason the program fails toreset the WDT, then the WDT time-out signal issues a RESET, restarting programexecution from the power-up state. In the PICmicro family, the WDT can also wakethe PIC from SLEEP. Waking the PIC from sleep does not cause a power-up reset,but rather operation continues from the instruction following the SLEEP instruc-tion.

The WDT in the mid-range PICmicro family is a counter fed from a continu-ously running, on-chip R/C oscillator, which issues a WDT time-out approximatelyevery 18 ms. The WDT time-out signal can be fed to an 8-bit postscaler counter,which can extend the time-out period to approximately 2.3 seconds. The WDTpostscaler is also the TMR0 prescaler. Therefore, assigning the postscaler to WDTprevents TMR0 from using the prescaler, and vice-versa. For clarity, the diagrambelow shows only the register bits required in setting the WDT. See Chapter 11 fora diagram showing how these same bits can select TMR0 options.

In this chapter, we’ll demonstrate two WDT programs. One shows how to usethe WDT to perform a RESET during failed program execution, and the other showsthe use of WDT in waking the PIC from SLEEP.

Both Vdd level and tem-perature affect the time-outperiod of the R/C oscillator.Because of this, don’t counton the WDT for precisetiming.

Page 184: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code184

Handling Software Faults using the WDT

The pseudo-code for a typical WDT-enabled program is shown below.

InitializeEnable WDT

Main Code..

Clear WDT

GOTO Main Code

All WDT-enabled programs must, as part of their regular execution, reset theWDT periodically. Failure to do this, of course, will result in the WDT timing outand resetting the PIC. Think of the WDT as a ticking time-bomb. Your programneeds to reset the counter before the counter expires, which would reset your pro-gram. In a simple program, where all tasks can be completed before a time-out, asingle CLRWDT instruction at the end of your code is sufficient. Otherwise, yourcode must ensure that the WDT is cleared before a time-out occurs by includingCLRWDT instructions within all of its subroutines.

The program TIMEOUT.ASM demonstrates not only how the PIC can be resetby the WDT, but also how to determine whether the reset occurred because of aWDT time-out or power-up/MCLR (depressing the RESET button). Being able todistinguish the cause of a reset provides your program with the ability to be self-monitoring—it can indicate to the user that a software or hardware fault triggered anunintended reset. Pull out TIMEOUT.ASM as we examine the program flow.

After initializing a few registers and the setting up the ports for LCD use,TIMEOUT.ASM begins execution by determining the cause of the last reset. It doesthis by checking TO, the Status register Time Out bit. If TO is set, the PIC restartedfrom a power-up or MCLR reset, and execution continues by initializing the WDT.Of TO is low, a message indicating that the WDT generated the reset is displayed onthe LCD.

Assuming a power-up reset occurred, the program configures the WDT with themaximum prescaler/postscaler value, which sets a time-out period of approximately2.3 seconds. Before doing this, the CLRWDT instruction assures us that no unin-tended resets will occur as the prescaler/postscaler is changed.

Initialize ;Continue by initializing the LCD display.

CALL LCD_Port ;Set up Ports for LCD use

BTFSS TO ;Check WDT Time Out flag and GOTO WDT_Message ;skip WDT and LCD init if reset by

Init_WDT CLRWDT ;Clear Watchdog Timer BSF RP0 ;Select register page 1 MOVLW 0FFh ;Set Option register for WDT with MOVWF Option ;1:128 prescaler (maximum prescaler BCF RP0 ;Return to register page 0

Handling SoftwareFaults using the WDT

Page 185: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 185Chapter 18

Watch Dog Timer

After initializing the LCD and displaying the reset and power-up messages, theWait_for_Key subroutine checks for key strokes.

If no keys are pressed, execution continues by resetting the WDT.

The Wait_for_Key and Reset_WDT routines form a tight program loop—checkfor a key press, and if none, reset the WDT before checking for the next key press.This loop takes far less time than the WDT time-out period to execute, demonstrat-ing normal WDT operation.

If a key is pressed, program flow remains within the Key_Release subroutinefor the duration of the key press. Note that because there is no CLRWDT instructionwithin the Key_Release subroutine, one of two things will happen. If the key ispressed and released within the WDT time-out period, program operation continuesin the normal way by having the Reset_WDT subroutine reset the WDT, andWait_for_Key check for the next key press. If, however, a key is pressed and heldfor the duration of the WDT period, the WDT will time-out, clear the Status TO bit,and issue a device reset. When the PIC restarts program execution, the TO bit checkin the Initialize routine will cause the program to branch to the WDT_Messageroutine, which changes the LCD to show the WDT as the cause of the last reset.

The importance of this program is that it demonstrates the additional level ofprogramming necessary to cope with the potential loss of control due to WDT op-eration. Put simply, when and if the WDT times out, your program is no longerdoing what you programmed it to do. How gracefully your program recovers fromthe unintended reset is now determined by the code that follows your TO bit check.Complicating the whole matter is that you don’t know at which point your pro-gram’s execution it was reset. If nothing else, this factor alone necessitates that youcarefully plan your program’s structure in order to accommodate the WDT and en-sure that your initialization code configures the I/O to a known state, leaving noth-ing to chance. For all of its benefits, you cannot just enable the WDT because youthink it’s a good idea—your code needs to be written for it!

Wait_for_Key ;Checks for a key press. If no keys are pressed, WDT is res

CALL KB_Port ;Set up Ports for keypad scanning CALL KB_Scan ;Get Key return code MOVF Key,W ;Load Key code into W to set flags BTFSC Z ;and check for 0 (0=no key) GOTO Reset_WDT ;If no key pressed, reset WDT

Reset_WDT ;Resets the WDT, setting the TO flag.

CLRWDT ;If no key pressed, clear Watchdog GOTO Wait_for_Key ;and check for another key press

Key_Release ;Waits for the key to be released. If a key is held for 2-3 ;seconds, the WDT will time out since there is not CLRWDT ;instruction inside this wait loop.

CALL KB_Scan ;Scan keys for key press MOVF Key,W ;Check Key return code for no key BTFSS Z ;by checking for 0 (0=no key) GOTO Key_Release ;If key is held, check again

Page 186: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code186

Enabling the WDT

Before programming a PIC with TIMEOUT.ASM, let’s take a look at where theWDT is enabled. PIC programs themselves have no control over the WDT. Enablingor disabling the WDT is accomplished by the programmer or downloader when thedevice configuration bits are programmed. The Device directive in the code controlsthe configuration bits.

In the Device directive above, thecommand WDT_ON instructs the assem-bler to enable the WDT in the PIC’s con-figuration bits. The EPIC downloadingsoftware (at right) allows you to overrideany of these settings at programming time.Whenever programming a PIC with aWDT-enabled program, it’s a good ideato double-check the device settings to en-sure that the WDT will indeed be turnedon. Alternatively, a single click can dis-able the WDT in a WDT-enabled programfor debugging.

Waking the PIC using the WDT

If a WDT-enabled PICmicro™ processor is put to sleep, the WDT will wake thePIC from sleep at the end of its time-out period. The WDT will not cause a devicereset when the PIC is asleep. Another simple WDT program illustrates this.

When WDTIMER.ASM is first started, a 16-bit wake-up counter is reset to zerobefore the WDT is enabled. Then, the number of wake-up cycles is displayed on theLCD. Next, the PIC goes to sleep. At the end of the WDT period, the PIC wakes up,increments the wake-up count on the LCD, and goes back to sleep. Had a devicereset occurred, the wake-up counter which was initialized at the start of the programwould also be reset, and the wake-up count would never increment. Pull outWDTIMER.ASM to examine it as we dissect the code.

The Initialize subroutine clears the upper and lower bytes of the 16-bit wake-upcounter. Like the TIMEOUT.ASM program from earlier in the chapter, Init_WDT

Device PIC16F84,HS_OSC,WDT_ON,PROTECT_OFF,PWRT_ON

Initialize ;Continue by initializing the LCD display.

CLRF Wake_UpH ;Continue clearing registers CLRF Wake_UpL CALL LCD_Port ;Set up Ports for LCD use

Init_WDT CLRWDT ;Clear Watchdog Timer BSF RP0 ;Select register page 1 MOVLW 0FEh ;Set Option register for WDT with MOVWF Option ;1:64 prescaler BCF RP0 ;Return to register page 0

See Appendix C for moreinformation on the Devicedirective.

Handling SoftwareFaults using the WDT

Page 187: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 187Chapter 18

Watch Dog Timer

clears the WDT before setting a prescaler/postscaler in the Option register. Thistime, the WDT time-out period is approximately 1.15 seconds.

After initializing the LCD and displaying the “Wake-up #:” message on the topline, and the “Processing” message on the bottom line, the Main subroutine incre-ments the Wake_UpL and Wake_UpH counters. Using ADDWF instead of INCFallows us to check the C flag for the Wake_UpL roll-over. If Wake_UpL rolls over,Wake_UpH is incremented. After the increment, the wake-up counters are copied toLowByte and HighByte for conversion to BCD.

MOVLW Wake_Ups and CALL LCD_REG send the starting position of thewake-up count to the LCD. The next four instructions isolate the first BCD nybbleof the 16-bit number, add 30h to convert it to an ASCII number, and display thenumber on the LCD. Similar groups of instructions display the remaining four digitsof the wake-up count.

After the wake-up count is displayed, a pause is added by calling the Delay_5mssubroutine. The only purpose of the delay is to lengthen the amount of time that the“Processing” message appears on the LCD. Otherwise the processing itself takes solittle time that the “Sleeping” message would never appear to change.

Finally, the “Sleeping” message is displayed, and the PIC is put to SLEEP. Afterthe WDT time-out period expires, execution continues at the start of Main, wherethe “Processing” message is displayed before updating the wake-up count.

MOVLW 1 ;Increment Wake-Up counter low byte ADDWF Wake_UpL ;using Add instruction BTFSC C ;Check Carry for roll-over INCF Wake_UpH ;and increment high byte if set

MOVF Wake_UpL,W ;Copy Wake-Up counters to LowByte a MOVWF LowByte ;HighByte for BCD conversion MOVF Wake_UpH,W MOVWF HighByte

CALL Bin_BCD ;Convert to BCD

MOVLW Wake_Ups ;Send starting address of wake-up CALL LCD_Reg ;counter to LCD MOVF TenThous,W ;Load W with lower nybble of ANDLW 0Fh ;Ten thousands digit ADDLW 30h ;Convert it to ASCII and CALL LCD_Data ;display it on the LCD

MOVLW LCDLine2 ;Send line 2 starting address CALL LCD_Reg ;to LCD CALL Delay_5ms ;Add a 20ms pause to see Processing CALL Delay_5ms CALL Delay_5ms CALL Delay_5ms

MOVLW Sleep_Msg ;Load W with Sleeping message offse CALL Disp_Message ;and display it on line 2 of LCD

SLEEP ;Sleep until WDT expires NOP ; GOTO Main ;On WDT wake-up, display next count

Page 188: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code188

Chapter Summary

The WDT is an independent timer that, when enabled, can reset the PIC orperiodically wake the PIC from sleep. Programs can use the WDT as a safety devicethat will reset the PIC in case of a stuck code condition. If the CLRWDT instructionis not issued by a program before the WDT time-out period expires, the WDT willreset the PIC. WDT-enabled programs require greater planning on the part of theprogrammer, since a method of handling both unintended resets as well as unknownI/O states must be implemented to ensure proper code operation.

Using the TO bit, WDT-enabled programs can determine the cause of the devicereset and can respond appropriately. Programs should also be tested for the effect ofunanticipated I/O delays, such as a stuck key or sensor.

If the PIC is asleep, the WDT time-out merely wakes the PIC from sleep ratherthan causing a device reset.

If you ignore it, the WDT will blow your program back to its start!

Chapter Summary

Page 189: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 189Chapter 18

Watch Dog Timer

Questions

1. Why is it important that the WDT has its own internal R/C oscillator? Whycan’t the WDT use the PIC’s oscillator?

2. Using pseudo-code, show how to set up the WDT for use as an approximately20 ms long switch debounce delay.

3. The WDT is not a bullet-proof method of ensuring a device reset during asoftware failure. If a programming error leaves the PIC stuck in a loop, whatsoftware conditions must have been met, both before and during the loop, toensure that the WDT resets the device?

Assignment

1. Modify the program TIMEOUT.ASM so that holding a key does not cause aWDT time-out. This change would represent normal WDT operation, in whichthere should never be a time-out.

2. Implement a long time period delay using the WDT. Compare the number ofregisters required as counters for a five-minute delay timer using the WDT,with that of a five-minute delay timer implemented in software delay loops.Assume 10MHz operation.

Page 190: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code190Notes

Page 191: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-1Appendix A

PIC-MDS Installationand Setup

©1998 Sirius microSystems

A PIC-MDS Installationand Setup

Page 192: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-2 ©1998 Sirius microSystems

Page 193: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-3Appendix A

PIC-MDS Installationand Setup

©1998 Sirius microSystems

Congratulations on your purchase of the Sirius microSystems PIC-MDS. Theinstructions in this chapter will guide you through the installation and setup of thePIC-MDS hardware and software. First, ensure that you have everything in yourPIC-MDS package.

PIC-MDS Professional Package

• PIC-MDS circuit board with ZIF socket• PIC16C711 microcontroller• PIC16F84 microcontroller• 10 Mhz crystal• EPIC Programmer• 6 ft., DB-25 m-f parallel port extension cable• 6 in., 10-conductor in-circuit programming ribbon cable• 2-120 VAC wall adapters *• PIC-MDS Programs and Software Libraries diskette• EPIC Programmer diskette• PIC-MDS Microcontroller Development System Training Manual

PIC-MDS Professional

• PIC-MDS circuit board with ZIF socket• PIC16C711 microcontroller• PIC16F84 microcontroller• 10 MHz crystal• 120 VAC wall adapter *• PIC-MDS Programs and Software Libraries diskette• PIC-MDS Microcontroller Development System Training Manual

PIC-MDS Hobbyist Package

• PIC-MDS circuit board kit• Assembling and Testing Your PIC-MDS booklet (green)• PIC16F84 microcontroller• 10 MHz crystal• EPIC Programmer• 6 ft., DB-25 m-f parallel port extension cable• 6 in., 10-conductor in-circuit programming ribbon cable• 2-120 VAC wall adapters *• PIC-MDS Programs and Software Libraries diskette• EPIC Programmer diskette• PIC-MDS Microcontroller Development System Training Manual

PIC-MDS Hobbyist

• PIC-MDS circuit board kit• Assembling and Testing Your PIC-MDS booklet (green)• PIC16F84 microcontroller• 10 MHz crystal• 120 VAC wall adapter *• PIC-MDS Programs and Software Libraries diskette• PIC-MDS Microcontroller Development System Training Manual

* Wall adapters areshipped with orders toNorth America only. TheEPIC Programmer requires12 VAC at 500 mA. ThePIC-MDS can operate on9-12 VAC, 12-15 VDC, oran external power supplyat 300 mA. See Chapter 4.

Page 194: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-4 ©1998 Sirius microSystems

PIC-MDS Requirements

To use the PIC-MDS you will need and IBM PC or compatible computer with:

• Microsoft® MS-DOS• a standard parallel port• 1 MB of free hard disk space to install the software (recommended)

The EPIC Programmer software is designed to be run from MS-DOS only, us-ing a standard parallel port. Some newer system boards with built-in ECP/EPP par-allel ports may not work properly with the EPIC Programmer software. If the EPICProgrammer software give repeated “Programmer not found” messages or had dif-ficulty programming microcontrollers, try to disable the ECP/EPP parallel port fea-tures in the system board BIOS setup utility or purchase a standard parallel portcard for your computer.

The EPIC Programmer software is dependent on accurate timing which canonly be guaranteed when it is run from MS-DOS. We do not recommend runningthe EPIC Programmer software from within other multi-tasking operating systems.Due to the wide variety of computer systems and the complexity of multi-taskingoperating systems we can support only those customers running the EPIC Program-mer software from MS-DOS. However, below are some suggestions which mayhelp you to run the EPIC Programmer software from other operating systems:

Windows 3.x and Windows 3.11 for Workgroups

From the Main Group start an MS-DOS session in full-screen mode. Do notattempt to run the EPIC Programmer software from within a DOS Window on theProgram Manager screen.

Windows 95 and Windows 98

From the Start Button perform a Shut Down and select “Restart the computer inMS-DOS mode” from the list of Shut Down choices. After the computer restarts,run the EPIC software from MS-DOS mode.

OS/2 Warp v.3 and OS/2 Warp Connect

Start a DOS Full Screen session in which the HW_Timer setting has been set toOn and Video_Retrace_Emulation is set to OFF. Run the EPIC Programmer soft-ware in full-screen mode.

Installing the Software

If you are using the PIC-MDS with the EPIC Programmer...

Insert the diskette labelled “PIC-MDS Programs and Subroutine Libraries” intoyour floppy diskette drive. At the MS-DOS prompt type:

a:\install c: [Enter]

Where a: is the identifier of your floppy diskette drive and c: is the identifier ofthe hard disk drive that you with to install the PIC-MDS software on to.

See the appropriateMicrosoft or IBM manualsor Help files for moreinformation on MS-DOSsessions. Although notrecommended, we havebeen able to run the EPICProgrammer software fromeach of the three operatingsystems at right.

PIC-MDS Require-ments

Page 195: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-5Appendix A

PIC-MDS Installationand Setup

©1998 Sirius microSystems

The installation program creates a directory named “PIC-MDS” on the speci-fied hard disk drive and copies the program source files (*.SRC) and library files(*.LIB) into this directory. When this is complete, the installation program promptsyou to insert the “EPIC Programmer” diskette.

Remove the “PIC-MDS Programs and Subroutine Libraries” diskette from yourfloppy disk drive and insert the “EPIC Programmer” diskette. Press any key tocontinue the installation.

After inserting the “EPIC Programmer” diskette and pressing a key, the instal-lation program copies the PIC Macro Assembler software (PM.EXE), EPIC Pro-grammer software (EPIC.EXE) as well as a demonstration program and a numberof text files to the PIC-MDS directory. Finally, the installation program creates asubdirectory named INC within the PICMDS directory and copies the microcon-troller device type include files into it.

At this point the PIC-MDS software installation is complete. The diagram be-low indicates the program directory structure:

Hard Disk Drive

PICMDS*.ASM - Microchip source code files#*.ASM - Parallax source code files*.LIB - subroutine library filesPM.EXE - PIC Macro Assembler programEPIC.EXE - EPIC ProgrammerINC

P*.INC - PIC device type include files

If you are using the PIC-MDS with a third-party programmer...

Insert the “PIC-MDS Programs and Subroutine Libraries” diskette into yourfloppy disk drive and copy all of the source files (*.ASM) and library files (*.LIB)into the directory on you hard disk that contains your PIC assembler software oryou other PIC source code programs.

PIC-MDS Setup

Connecting the EPIC Programmer

To prepare the EPIC Programmer for use you will need:

• EPIC Programmer• 6 ft., DB-25 m-f parallel port extension cable• 12 VAC, 500 mA output wall adapter or two 9 V batteries

Remove the EPIC Programmer from is package and set it on a non-conductivesurface. Attach one end of the included 25-pin male to 25-pin female printer exten-sion cable to the 25-pin connector on the EPIC Programmer.

Page 196: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-6 ©1998 Sirius microSystems

Connect the other end of the 25-pin cable to the parallel printer port on yourcomputer.

CAUTION: Make sure that you connect the programmer to a parallel printerport. Connecting the programmer to a serial port may result in damage tothe serial port or the programmer.

If you use a 12 VAC adapter to power the EPIC Programmer, remove the shortingblock from the jumper labelled “Batt ON”. Plug the AC adapter into a receptacleand connect the round coaxial plug into the power jack on the top right of the EPICProgrammer.

If you use two 9 V batteries to power the EPIC Programmer, connect the shortingjumper across the “Batt ON” header and plug the batteries into the battery snaps.

WARNING: Never connect a battery across the centre snaps. This maycause the battery to overheat and explode.

One or both of the LEDs on the EPIC Programmer may now be lit.

With your computer running, make sure that you are in the directory that con-tains the PIC-MDS software by typing:

cd \picmds [Enter]

Start the EPIC Programmer software by typing:

epic [Enter]

If the EPIC Programmer is properly connected to your computer you should seethe EPIC Programmer screen appear on your computer. Both LEDs on the EPICProgrammer board should now be off.

This is the EPIC Program-mer screen that appearswhen the EPIC Program-mer is properly installed.

PIC-MDS Setup

Page 197: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-7Appendix A

PIC-MDS Installationand Setup

©1998 Sirius microSystems

If you see the “Programmer not found” messagemake sure that the EPIC Programmer is connected toyour parallel printer port and that the cable is firmlyseated. Then check that the AC adapter is plugged inand select “Retry”.

The EPIC Programmer software and hardware is fully installed and ready toprogram a microcontroller.

Connecting the PIC-MDS

To prepare the PIC-MDS for use you will need:

• PIC-MDS• 6 in., 10-conductor in-circuit programming ribbon cable• wall adapter or power supply• PIC16C711 or PIC16F84 microcontroller• 10 MHz crystal

Remove the PIC-MDS from is package and set it on a non-conductive surface.Attach the included 10-pin In-Circuit programming cable to the In-Circuit program-ming header (H2) on the PIC-MDS. Note: The cable should extend away from thePIC-MDS.

Position the EPIC Pro-grammer and PIC-MDS asshown in the picture andconnect the other end ofthe 10-pin In-Circuit pro-gramming cable to theconnector labelled “J3” onthe EPIC Programmer.Note: The cable shouldextend over the EPIC Pro-grammer.

Before installing themicrocontroller into thePIC-MDS, make sure thatboth LEDs on the EPICProgrammer are off.

Now, carefully take the PIC16F84processor out of its packaging and insert itinto the processor socket (U3) on the PIC-MDS making sure that pin 1 of thePIC16F84 is closest to the label U3. If youhave a green ZIF socket, lift the handle tothe vertical position before inserting thePIC16F84. Once the PIC16F84 is in thesocket, push the handle back down to thehorizontal position.

Batt ON Jumper

In-Circuit Cable

10 MHz Crystal

Pin 1

The In-Circuit program-ming cable allows you toprogram and erase aPIC16F84 microcontrollerin the PIC-MDS circuitboard. You do not need toplug the microcontrollerinto the programmingsocket on the EPIC Pro-grammer and transfer it tothe PIC-MDS after pro-gramming. PIC16C711microcontrollers can beprogrammed in the PIC-MDS, but require UV lightfor erasure.

Page 198: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

A-8 ©1998 Sirius microSystems

CAUTION: Make sure that the notch and the Microchip logo on the PIC16F84are closest to the label U3 on the PIC-MDS circuit board. Inserting thePIC16F84 into the PIC-MDS backwards may result in damage to the proc-essor or the PIC-MDS.

Plug the 10 MHz crystal into the crystal socket labelled Y1 on the PIC-MDS.

At this time, connect the plug from the PIC-MDS AC adapter into the coaxialpower jack (J1) or connect a power supply to CON1 (see Chapter 4). The LED atthe top of the LED bar graph display (labelled PWR) should light up. Note: Someor all of the other LEDs may also be lit. The LCD display may contain one line ofblock characters. This is normal.

The PIC-MDS hardware is now connected to the EPIC Programmer and is readyto program a PIC16F84 via the in-circuit programming cable, or to run the programin a previously programmed PIC microcontroller.

Assembling and Downloading Programs

If you are familiar with programming microcontrollers, you may want to con-tinue from step 3 of the Quick Start ! sheet. Otherwise, chapters 5, 6 and 7 leadyou through writing, assembling and downloading your first program. Chapters 1and 2 provide some background on how microcontrollers work. Chapters 3 and 4describe the PIC family and the PIC-MDS in detail.

PIC

-MD

S

PIC-MDS

PIC Microcontroller Development System Training Manual

PIC

Microcontroller D

evelopment S

ystem T

raining Manual

Yes, it’s finally time to read the manual!PIC-MDS Setup

Page 199: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-1Appendix B

Troubleshooting©1998 Sirius microSystems

B Troubleshooting

Before resorting to incantations, rituals and spells, try the advice in this section. Then call the wizardsat Sirius microSystems.

Page 200: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-2 ©1998 Sirius microSystems

Page 201: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-3©1998 Sirius microSystems

Appendix BTroubleshooting

Troubleshooting

If you should encounter a problem with your PIC-MDS, EPIC Programmer orthe included software, please look in this section for descriptions that most closelyresemble the symptoms you observe before contacting Sirius microSystems for tech-nical support. Try the suggestions listed and if applicable re-read the section orsections of the training manual that describe the operation you were trying to per-form when you came across the problem.

Software Installation

If the installation program does not work correctly:

• Make sure the “PIC-MDS Programs and Subroutine Libraries” diskette is inyour floppy diskette drive and that your floppy diskette drive can read 3.5”high-density diskettes.

• Start the installation program by typing:

a:\install c: [Enter]

where a: is the device descriptor of your floppy diskette drive and c: is thedirectory on your hard disk to which you would like to install the PIC-MDSsoftware.

• Make sure that you insert the diskette labelled “EPIC Programmer” when re-quested and press any key.

• Make sure that you are installing the program from MS-DOS and not an MS-DOS session in Windows 3.x, Windows 95 or OS/2 Warp.

If the installed files are not in the volume or directory expected:

• Make sure that you specify a destination volume or directory name after theinstall command (see above).

Assembling Programs with ASM

If you get a “Bad Command or File Name” message:

• Make sure that you start the PM software from within the PICMDS subdirectoryon you hard disk, or that you create a path to the PICMDS directory. Type:

cd \picmds [Enter]

to make the PICMDS directory the current directory. Then type:

asm filename [Enter]

where filename is the name of the source text file that you wish to assemble.

• You do not need to type the .ASM extension after filename .

Page 202: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-4 ©1998 Sirius microSystems

If you get a “Fatal : [302] Unable to Open File” message:

• Make sure that the filename you typed following ASM exists and has a .ASMfilename extension.

• Make sure that any called subroutine files are in the PICMDS directory and thatthe names of the subroutine files are spelled properly in the source code.

If you get a “Error filename.ASM 1 : [202] Illegal Character” message:

• make sure that the file specified as filename.ASM is an MS-DOS format textfile or has been saved as MS-DOS text by a Word Processing program.

Starting the EPIC Programmer Software

If you get a “Bad Command or File Name” message:

• Make sure that you start the EPIC software from within the PICMDS subdirectoryon your hard disk, or that you create a path to the PICMDS directory. Type:

cd \picmds [Enter]

to make the PICMDS directory the current directory. Then type:

epic [Enter] or epic filename.hex [Enter]

to start the EPIC Programmer software, or in the second case to start the EPICProgrammer software with an object file to download.

If you get a “Programmer Not Found” message:

• If a previously programmed PIC microcontroller is in the microcontroller socketon the PIC-MDS board, you may have to press and hold the “RESET” buttonon the PIC-MDS while selecting “Retry” from the “Programmer not found”message window.

• Check that the 25 pin male-female cable is properly seated into both the compu-ter parallel printer port and the EPIC programmer connectors.

• Make sure that you are running the EPIC software from MS-DOS, and not froman MS-DOS session in Windows 3.x, Windows 95 or OS/2 Warp.

• If you are using an AC wall adapter, check that the correct adapter (usually 12VAC 500 mA) is plugged into a working receptacle and that its 2.1 mm coaxialconnector is plugged into the EPIC Programmer. Also make sure that the “BattON” shorting jumper has been removed from the EPIC Programmer.

• If you are using two 9 V batteries, check that the batteries have sufficient chargeand that the shorting jumper connects the two pins of the “Batt ON” header onthe EPIC Programmer.

• If the EPIC Programmer is connected to the PIC-MDS via the In-Circuit pro-gramming ribbon cable, make sure that the PIC-MDS is connected to an appro-priate power supply and is operating. Also, make sure that the PIC-MDS has amicrocontroller in the microcontroller socket as well as a crystal in Y1.

AssemblingPrograms with ASM

Page 203: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-5©1998 Sirius microSystems

Appendix BTroubleshooting

If the object code of the file does not appear in the EPIC window:

• The ASM batch file assembles the source code file (*.ASM) to produce a list-ing file (*.LST) and an object code file (*.HEX). Make sure that you specifythe object code filename with an .HEX extension. Note: EPIC also supports an.OBJ extension.

Downloading Programs

If you get a “Verify Error at ” message:

• Make sure that you are programming a blank microcontroller, or a PIC16C84which is electrically erasable, and that the microcontroller is properly pluggedinto the microcontroller socket on the PIC-MDS or the programming socket onthe EPIC Programmer.

• If the microcontroller to be programmed is in the PIC-MDS, make sure that theIn-Circuit programming ribbon cable is correctly attached to both the PIC-MDSand the EPIC Programmer. See the picture on the Quick Start ! sheet.

• Check that the 25 pin male-female cable is properly seated into both the compu-ter parallel printer port and the EPIC programmer connectors.

• If you are using an AC wall adapter, check that the correct adapter (usually 12VAC 500 mA) is plugged into a working receptacle and that its 2.1 mm coaxialconnector is plugged into the EPIC Programmer. Also make sure that the “BattON” shorting jumper has been removed from the EPIC Programmer.

• If you are using two 9 V batteries to power the EPIC Programmer, check thatthe batteries have sufficient charge and that the shorting jumper connects thetwo pins of the “Batt ON” header on the EPIC Programmer.

• Make sure that you are running the EPIC software from MS-DOS, and not froman MS-DOS session in Windows 3.x, Windows95 or OS/2 Warp.

Assembling, Downloading and Running Programs

If the PIC-MDS Chapter examples don’t work:

• Make sure that power is applied to the PIC-MDS. The top LED in the LED bargraph display lights when power is on. If this LED is off, compare the jumpersettings on the PIC-MDS with the defaults shown in Chapter 4 and reset thejumpers on the PIC-MDS before reapplying power.

• If you use a power supply instead of the wall adapter, check your connections tothe terminal strip with the schematic in Chapter 4. Also, ensure that JU1 andJU2 are set properly.

• Make sure that the PIC microcontroller is in the microcontroller socket on thePIC-MDS and that a crystal or resonator is in the crystal socket, Y1.

• Check the jumpers and the JU6 jumper block in particular to ensure that theymatch the defaults shown in Chapter 4.

Page 204: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

B-6 ©1998 Sirius microSystems

• Make sure that the program source files haven’t been inadvertently modified.Compare the source code to the original program source code in the Pull-OutProgram References section and if needed copy the original files from the “PIC-MDS Programs and Subroutine Libraries” diskette to your PICMDS directory.

For example, if the OUTPUT.ASM program from Chapter 5 doesn’t light theLEDs in a 10101010 pattern, the OUTPUT.ASM code in your PICMDS direc-tory may have been modified. Copy the original from the PIC-MDS Programsand Subroutine Libraries disk to your PICMDS directory by typing:

copy a:\output.asm c:\picmds [Enter]

• Read the comments at the beginning of the source code. Jumper settings andspecial requirements are explained here.

• Check to make sure that the bottom of the PIC-MDS is clean and free of debrisand that the PIC-MDS is resting on a non-conductive surface.

Converting PIC-MDS Source Codefor Third-Party Tools

If you use a third-party assembler:

• Comment out or remove the “MACLIB” directive. While most other assem-blers do not require you to explicitly specify the target device, the MACLIBdirective allows the PIC Macro Assembler (PM.EXE) to easily accommodatenew Microchip microcontrollers.

• Check your assembler documentation to see if the “DEVICE” directive is sup-ported. Parallax and microEngineering Labs assemblers use the DEVICE di-rective to set configuration fuses and ID bytes.

• Check the default radix of your assembler. PM assumes a default decimal radixif no suffix follows the number.

• PM uses a suffix to denote a numerical radix. For example, 11 represents eleven,11B represents the number three and 11H represents the number seventeen.Some assemblers require a prefix or an alternate suffix.

• Both PM and Parallax tools support local assembly labels. Local labels areprefixed with a colon (:). If your assembler does not support local labels, changeeach local label to a unique label.

Assembling,Downloading andRunning Programs

Page 205: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-1©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

C PIC Macro AssemblerReference

Page 206: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-2 ©1996 microEngineering Labs

Copyrights and Trademarks

Copyright © 1996, microEngineering Labs.

Parallax is a trademark of Parallax, Inc.PIC is a Registered Trademark of Microchip Technology, Inc.

Disclaimer of Liability

microEngineering Labs is not responsible for special, incidental, orconsequential damages resulting from any breach of warranty, or under anylegal theory, including lost profits, downtime, goodwill, damage to orreplacement of equipment or property, or any costs for recovering,reprogramming, or reproducing any data used with microEngineering Labs'products.

Page 207: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-3©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

Table of Contents1. Assembler Overview C-7

Compatibility ................................................................................ C-7Operation ..................................................................................... C-7Symbol Names ............................................................................ C-7Numbers ...................................................................................... C-7Strings ......................................................................................... C-7

2. Command Line Options C-72.1. Usage ................................................................ C-72.2. The PM Environment Variable ........................... C-82.3. Options .............................................................. C-8

2.3.1. Option -C ........................................................................... C-92.3.2. Option -D ........................................................................... C-92.3.3. Option -ELext .................................................................... C-92.3.4. Option -EMext ................................................................... C-92.3.5. Option -EOext ................................................................... C-92.3.6. Option -ESext .................................................................... C-92.3.7. Option -EIext ..................................................................... C-92.3.8. Option -G# ....................................................................... C-102.3.9. Option -Ipath ................................................................... C-102.3.10. Option -Lname .............................................................. C-102.3.11. Option -OB .................................................................... C-102.3.12. Option -OH .................................................................... C-102.3.13. Option -Q ....................................................................... C-10

3. Pseudo-Ops C-113.1. CODE .............................................................. C-113.2. DATA................................................................ C-113.3. EEPROM ......................................................... C-113.4. ABS ................................................................. C-113.5. ORG................................................................. C-113.6. DS.................................................................... C-123.7. DB.................................................................... C-123.8. DW .................................................................. C-123.9. EQU ................................................................. C-123.10. =..................................................................... C-12

4. Conditional Assembly C-124.1. IF...................................................................... C-134.2. ELSEIF ............................................................ C-134.3. ELSE ............................................................... C-134.4. ENDIF .............................................................. C-13

Page 208: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-4 ©1996 microEngineering Labs

4.5. IFDEF .............................................................. C-134.6. IFNDEF ............................................................ C-134.7. IFB ................................................................... C-134.8. IFNB................................................................. C-13

5. Macro Facility C-145.1. REPT ............................................................... C-145.2. IRPC ................................................................ C-145.3. IRP ................................................................... C-145.4. MACRO ........................................................... C-145.5. LOCAL ............................................................. C-145.6. EXITM .............................................................. C-155.7. ENDM .............................................................. C-15

6. File Controls C-156.1. INCLUDE ......................................................... C-156.2. MACLIB ........................................................... C-15

7. File and Listing Controls C-167.1. TITLE ............................................................... C-167.2. PAGE ............................................................... C-167.3. LIST ................................................................. C-167.4. NLIST............................................................... C-167.5. MTLIST ............................................................ C-167.6. NMTLIST ......................................................... C-167.7. CLIST............................................................... C-177.8. NCLIST ............................................................ C-177.9. LALL ................................................................ C-177.10. XALL .............................................................. C-177.11. SALL .............................................................. C-17

8. Device Controls C-178.1. DEVICE ........................................................... C-17

8.1.1. Fuse Specifier ................................................................. C-178.1.2. Core Specifier ................................................................. C-188.1.3. Reserved Options ........................................................... C-18

8.2. ID ..................................................................... C-188.3. RESET............................................................. C-19

9. Expressions C-199.1. Calculations ..................................................... C-19

Table of Contents

Page 209: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-5©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

9.2. Operators ......................................................... C-199.2.1. Bit Extension ................................................................... C-209.2.2. Modulus ........................................................................... C-209.2.3. Shift Right ........................................................................ C-209.2.4. DEF & REF...................................................................... C-20

9.3. Numeric Constants ......................................... C-219.4. String Constants .............................................. C-219.5. List Quoting ...................................................... C-219.6. Identifiers ......................................................... C-22

9.6.1. Identifiers Starting with ‘:’ ................................................ C-22 9.6.2. Identifiers Starting with ‘$’ .............................................. C-229.6.3. Identifiers Starting with ‘_’ ............................................... C-229.6.4. Identifiers Starting with ‘@’ ............................................. C-22

9.7. System Variables ............................................. C-229.7.1. $ ...................................................................................... C-229.7.2. DEVICE ........................................................................... C-23

10. File Formats C-2310.1. Source File ..................................................... C-2310.2. Map File ......................................................... C-2310.3. Binary Output File .......................................... C-2310.4. Merged Intel HEX File .................................... C-23

10.4.1. PIC16C5x Device Descriptor ........................................ C-2410.4.2. PIC16Cxx Device Descriptor ......................................... C-24

10.5. Symbol Table File........................................... C-2510.6. Listing File ...................................................... C-25

11. Assembling Existing Parallax Code C-26

12. Warnings C-27100 Attempt to Skip MultiByte OpCode @ Address ................. C-27101 Use of Local Label Prior to Use of Non-Local Label ......... C-27102 Code Crosses Boundary @ Address ................................. C-27104 Called Addresses must Reside in Lower Half of Page ...... C-27105 Bit Addresses are the Same .............................................. C-27 106 Register Addresses are the Same .................................... C-27

13. Errors C-28200 Instruction Restricted to 14-Bit Core .................................. C-28201 ‘Character’ Expected.......................................................... C-28202 Illegal Character ‘Character’ .............................................. C-28203 ‘—’ or ‘++’ Expected ........................................................... C-28204 ‘W’ Expected as First Parameter ....................................... C-28205 Illegal Use of Keyword ‘Keyword’ ....................................... C-28206 CHECKSUM Not Supported in 14-Bit Core ....................... C-28208 Illegal Use of SUB Instruction ............................................ C-28

Page 210: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-6 ©1996 microEngineering Labs

209 Indirect Jump Expected in Form of ‘PC+W’ ....................... C-29210 Bit Addresses Must Differ................................................... C-29211 Poorly Formed Numeric Constant ‘Token’.......................... C-29212 Extra Tokens on End of Line .............................................. C-29213 IRPC Expected Id or String Constant ................................ C-29214 IRPC Missing Replacement Parameter ............................. C-29215 Attempt to Redefine Macro ‘Identifier’ ............................... C-29216 Attempt to Redefine Macro Parameter ‘Identifier’ ............. C-29217 Attempt to Generate Code in Non-Code Segment ............ C-29218 Address Limit of Address Exceeded .................................. C-30219 Collision in HEX File @ Address ........................................ C-30220 Illegal Bit Number ............................................................... C-30221 Illegal Bit Address .............................................................. C-30222 Illegal Destination Specifier ................................................ C-30223 Illegal TriState File Register Address Register .................. C-30224 Keyword Directive Only for Use in Macros ........................ C-30225 Undefined Symbol ‘Identifier’ ............................................. C-30226 Numeric Constant or Symbol Name Expected .................. C-31227 Divide by Zero .................................................................... C-31228 Modulus by Zero ................................................................ C-31229 Device Doesn’t Support EEPROM..................................... C-31230 Collision in EEPROM @ Address .................................... C-31231 Attempt to Redefine ‘Identifier’ .......................................... C-31232 File Name Expected .......................................................... C-31233 String Expression Expected for Title .................................. C-31234 Identifier Expected ............................................................. C-31235 Opcode Expected Instead of ‘Token’ ................................. C-31236 Label ‘Identifier’ Undefined in Pass 0 ................................ C-32237 IRP Missing Replacement Parameter ................................ C-32

14. Fatal Errors C-32300 Too Many Errors ................................................................. C-32301 Out of Memory ................................................................... C-32302 Unable to Open File ‘Filename’.......................................... C-32303 Unable to Create File ‘Filename’ ........................................ C-32304 No Source File Specified ................................................... C-33305 Unable to Write to File ‘Filename’ ...................................... C-33306 Page Width must be 80 to 255 Columns ........................... C-33307 Illegal Device Type ............................................................. C-33308 Macro Buffer Overflow ....................................................... C-33

15. Internal Errors C-33400 Attempt to Free Non-Allocated Memory [Pointer] .............. C-33401 Attempt to Reference Non-Allocated Memory [Pointer] .... C-33402 Attempt to Pop Empty Symbol Table Stack ....................... C-33403 Attempt to Exit on Empty File Stack .................................. C-33404 Attempt to Pop Empty Macro Stack ................................... C-33405 Macro Stack Error .............................................................. C-33406 Attempt to Pop Empty Conditional Assembly Stack .......... C-33407 No Function Handler for ‘Keyword’ .................................... C-33

Table of Contents

Page 211: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-7©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

1. Assembler Overview

Compatibility

Microchip & Parallax Instruction SetsMicrosoft Compatible MacrosSupports all 12-bit (16C5x) and 14-bit (16Cxx) PICs

Operation

Two-Pass AssemblyOperator precedence in evaluation of expressionsConditional AssemblyListing ControlsSeparate Code, Data and EEPROM Segments

Symbol Names

Symbols up to 32 of the following characters :: @ $ _ A-Z 0-9First character must be legal character other than 0-9.Special Uses :$ Reserved for Debugger Commands_ Reserved for Compilers@ Temporary Labels: Local LabelsCase sensitivity is optional.Program labels must begin in column 1.Non-labels must not begin in column 1.

Numbers

Default Radix is 10. All numbers must begin 0-9. An alternate radix may beselected with one of the following suffixes :

B BinaryO OctalH HexadecimalRadix suffixes are not case sensitive. All numbers are kept in 32 bit two’s com-

plement form (-231 to 231-1).

Strings

Strings are enclosed by a matching pair of single or double quotes. No stringoperations are allowed.

2. Command Line Options

2.1. Usage

PM can be invoked from the DOS command line using the following commandformat :

PM Options filename

Page 212: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-8 ©1996 microEngineering Labs

Zero or more options can be used to modify the manner in which the assemblerprocesses the input file. Options begin either with a slash ( ‘/’ ) or a minus ( ‘-’ ). Thecharacter following the minus is a letter which selects the option. Additional charac-ters may be needed by some options to supply additional information. No spaces mayoccur within an option. Options not recognized by the assembler will generate errorsand be ignored.

The first parameter not starting with a minus or a slash is assumed to be thefilename. Extra parameters are ignored.

If PM is invoked with no options and no filename, a brief help screen is dis-played.

2.2. The PM Environment Variable

With programming tools, a programmer will often want certain options to beinvoked consistently. This usually requires the programmer to invoke these optionseach time the tools is used. While batch files and makefiles can reduce this tedium,problems can also occur due to DOS limits on the length of command lines.

In order to alleviate these problems, the assembler uses a DOS environmentvariable named PM. This contains a string of command line options which are im-plicitly selected whenever the assembler is invoked. It uses the same format as theoptions selected on the command line. Once these have been processed, then normalcommand line options are processed and the file is assembled. Thus, you can use PMto override the assembler defaults and then use the command line to override PMdefaults. This allows a great deal of customization to the assembler.

For example, suppose you want the PIC Macro Assembler to look more like theoriginal Parallax assembler. No problem - simply add the following to yourAUTOEXEC.BAT :

set PM=-EOOBJ

This changes the extension of the output filename from ‘HEX’ to ‘OBJ’.

2.3. Options

Option Option DescriptionC Identifiers to be Case SensitiveD Generates Listing, Symbol Table, and Map FileEcext Sets filename extension for specified file type

L = Listing FileM = Map FileO = Output FileI = Input FileS = Symbol Table

G# Set maximum error countIpath Set default INCLUDE/MACLIB directory

Command LineOptions

Page 213: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-9©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

Option Option DescriptionLname Generate listing (listing filename is optional)Of Set output format

B = BinaryH = Merged Intel HEX

Q Force use of explicit extension of source filename

2.3.1. Option -C

By default, all items in PM are case insensitive. Thus, MIXED, Mixed, mixed,and mIXEd would all be treated as the same label or macro. When the -C option isinvoked, identifiers are case sensitive. In this mode, the sample identifiers would allbe treated as unique. In either mode, opcodes and pseudo-ops are always case insen-sitive. This mode is generally intended for use by compilers where case is important(such as C).

2.3.2. Option -D

PM normally assembles a source file and outputs an executable equivalent of theprogram. When the -D option is invoked, a listing, a map and a symbol table are alsogenerated. This options is mainly used to generate information for debuggers.

2.3.3. Option -ELext

2.3.4. Option -EMext

2.3.5. Option -EOext

2.3.6. Option -ESext

The names for listing, map, output and symbol table files are generated auto-matically by the assembler. These names are created by taking the base name of thesource file (up to 8 characters) and appending an extension indicating file type. Thedefault extensions are :

File Type Default ExtensionListing LSTMap MAPOutput HEX or BINSymbol Table SYM

These files are placed in the current directory. The -E options allows these de-fault extensions to be changed. If the specified default is longer than 3 characters, itis truncated without warning or error. This option can be used to make the outputs ofPM easier to use with various debugging platforms.

2.3.7. Option -EIext

Whenever the assembler is invoked, it checks the name of the source file for anextension. If one is explicitly defined, it is used. If none is defined, then the assemblerappends a default input extension to the filename. By default, this extension is SRC.The -EI option can be used to change this default to any three letter combination. Ifthe specified default is longer than 3 characters, it is truncated without warning orerror.

Page 214: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-10 ©1996 microEngineering Labs

The -Q option can be used to force the programmer to always specify the filenameextension, if any. Thus, -Q negates the use of the -EI option.

2.3.8. Option -G#

PM can generate an unlimited number of warning. For the sake of clarity, how-ever, it limits the number of errors that can be generated. By default, PM terminateswith a fatal error if 15 or more errors occur. Using the -G option, this value may bechanged to any arbitrary number.

2.3.9. Option -Ipath

Whenever the assembler encounters an INCLUDE or MACLIB directive, a searchis conducted for the specified file. If a path is explicitly specified, that directory issearched. If the file is not found, a fatal error is generated.

If no path is specified, the file is first sought in the current directory. If not foundthere, then the system header directory is searched. By default, this directory is theINC subdirectory of the directory from which PM is executed. If also not found here,a fatal error is generated.

The -I option can be used to specify the new path of this default directory. Wheninvoked, the path specified by the -I option is not checked for validity. Thus, specify-ing a non-existent or erroneous path can cause header files to seem to mysteriouslydisappear (i.e. the assembler can’t find them because the directory doesn’t exist).

2.3.10. Option -Lname

When used, the -L option causes the assembler to generate a listing file in addi-tion to the normal executable image generated. When used by itself, the listing isplaced in a file whose name is created by appending the listing extension (default isLST) to the base name of the source file. If the -L options is used to specify a filename,the listing is generated to the named file.

Note that even if the -D option (which by default generates a listing) is used, the-L option can still be valuable, because it allows you to specify the name and path ofthe listing file.

2.3.11. Option -OB

By default, PM generates Merged Intel HEX format for the executable image.The -OB option allows the assembler to generate 16-bit binary format.2.3.12. Option -OH

The -OH option forces PM to generate the executable image in the Merged IntelHEX format. This option is mainly useful to override the use of the -OB option thatmight be specified in the PM environment variable.

2.3.13. Option -Q

Normally, when no extension is explicitly specified for the source, PM appendsa default extension to the filename (SRC by default). The -Q option prevents this andforces the programmer to explicitly define the extension (if any) of the source filename.

Command LineOptions

Page 215: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-11©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

3. Pseudo-Ops

3.1. CODE

CODE [ Expr ]

The code segment manages the program space of the PIC. The CODE pseudo-opselects the code segment as the current segment. All bytes generated in the codesegment are placed in the executable image file. The optional expression may be usedto set the load pointer for the code segment.

3.2. DATA

DATA [ Expr ]

The data segment manages the RAM space of the PIC. The DATA pseudo-opselects the data segment as the current segment. Generation of code or initialized datain this segment results in an error (due to the Harvard architecture of the PIC). Thus,DS is the only usable pseudo-op in the data segment. The optional expression may beused to set the load pointer for the data segment.

3.3. EEPROM

EEPROM [ Expr ]

The EEPROM segment manages the EEPROM space available in the 8x familyof PICs. The EEPROM pseudo-op selects the EEPROM segment as the currentsegment. Generation of code in this segment results in an error (due to the Harvardarchitecture of the PIC). Thus, DS, DB and DW are the only usable pseudo-ops inthe EEPROM segment. The optional expression may be used to set the load pointerfor the EEPROM segment.

3.4. ABS

ABS [ Expr ]

Sets the current segment to the absolute segment. This is the default segment andoperates in the mode most familiar to programmers as “absolute” assembly. All bytesgenerated in this segment are placed in the executable image file. The DS commandmerely advances the load pointer. The optional expression may be used to set the loadpointer for the absolute segment.

3.5. ORG

ORG Expr

Sets the load pointer for the current space. The user may get the current value ofthe load pointer for the current segment via the system variable $.

Page 216: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-12 ©1996 microEngineering Labs

3.6. DS

DS Expr

Advances the load pointer by the specified value. DS is normally used to allocatespace within the data or EEPROM segments. When used in the EEPROM segment,no data is generated in the HEX file for the allocate locations. This allows EEPROMlocations to be allocated that will not be programmed (assuming your programmerdoesn’t unconditionally program all EEPROM locations).

3.7. DB

DB (Expr|String) { , (Expr|String) }

Stores one or more constant bytes in the current segment. In the case of numericconstants, the resulting values (truncated to 8 bits, if necessary) are stored. Stringconstants are stored as consecutive bytes.

Since the PIC cannot store data in the code space directly, each byte generated inthe code segment is actually stored as a RETLW instruction. Bytes generated in theEEPROM segment are stored merely as data. And, of course, bytes generated to thedata segment result in errors.

3.8. DW

DW Expr { , Expr }

Stores the resulting value in the current segment. The value is truncated to 16-bits. The least significant byte is stored first. Each byte is generated in the samemanner as the DB pseudo-op.

3.9. EQU3.10. =

Label EQU ExprLabel = Expr

Assigns a numeric value to the specified symbol. The two operations are similar,except it is an error to redefine a symbol created using the EQU pseudo-op. Symbolscreated using the = may be reassigned value without error.

4. Conditional Assembly

Note: PM requires that all symbols be defined at the end of the first pass. In orderto meet this requirement, the evaluation of all conditional assembly constructs mustbe consistent in both passes. Thus, unlike other assembler features, conditional as-sembly may not assemble correctly if it relies on forward references.

Pseudo-Ops

Page 217: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-13©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

4.1. IF4.2. ELSEIF4.3. ELSE4.4. ENDIF

IF Expr...

ELSEIF Expr...

ELSE...

ENDIF

Assembly continues following the first true (i.e. non-zero) expression in the se-ries of IF and ELSEIF statements and continues until the next statement in theIF..ELSE..ENDIF chain. If no statement is true and an ELSE statement is present,the code between ELSE and ENDIF is assembled. The IF and ENDIF terms aremandatory. One ELSE and multiple ELSEIF terms are optional.

4.5. IFDEF4.6. IFNDEF

IFDEF LabelIFNDEF Label

The IFDEF and IFNDEF statements may be substituted for the IF term in theIF..ELSE..ENDIF construct. IFDEF evaluates true if the specified symbol is de-fined. IFNDEF evaluates true if the specified symbol is not defined. There are noIFDEF/IFNDEF replacements for the ELSEIF statement.

The DEF operator may be used for more complicated variations on the IFDEF/IFNDEF pseudo-ops.

4.7. IFB4.8. IFNB

IFB [ Item ]IFNB [ Item ]

The IFB and IFNB statements may be substituted for the IF term in theIF..ELSE..ENDIF construct. IFB evaluates true if an item is listed on the line follow-ing the IFB statement. IFNB evaluates true if no item is listed on the line followingthe IFNB statement. There are no IFB/IFNB replacements for the ELSEIF state-ment.

Comments are treated as blanks in the evaluation of IFB and IFNB statements.These constructs are mainly useful in macros to test whether a parameter has beenspecified by the caller or has been omitted.

Page 218: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-14 ©1996 microEngineering Labs

5. Macro Facility

5.1. REPT

REPT ExprBodyENDM

The body of the macro is repeated the number of times specified by the numericexpression. The REPT macro is executed immediately.

5.2. IRPC

IRPC Param , StringBodyENDM

The body of the macro is repeated once for each character in the specified string.The specified parameter is substituted on each expansion with the scanned character.The IRPC macro is executed immediately.

5.3. IRP

IRPParam , < Expr { , Expr } >BodyENDM

The IRP macro is similar to the IRPC macro, except that items from the speci-fied list (bracketed with < and >) are substituted for the specified parameter. The IRPmacro is executed immediately.

5.4. MACRO

Label MACRO Param { , Param }BodyENDM

Unlike other macro types, MACRO merely creates a template for later macroexpansions. MACRO accepts up to 32 identifiers as parameters. Whenever found inthe body (even in quotes), these parameters are substituted with the value specifiedwhen the macro is invoked. Macros are invoked just as any other pseudo-op or opcode.Parameters specified in the definition but not assigned values when invoked are leftunsubstituted. This allows macros with a variable number of parameters if used withthe IFB and IFNB conditional assembly constructs.

Since a macro’s name is a label, it must begin in column 1.

5.5. LOCAL

LOCAL Symbol { , Symbol }

Macro Facility

Page 219: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-15©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

Allows the creation of local symbols in any macro type. A unique temporarysymbol is created for each local symbol for every expansion of the macro’s body.Any number of LOCAL statements may be defined, but they must immediately fol-low the macro definition (REPT, IRPC, IRP or MACRO pseudo-op). Local symbolstake the form @@NNNN, where NNNN is a four digit decimal number assignedsequentially from 0000.

5.6. EXITM

Allows premature abortion of macro expansion. This is useful for implementingloops whose lengths are not determinant.

5.7. ENDM

All macro definitions are terminated by the ENDM pseudo-op.

6. File Controls

6.1. INCLUDE

INCLUDE String

The INCLUDE statement is replaced with the contents of the specified file. If nopath is specified, the file is searched for first in the current directory. If not found,then the system header directory is searched. If still not found, an error results.

By default, the system header directory is the INC subdirectory of the directoryfrom which PM.EXE is executed. This directory contains files defining importantconstants and macros for each of the PICs supported. This can be changed by the useof the -I command line option.

6.2. MACLIB

MACLIB String

MACLIB is identical in operation to INCLUDE, except that the file is onlyparsed on the first pass. This is intended for use on include files that contain onlymacro and symbol definitions.

Avoid the use of MACLIB if the file includes any opcodes. If used on such a file,the file will affect assembly on the first pass, but not on the second. This can createmajor discrepancies in the second pass of assembly and usually results in a largenumber of confusing error.

Page 220: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-16 ©1996 microEngineering Labs

7. File and Listing Controls

7.1. TITLE

TITLE String

Specify the title at the top of every page in listing file.

7.2. PAGE

PAGE Expr , ExprPAGE ExprPAGE

If the first parameter is defined, it sets the page width for the listing. The pagewidth must be between 80 and 255 characters (default is 132). Characters beyondthis width are truncated from the listing. If the second parameter is defined, it sets thepage length of the listing (default is 60). If the page length is set 0, no automatic pagebreaks are generated.

If the PAGE pseudo-op is used without parameters, it forces a page break in thelisting.

7.3. LIST7.4. NLIST

If the -L option is used, the listing counter is initialized to 1. Otherwise, it de-faults to an initial value of 0. LIST increments the listing counter. NLIST decrementsthe listing enable counter. Whenever the listing counter is positive, lines are gener-ated for the listing.

This simple arrangement allows a greater flexibility in listing control than didearlier versions of PM. For example, the source file may contain listing controlswithout unconditionally generating a listing.

7.5. MTLIST7.6. NMTLIST

If the MTLIST pseudo-op is used, enough lines are generated to display all bytesgenerated by the listed statement. This is the default.

If the NMTLIST is pseudo-op is used, only one line is listed for each line ofsource code. If a line generates more than 4 words of code, additional bytes are notdisplayed and the line is marked with an ‘#’.

File and ListingControls

Page 221: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-17©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

7.7. CLIST7.8. NCLIST

The CLIST pseudo-op forces all portions of IF..ELSE..ENDIF constructs to belisted. This is the default.

The NCLIST pseudo-op forces only those portions of IF..ELSE..ENDIF con-structs that are assembled to be listed. The conditional statements themselves arealways listed, although nested IF..ELSE..ENDIF constructs in unassembled blocksof code are not listed.

7.9. LALL7.10. XALL7.11. SALL

If LALL pseudo-op is used, all lines of a macro expansion are listed. This is thedefault.

If XALL pseudo-op is used, only those lines of a macro expansion which gener-ate code are listed.

If SALL pseudo-op is used, no lines of a macro expansion are listed.

8. Device Controls

PM was written to be compatible with all 12-bit and 14-bit PICs. The assemblerwas designed to handle the architectural limits of both core types. Each programmust specify which core and a specific set of capabilities by using the DEVICEstatement.

8.1. DEVICE

DEVICE Expr { , Expr }

The DEVICE pseudo-op takes one or more comma separated 32-bit expressionsas parameters. The bits 31 and 30 of each value distinguishes one of four separateprocessor specifications. These two bits determine how the remaining thirty bits ofthat value are interpreted.

8.1.1. Fuse Specifier

If the upper two bits of a parameter are 00, this word defines the configurationfuses. PM allows arbitrary control of a 14-bit fuse word. When a fuse specifier isused, two actions are taken:

• The current fuse value is ANDed with the upper 16 bits of the 32 bit word.

• The resulting fuse value is then ORed with the lower 16 bits of the 32 bit word.

Page 222: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-18 ©1996 microEngineering Labs

This system allows one or more values to be chained together to control variousbit locations in the fuses. These may occur in any order or even in multiple DEVICEstatements. The actual values used to set the fuses are normally defined in the headerfile defined for a particular component or family of components. Below is a partialtable containing the most common fuse specifiers. For a full list, consult the deviceheader for your particular device.

DEVICE Parameter DescriptionRC_OSC RC OscillatorHS_OSC HS OscillatorXT_OSC XT OscillatorLP_OSC LP OscillatorBOD_ON Brown-Out Detection EnabledBOD_OFF Brown-Out Detection DisabledPROTECT_ON Code Protection EnabledPROTECT_OFF Code Protection DisabledWDT_ON Watch Dog Timer EnabledWDT_OFF Watch Dog Timer Disabled

8.1.2. Core Specifier

The core specifier defines the processor’s core type (12 bit or 14 bit) and theamount of ROM/EEPROM available. This information is needed to generate coreappropriate instructions and to perform range checking on addresses.

Additionally, an arbitrary 8-bit numeric code may be assigned to the processor.While PM doesn’t use this information, it is embedded in the output file and thisinformation is used by some simulators, programmers, and other third party develop-ment tools. There is no standardization (among tool providers) on these numbers.

No attempt is made to provide RAM availability information. The asymmetry ofdata pages makes it difficult to perform error checking without generating warningson valid instructions.

Unlike fuse specifiers, a core specifier must be set in one value - it lacks therunning accumulation effect of fuse specifiers.

8.1.3. Reserved Options

The two remaining DEVICE fields (10 and 11) are reserved for future use. AnyDEVICE value containing these upper 2 bits will generate an error.

8.2. ID

ID ExprID StringID CHECKSUM

Each PIC has a 16-bit (12-bit core) or 28-bit (14-bit core) ID. This value can beset in one of three methods. A numeric expression or string constant can be used foreither core type. For 12-bit cores only, the reserved word CHECKSUM may be used.

Device Controls

Page 223: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-19©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

This forces the Parallax PIC Programmer to compute the checksum of the PICcode space.

8.3. RESET

RESET Expr

Each time a PIC is powered up or reset, the PC is set to a determinant spot. It isassumed that the programmer will use this knowledge to get his program to startexecuting whenever the PIC is ready. The most common method of doing this is toplace a GOTO instruction at this spot. In the 12 bit core, execution begins with thelast word of ROM. In the 14 bit core, execution begins at 0000h.

The RESET pseudo-op places a GOTO at the correct address determined for thecurrent processor type (as set by the DEVICE pseudo op). The RESET command ismost commonly used in programs for 12-bit cores.

9. Expressions

9.1. Calculations

Even though PIC processors only handles 8-bit math and use 11-bit or 13 bitaddresses, PM performs all calculations and stores all constants 32-bit, two’s com-plement form.

No string operations are available.

9.2. Operators

Operator Function Unary Precedence( ) Grouping Operators x 1REF Label Reference x 2DEF Label Defined x 2- Unary Minus x 2+ Unary Plus x 2~ Bitwise NOT x 2! Logical NOT x 2HI MSB of Word x 2LO LSB of Word x 2* Multiply 3/ Divide 3% Modulus 3>> Shift Right 4<< Shift Left 4

continued on next page..

Page 224: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-20 ©1996 microEngineering Labs

Operator Function Unary Precedence- Subtract 5+ Addition 5= Equivalence 6<> Inequality 6< Less Than 6> Greater Than 6<= Less Than or Equal 6>= Greater Than or Equal 6& Bitwise AND 7^ Bitwise XOR 8| Bitwise OR 8. Bit Address Operator 9

Expressions are resolved from left to right using operator precedence to resolveambiguities in evaluation. The precedence of each operator is shown. Operators withthe highest precedence (i.e. those which are evaluated first) are show as precedence_1.

9.2.1. Bit Extension

Whenever bits in a number are inverted, this inversion occurs in all 32 bits. Thiscauses the bit-wise inversion and negation of byte-sized numbers with 1’s in theupper bits. This, however, isn’t usually a problem, since opcodes usually truncatecalculated values to the appropriate size without generating warnings or errors.

9.2.2. Modulus

Modulus is the proper name for what you may have learned in school as the“remainder”. In short, it is value that is “left over” when one integer value is dividedby another. In systems which support signed numbers, there is some ambiguity as tothe sign of the remainder for negative numbers. PM returns a modulus with the samesign as the dividend.

9.2.3. Shift Right

Shift right is often used as a fast-divide for binary values (e.g. shifting right by 3bits is the same as dividing by 8). Since PM works with signed numbers, a numbershifted right will retain the value of the 32nd bit (i.e. sign extension).

9.2.4. DEF & REF

DEF ( LabelList )REF ( LabelList )

In order to allow PM to simulate a linking library, the DEF and REF operatorsare defined. The DEF operator returns true (1) if the specified label(s) have beendefined earlier in the program. Similarly, the REF operator returns true (1) if thespecified label(s) have been used (referenced) earlier in the program. Both return 0 ifthe tested condition is false.

To increase flexibility, more than one label may be tested. In fact, logical opera-

Expressions

Page 225: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-21©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

tors (‘|’ for OR and ‘&’ for AND) and parenthesizes have are supported for complexlabel lists.

9.3. Numeric Constants

All numbers default to radix 10. All numbers (regardless of radix) must beginwith digits 0-9. Other bases may be selected by appending the following suffixes.Suffixes are not case sensitive.

B BinaryO OctalH Hexadecimal

9.4. String Constants

PM supports string constants mainly for the purpose of generating strings ofRETLWs (via the RETW opcode and DB pseudo-op). Strings may be enclosed byeither single ( ‘ ) or double ( “ ) quotes. If single quotes are used, then double quotesmay be used freely within the string, and vice versa. Single quotes may not appearwithin a single quoted string and double quotes may not appear within a doublequoted string.

String constants may also be used to drive the IRPC macro pseudo-op. On eachexpansion of the IRPC macro, the replacement parameter is replaced with an unquotedcharacter. When used as a parameter for macros defined using the MACRO pseudo-op, the quoted string is passed unmodified (quotes intact).

9.5. List Quoting

The IRP macro is driven by a list of comma separated items bracketed with <and > characters. This item can be so useful, that < and > have been given a special“quoting” function in macros. When the < character is encountered in the parameterlist for a macro defined using the MACRO pseudo-op, the parameter is considered tocontain all characters up to the next >. This type of bracketing may not be nested.When this parameter is substituted, the < and > are stripped from the substitution.

1 defb1 macro list2 irp item,<list>3 db item4 endm5 endm67 defb2 macro list8 db list9 endm1011 defb1 <1,�One�,2,�Two�>+ irp item,<1,�One�,2,�Two�>+ db item+ endm+ 000- 801 db 1+ 001- 84F 86E 865 db �One�+ 004- 802 db 2+ 005- 854 877 86F db �Two�12 defb2 <1,�One�,2,�Two�>+ 008- 801 84F 86E 865 db 1,�One�,2,�Two�

00C- 802 854 877 86F

Page 226: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-22 ©1996 microEngineering Labs

9.6. Identifiers

Identifiers are the names used as program labels, variables and macro names.Although they can be any length, only the first 32 characters are significant and theymust be unique in these 32 characters. Identifiers differing only in the 33rd or latercharacter are considered identical. Identifiers consist of any of the following charac-ters :

A-Z 0-9 : @ $ _

Identifiers may begin with any of these characters except 0-9. The first charactermay have a special meaning, as described in the following sections.

9.6.1. Identifiers Starting with ‘:’

Symbols starting with a colon ( ‘:’ ) are local symbols. This method appends thislocal label to the last non-local label (i.e. label beginning with other than a colon).This allows simple labels within a global block not to pollute valuable name space.The labels can be referenced within this local block using the abbreviated local name.To reference this label outside the block, the full form needs to be used (i.e. nonlocal:local).

9.6.2. Identifiers Starting with ‘$’

Symbols starting with the dollar sign ( ‘$’ ) are reserved for future debugginguse. Currently, only one symbol starting with the dollar sign is reserved by the as-sembler, which is the dollar sign itself. It is used to get the value of the load pointerfor the current segment.

9.6.3. Identifiers Starting with ‘_’

Symbols starting with the underscore ( ‘_’ ) are reserved for use by compilers.

9.6.4. Identifiers Starting with ‘@’

Symbols starting with the at symbol ( ‘@’ ) are treated as temporary labels.Temporary symbols are treated just like other labels, except they are not included inthe symbol table. The LOCAL pseudo-op generates symbols in the form of@@NNNN, where NNNN is a four digit decimal number starting with 0000.

9.7. System Variables

In order to make programming easier, PM defines some system variables. Youcannot redefine these variables, although they can be used as you would other vari-able.

9.7.1. $

The dollars sign ( $ ) is used to get the value of the load pointer for the currentsegment. Each of the four segments (CODE, DATA, EEPROM and ABS) has itsown load pointer. Therefore, the value of $ depends on the segment in which it ap-pears.

Expressions

Page 227: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-23©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

9.7.2. DEVICE

DEVICE returns the core specifier. For details on these flags, see the descriptionof the DEVICE pseudo-op.

10. File Formats

10.1. Source File

; Test File for PIC Macro Assembler

include �T13.INC� ; Show Include File

SIZE equ 10h ; Show Assignment Statementmac �uChip� ; Show Macro Expansion

nmtlist ; Suppress Multi Line Listingdb �uChip� ; Generate Constantsmac �uChip� ; Expand & Generate Constants

PM uses a common collimated format for the input (or source) file. This is thesame format as used by the original Parallax PIC assembler. Items starting in column1 are either labels, variables, or macro names. Items beginning in column 2 or laterare assumed to be opcodes or pseudo ops. Depending on the opcode or pseudo-op,zero or more comma separated parameters may follow the opcode/pseudo-op. Com-ments (which begin with a semicolon) may begin in any column.

10.2. Map File

The MAP file is used to link the executable file to the source file. The MAP filecontains one 16-bit number (2 bytes) for each word in the code space of the targetprocessor. This 16-bit number (stored LSB first) is the number of the line in thesource file which generated the corresponding instruction in the executable image.No provisions are made for mapping instructions on to lines in generated in IN-CLUDE or MACLIB files.

10.3. Binary Output File

The simplest output format of PM is the 16-bit binary format. The binary filecontains one 16-bit word (2 bytes) for each word in the code space of the targetprocessor. This word (stored LSB first) contains the actual PIC opcode for the corre-sponding address (i.e. the first word of the file corresponds to address 000h in thetarget processor). The most significant bits of the word which are unused by theprocessor (4 in the 12-bit core, 2 in the 14-bit core) are zeroed. Addresses not as-signed values by the assembler are stored with all 1’s (0FFFh in the 12-bit core,3FFFh in the 14-bit core).

10.4. Merged Intel HEX File

The default output format of PM is the Merged Intel HEX format. This sectionwill not describe the standard Intel HEX format (which is well documented else-where), but details the deviations from the standard for the Merged format.

Page 228: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-24 ©1996 microEngineering Labs

Each word of the executable image is stored in consecutive bytes in the Intelformat (LSB first). To adjust for the 2-byte word size of the PIC, the Intel HEXaddresses are doubled (since the format is strictly byte oriented). With these twoadjustments made, the Merged Intel HEX format is identical to the standard IntelHEX format.

Unlike the binary format, only bytes which are actually generated have any valuespecified in the Merged Intel HEX format. If some fill value is required, this must behandled by your PIC programmer.

Unlike the binary file format, the Merged Intel HEX format also contains infor-mation on the processor type, ID/checksuming flag and the fuses.

10.4.1. PIC16C5x Device Descriptor

:061FFA00 0001 FFFF 03 02 DDIntel ChecksumFusesProcessor NumberIDChecksum FlagIntel Header

The device descriptor for the PIC16C5x family is shown above. The checksumflag (2 bytes) is 0000 if no checksum is to be calculated and 0001 is the checksum isto be calculated. The ID field contains the 16-bit ID (LSB first) as specified by theID pseudo-op. The ID is FFFF if the checksum for the PIC is to be calculated (i.e.Checksum = 0001). The processor numbers for the PIC16C5x family are as follows:

00 PIC16C5401 PIC16C5502 PIC16C5603 PIC16C5704 PIC16C58

For details on the fuses field, see the description of the DEVICE pseudo op.

10.4.2. PIC16Cxx Device Descriptor

:084000007F007F007F007F00BCIntel ChecksumIDIntel Header

:04400E00FF3F000070Intel CheksumProcessor CodeFusesIntel Header

File Formats

00 PIC16C7101 PIC16C8402 PIC16C6403 PIC16C74

Page 229: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-25©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

10.5. Symbol Table File

a_abs 0000000Aa_code CODE 0000000Aa_data DATA 0000000Aa_eeprom EEPROM 0000000Ax_abs 00000000x_code CODE 00000000x_data DATA 00000000x_eeprom EEPROM 00000000

The symbol table contains all labels (except labels starting with the ‘@’ charac-ter) defined in the program. This file contains three unlabeled columns. The firstcolumn contains the actual name of the symbol. The case of the defining instance ispreserved and only the first 32 significant characters are displayed. The second col-umn may contain the label’s type (CODE, DATA or EEPROM). This is determinedby the segment in which the label was defined. No type is generated for the ABSsegment, which is the default. Finally, the last column contains the full 32-bit repre-sentation of the number in hexadecimal. Note that base-16 is understood and no ‘H’suffixes or ‘0x’ prefix has been included. Symbols are listed in alphabetical order.

This format is intended for use by debuggers and is not really made humanreadable. While the items currently begin in fixed column, this may change in thefuture. Those parsing these items should rely on the use of whitespace as separators,rather than column numbers. Additional fields (columns) may be added to the end ofeach line in the future, so those processing this format should ignore items occurringafter the value.

10.6. Listing File

1 ; Test File for PIC Macro Assembler23 include �T13.INC�

* 1 mac macro p* 2 db �p�* 3 endm* 4 mac �uChip�

+ 000- 822 875 843 868 db ��uChip��004- 869 870 822

45 =0010 SIZE equ 10h6 mac �uChip�+ 007- 822 875 843 868 db ��uChip��

00B- 869 870 82278 nmtlist

# 9 00E- 875 843 868 869 db �uChip�10 mac �uChip�

# + 013- 822 875 843 868 db ��uChip��

The listing file gives the programmer the most information about the actual as-sembly of the source file, and is therefore the most complex. This file contains threecolumns of assembly information followed by the source code.

The first column of the listing is a single character which gives additional infor-mation about the line being listed. The following table shows these tag characters.While multiple tags might apply to a single line, only one is listed. Thus, they arelisted below in order of preference :

Page 230: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-26 ©1996 microEngineering Labs

# More than 4 Words Generated, but Suppressed* Line is from Include File

Normal Source Line

The second column displays the line number. If the current line is from an in-cluded file, the number of that line within the include file is listed. If the current lineis generated by a macro expansion, the line number is replaced with a ‘+’.

The last column displays the results of the line. If the line computes a value for alabel or as the parameter for a pseudo-op, then the value is display either as a 4 or 8hexadecimal digit number following an ‘=’. If the line generates code, the currentload pointer is displayed, followed by ‘-’ and one or more lines of up to 4 words perline. For comments and many pseudo-ops, this column is left blank.

11. Assembling Existing Parallax Code

For the most part, PM will assemble existing Parallax code (previously assem-bled w/ PASM, PASM71 or PASMX) with little or no change. The following stepsmay be needed :

* Depending on the type of PIC, place the following line in the source prior toany lines of code :

PIC16C5x MACLIB ‘P5X.INC’PIC16C61 MACLIB ‘P61.INC’PIC16C62 MACLIB ‘P62.INC’PIC16C62x MACLIB ‘P62x.INC’PIC16C63 MACLIB ‘P63.INC’PIC16C64 MACLIB ‘P64.INC’PIC16C65 MACLIB ‘P65.INC’PIC16C70 MACLIB ‘P70.INC’PIC16C71 MACLIB ‘P71.INC’PIC16C72 MACLIB ‘P72.INC’PIC16C73 MACLIB ‘P73.INC’PIC16C74 MACLIB ‘P74.INC’PIC16C84 MACLIB ‘P84.INC’

* If you receive the error [225] Undefined Symbol ‘W’, the source may con-tain the Parallax opcode MOV W,fr-W. This opcode is not supported by PM. Thisopcode can, however, be replaced with the Microchip equivalent SUBWF fr,0.

MOV W,fr-W Becomes SUBWF fr,0

* The SUBB instruction of PASM was specialized for use with the PIC carryflag (C), which is inverted from carry flags in most conventional processors (0 if aborrow occurs). Thus, SUBB modified its destination if the specified bit is 0, whichis nonsense for general bit usage (although it makes sense for 16-bit subtraction). Ifyou used these instructions in your program, you must invert the sense of the bit.

File Formats

Page 231: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-27©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

SUBB fr,bit Becomes SUBB fr,/bitSUBB fr,/bit Becomes SUBB fr,bit

* The original Parallax assembler evaluates equations strictly left to right (i.e.3+4*5 = 35). PM also evaluates equations left to right, but uses operator precedence(i.e. 3+4*5 = 23). This typically creates no problems since PIC programs tend to berelatively simple. You should, however, check for complex calculations to assure thattheir evaluation will be correct.

12. Warnings

100 Attempt to Skip MultiByte OpCode @ Address

Indicates the current instruction is a multibyte Parallax instructions and that theprevious instruction is attempting to skip it. Obviously, if this were done unintention-ally, a successful skip would enter the current opcode mid-instruction.

101 Use of Local Label Prior to Use of Non-Local Label

Indicates that a local label (i.e. starting with a colon) has been defined prior to thedefinition of a non-local label (i.e. a legal label name starting with other than a colon).Because local names depend on the named of last non-local label defined, this usage isobviously suspicious. The label generating the warning is not expanded as are otherlocal labels (see Local Labels).

102 Code Crosses Boundary @ Address

Both the 12-bit and 14-bit PIC cores have paged architectures in which the normalincrementing of the PC doesn’t extended into page select registers (PA0 & PA1 in thePIC16C5x, PCLATH in the PIC16Cxx). If a continuous block of code is generatedacross a page boundary and a forward jump is coded, the actual jump location will beto the previous page.

104 Called Addresses must Reside in Lower Half of Page

In the PIC16C5x family, the 9th bit of address is zeroed on calls. Thus, call desti-nations must reside in the lower 256 words of any 512 word page. This mistake is onlya warning since calls made to the upper 256 words will alias to an address in the lower256 words of the page.

105 Bit Addresses are the Same

This warning indicates that you have attempted to copy a bit to itself. The ParallaxMOVB bit,bit instruction will correctly copy a bit to itself, although the operation hasno useful applications.

106 Register Addresses are the Same

This warning indicates that you have attempted to copy a register to itself. Whilethis is legal, it generates a MOVF and MOVWF instruction, placing the moved value inW and setting the Z flag. If your intentions are to set the Z flag according to contents ofthe specified register, the TEST instruction will do this in one word and without de-stroying the contents of W.

Page 232: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-28 ©1996 microEngineering Labs

13. Errors

Unless specified otherwise, each of the following errors will terminate the as-sembly of the current line. If possible, the assembler will generate correct code (or atleast the correct number of words) before the line is aborted. Assembly continueswith the next line of source.

Unless otherwise specified, the error report has no side effects other than tobump the error count.

200 Instruction Restricted to 14-Bit Core

The opcode of the specified line cannot be used for the PIC16C5x family:ADDLW #literalSUBLW #literalRETFIERETURN

201 ‘Character’ Expected

The assembler expected, but didn’t find, the specified character.

202 Illegal Character ‘Character’

The assembler doesn’t recognize the legal use of the specified character.

203 ‘—’ or ‘++’ Expected

The Parallax instruction MOVSZ (MOVe and Skip in Zero) must take one oftwo forms : MOVSZ W,++fr

MOVSZ W,—fr

204 ‘W’ Expected as First Parameter

The Parallax instruction MOVSZ (MOVe and Skip in Zero) must take one oftwo forms : MOVSZ W,++fr

MOVSZ W,—fr

205 Illegal Use of Keyword ‘Keyword’

Indicates that the specified identifier is a reserved word of the assembler and hasbeen improperly used.

206 CHECKSUM Not Supported in 14-Bit Core

The CHECKSUM option may be used as the ID of a processor in the PIC16C5xfamily. This option is not legal on the 14-bit core.

208 Illegal Use of SUB Instruction

This error indicates an attempt was made to use the illegal instruction :SUB W,fr

Errors

Page 233: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-29©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

209 Indirect Jump Expected in Form of ‘PC+W’

This error indicates an attempt was made to use the illegal instruction :JMP PC+Expr

210 Bit Addresses Must Differ

The Parallax MOVB bit1,/bit2 instruction requires that the source and destina-tion bits be different. An attempt to copy the complement of a bit to itself will resultin the unconditional setting of the bit.

211 Poorly Formed Numeric Constant ‘Token’

Indicates that the symbol is not a legally formed numeric token. If any initialportion of this token is a valid constant, that portion is converted and its value is usedas the result of the token.

212 Extra Tokens on End of Line

Some initial portion of the current line assembled correctly, but additional as-sembly tokens remain unprocessed. This is often the result of a syntax error (extraparameters, misplaced or missing punctuation, etc.). Code is generated for the cor-rect initial portion of the line.

213 IRPC Expected Id or String Constant

The second parameter of the IRPC macro definition is the item (scanned charac-ter by character) which drives the macro expansion. This item must be either anidentifier or a quote-enclosed string constant.

214 IRPC Missing Replacement Parameter

The first parameter of the IRPC macro definition is the variable which acceptsthe characters scanned from the second parameter. The first parameter must be anidentifier unique within the definition of the macro.

215 Attempt to Redefine Macro ‘Identifier’

An attempt was made to redefine the named macro.

216 Attempt to Redefine Macro Parameter ‘Identifier’

Each parameter and local variable of a macro must be unique. This error indi-cates that a parameter or local name has been duplicated.

217 Attempt to Generate Code in Non-Code Segment

Due to the Harvard Architecture (split code and data spaces) of the PICs, in-structions may only be executed from CODE space (ROM). This error indicates thatan attempt was made to generate opcodes in the data or EEPROM segments. Ingeneral, only the DS pseudo-op is legal in the data segment and DS, DB and DW arethe only legal pseudo-ops in the EEPROM segment.

Page 234: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-30 ©1996 microEngineering Labs

218 Address Limit of Address Exceeded

This error indicates that current segment has overflowed.

219 Collision in HEX File @ Address

This error indicates that more than one word has been generated for the specifiedROM address.

220 Illegal Bit Number

In the PIC (and most processors), the bits of a byte are numbered from 0 (theleast significant bit - LSB) to 7 (the most significant bit - MSB). This error indicatesthat the specified bit number is not in the range of 0 to 7.

221 Illegal Bit Address

The four basic bit operators of the PIC take either an 8-bit field (12-bit core) ora 10-bit field (14-bit core). This is composed of a register address and a bit number.If this combination exceeds the 8 or 10 bit range for the selected processor, this erroris generated. Note that only the composite value is checked - this check in no wayguarantees the validity of the bit number or the register address. These value are,however, checked whenever they can be checked as separate parameters.

222 Illegal Destination Specifier

Many Microchip instructions expect the second parameter to specify the destina-tion of the operation result : 0 if the result is also the source register, 1 if the result isto be placed in W. This error indicates that a numeric expression was used for thisparameter which neither evaluated to 0 nor 1. For clarity, the second parameter canbe omitted to use the source register as the destination and W can be used to specifyW as the destination.

223 Illegal TriState File Register Address Register

The TRIS instruction may only operate upon registers 5, 6, or 7. This errorindicates that the specified register value was other than 5, 6, or 7. The equivalentParallax instruction may also generate this error :

MOV !Register,Source

224 Keyword Directive Only for Use in Macros

Some keywords (such as LOCAL and ENDM) only have meaning in the defini-tion of a macro body. This error indicates that an attempt was made to use such akeyword in some other context.

225 Undefined Symbol ‘Identifier’

A reference was made to the specified symbol although no such symbol wasdetected in the first pass of the assembler.

Errors

Page 235: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-31©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

226 Numeric Constant or Symbol Name Expected

A legal expression is a well formed sentence containing operators and terminalsfrom which values for the operators are derived. This error indicates that an expres-sion terminal was encountered which didn’t evaluate to a numeric value.

227 Divide by Zero

An attempt was made (in the source) to divide by zero at assembly time.

228 Modulus by Zero

An attempt was made (in the source) to take the modulus of a number by zero atassembly time.

229 Device Doesn’t Support EEPROM

An attempt was made to generate values in the EEPROM segment for a devicewhich doesn’t support EEPROM.

230 Collision in EEPROM @ Address

An attempt was made to generate more that one value for the specified EEPROMlocation.

231 Attempt to Redefine ‘Identifier’

An attempt was made to assign a new value to a symbol defined either as aprogram label or using the EQU pseudo-op. A common (but confusing) source ofthis error can result from different flows through conditional assembly blocks be-tween the first and second passes. While this type of variant programming can bedone, it is very tricky and poor programming practice - it should be avoided.

232 File Name Expected

Indicates that the parameter specified for the current INCLUDE or MACLIBpseudo-op is not a quoted string.

233 String Expression Expected for Title

The TITLE pseudo-op is used to replace the normal copyright notice of thelisting with a customized header. This new header must be specified as a quotedstring and is the only parameter of the TITLE pseudo-op.

234 Identifier Expected

The IFDEF and IFNDEF conditional assembly pseudo-ops require one identifieras it parameter. This error is generated whenever this parameter is other than a legalidentifier.

235 Opcode Expected Instead of ‘Token’

Any text starting in column 2 or later which is not a commented is assumed toeither be an opcode, a pseudo-op or the name of a defined macro. All other tokenswill generate this error.

Page 236: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-32 ©1996 microEngineering Labs

236 Label ‘Identifier’ Undefined in Pass 0

This error indicates that an attempt was made to define the specified symbol inpass 1, although no definition was made for the symbol during pass 0. This is almostalways the result of different flows through conditional assembly blocks betweenpass 0 and pass 1.

237 IRP Missing Replacement Parameter

The IRP macro takes two parameters. The first parameter is an identifier whichis substituted on each expansion with the next item from the comma separated list(the second parameter). This error indicates that the identifier expected for the firstparameter of the IRP statement was not found.

14. Fatal Errors

300 Too Many Errors

The assembler can generated an unlimited number of warnings, but the numberof errors is limited. While this value defaults to 15, it can be changed using the -Goption. This fatal error is generated when this allowance is exceeded.

301 Out of Memory

Indicates that the symbol table, macro table and other memory requirements forinternal bookkeeping have exceeded the memory capacity of your PC. While thiserror message is unlikely, it can occur on limited or heavily burdened systems. If notalready at the 640K limit for conventional memory, add memory. Unloading or load-ing high of TSRs and network drivers can increase usable memory. Memory mayalso be gained by reducing the number of BUFFERS and FILES allocated inCONFIG.SYS.

302 Unable to Open File ‘Filename’

Indicates that DOS was unable to open the specified file. This is either becausethe file could not be found or not enough file handles were available (this usually onlyoccurs with deep nesting of INCLUDE and MACLIB statements). If the file exists,make sure it resides in the current directory. If the file is an INCLUDE or MACLIBfile, also check in the default include directory. While this defaults to the INCsubdirectory of the directory where PM.EXE is kept, it can be modified using the -Ioption. If the file is found as described above, try increasing the number of FILES inCONFIG.SYS.

303 Unable to Create File ‘Filename’

Indicates that DOS was unable to create the specified file. This is either becausethere are not enough file handles available or there is not enough space on the desti-nation disk. If there is adequate disk space available, try increasing the number ofFILES in CONFIG.SYS.

Errors

Page 237: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-33©1996 microEngineering Labs

Appendix CPIC Macro Assembler

Reference

304 No Source File Specified

This error is generated if PM is invoked with options, but without the name of asource file. If PM is invoked with no options and no source name, a brief help screenis displayed.

305 Unable to Write to File ‘Filename’

Indicates that DOS was unable to write to the specified file. This usually resultswhen there is not enough space on the destination disk or the specified file has somespecial write protection (such as DOS SHARE.EXE).

306 Page Width must be 80 to 255 Columns

The PAGE pseudo-op is used to specify the size of the listing page. The firstparameter is used to specify the width of the page. This value must be between 80and 255, inclusive.

307 Illegal Device Type

An attempt was made to use an illegal specifier with the DEVICE statement.Such values would have 10 or 11 as the two most significant bits.

308 Macro Buffer Overflow

An attempt was made to define a macro which was larger than 4K. This usuallyindicates a missing ENDM pseudo-op.

15. Internal Errors

These errors are not documented, because they should not occur. If they occur,technical support should be contacted and a copy of the code producing the errorshould be made available.

400 Attempt to Free Non-Allocated Memory [Pointer]

401 Attempt to Reference Non-Allocated Memory [Pointer]

402 Attempt to Pop Empty Symbol Table Stack

403 Attempt to Exit on Empty File Stack

404 Attempt to Pop Empty Macro Stack

405 Macro Stack Error

406 Attempt to Pop Empty Conditional Assembly Stack

407 No Function Handler for ‘Keyword’

Page 238: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

C-34 ©1996 microEngineering Labs

Notes

Page 239: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-1©1998 Sirius microSystems

Appendix DParallax Instruction

Set Reference

D Parallax Instruction SetReference

Larry found that he learned a lot of instructions during his walk home ... as long asit didn’t rain.

Page 240: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-2 ©1998 Sirius microSystems

Page 241: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-3Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Table of ContentsMicrochip Instructions ............................................... D-7

Parallax Instructions .................................................. D-7Introduction ........................................................................................... D-7

Summary of Parallax Instructions ............................. D-8Byte-oriented Operations...................................................................... D-8Bit-oriented operations ......................................................................... D-9Inc/dec-conditional branches ................................................................ D-9Compare-conditional branches............................................................. D-9Bit-conditional branches ....................................................................... D-9Unconditional branches ...................................................................... D-10I/O and control operations .................................................................. D-10

ADD............................................................................ D-11ADD destination, source ......................................................................D-11

ADDB ......................................................................... D-11ADDB destination, bit ..........................................................................D-11

AND............................................................................ D-12AND destination, source ..................................................................... D-12

Call ............................................................................. D-13Call addr .............................................................................................. D-13

Compare and Jump .................................................. D-13Compare and jump if above .......................................................................D-13Compare and jump if above or equal ................................................. D-13Compare and jump if Below ............................................................... D-14Compare and Jump if below or equal ................................................ D-14Compare and jump if equal ................................................................ D-15Compare and jump if not equal .......................................................... D-15

Clear Carry ................................................................ D-16

Clear .......................................................................... D-16CLR register/flag ................................................................................. D-16Clear bit ............................................................................................... D-16

Compare and Skip .................................................... D-17Compare and skip if above ................................................................. D-17Compare and skip if above or equal .................................................. D-17

Page 242: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-4 ©1998 Sirius microSystems

Compare and skip if below ................................................................. D-18Compare and skip if below or equal ................................................... D-18Compare and skip if equal .................................................................. D-18Compare and skip if not equal ............................................................ D-19

Decrement ................................................................. D-19Dec file register ................................................................................... D-19Dec file register and skip if zero ......................................................... D-19Dec file register and jump if not zero .................................................. D-20

Increment .................................................................. D-20Increment file register and jump if not zero ....................................... D-20Increment file register ......................................................................... D-20 Increment file register and skip if zero.............................................. D-20

Jump .......................................................................... D-20Jump if carry ....................................................................................... D-20Jump to addr ....................................................................................... D-21Jump PC + W ..................................................................................... D-21Jump W............................................................................................... D-21Jump if not bit ..................................................................................... D-21Jump if not carry ................................................................................. D-21Jump if not zero .................................................................................. D-21Jump if zero ........................................................................................ D-22

Long Instructions ..................................................... D-22Long Call ............................................................................................. D-22Long Jump .......................................................................................... D-22Long Set ............................................................................................. D-22

Move .......................................................................... D-22MOV destination, Source .................................................................... D-22

Bit Move .................................................................... D-25MOVB Destination bit, Source bit ....................................................... D-25

Move and Skip .......................................................... D-26Move and skip if zero .......................................................................... D-26

Negate ....................................................................... D-26

No Operation ............................................................. D-26

Not ............................................................................. D-26Not fr/W............................................................................................... D-26

OR .............................................................................. D-27Or Destination, Source ....................................................................... D-27

Table of Contents

Page 243: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-5Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Return ........................................................................ D-28Return from subroutine ....................................................................... D-28Return from interrupt........................................................................... D-28Return with value in W........................................................................ D-28

Rotate ........................................................................ D-28

Skip ............................................................................ D-29

Set .............................................................................. D-30Set bit .................................................................................................. D-30Set Carry ............................................................................................. D-30Set Zero .............................................................................................. D-30

Sleep .......................................................................... D-30

Subtract ..................................................................... D-30Sub minuend,subtrahend ................................................................... D-30

Subtract Bit ............................................................... D-31

Swap Nibbles ............................................................ D-31

Test ............................................................................ D-31

XOR ........................................................................... D-32XOR Destination,Source .................................................................... D-32

Page 244: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-6 ©1998 Sirius microSystems

Notes

Page 245: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-7Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Microchip Instructions

Microchip instructions are described in detail in the PIC16C8X data sheets be-ginning on pages 53.

Parallax Instructions

Introduction

Early adopters of the PIC microcontroller were less than pleased with the PIC’sinstruction set. While appropriate for a RISC architecture, it is somewhat crypticand makes code unreadable. Parallax realized this when they decided to build PICdevelopment tools. To overcome the problem, Parallax decided to build an 8051-likeinstruction set.

The Parallax intruction set has some advantages. Most notably, the instructionsare more intuitive and generally allow programmers to write more readable code. Italso has some disadvantages. First, each Parallax instruction expands to between 1and 4 PIC instructions. This variable instruction length makes “cyclecounting”difficult. Second, it is not always obvious from the Parallax instructionwhat it actually happening. Consider the intruction mov fr,#lit. While the in-struction does the obvious (setting the file register to the literal value), it also has theless obvious side effect (setting the W register to the literal value). Such hidden sideeffects can make debugging difficult.

Recognizing that each instruction set has advantages and disadvantages, PMsupports both. While the PIC instruction set is widely documented, the Parallaxinstruction set is not. That is the purpose of this supplement.

—From microEngineering Labs “PIC Macro Assembler Instruction Set Supplement© 1996 microEngineering Labs

The following example demostrates the syntax difference between Parallax in-structions and Microchip instructions. Parallax instructions follow the Intel conven-tion of listing the operands in sequentially reverse order:

Instruction Destination,Source

whereas Microchip instructions take the form:

OpCode Operand,n

Microchip instructions encode the Source in the Operand and specify the desti-nation as a bit (n) that can represent either the Operand if n=1 (the default), or theWorking Register (W) if n=0.

We recommend that you examine both instruction sets. Work with the one youfind the most comfortable to use, or the most intuitive.

All PIC-MDS example programs are provided in Micochip and Parallax codeformats. Parallax code chapters have been printed on blue paper to distinguish themfrom the Microchip code chapters.

Page 246: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-8 ©1998 Sirius microSystems

Summary of Parallax Instructions

Byte-oriented Operations

Words Flags W usedmov w,#literal* 1 - - Move literal into wmov w,fr 1 Z - Move fr into wmov fr,w 1 - - Move w into frmov fr,#literal 2 - W Move literal into frmov fr1,fr2 2 Z W Move fr2 into fr1mov w,#literal-w 1 C,DC,Z - Move literal-w into wmov w,fr-w� 1 C,DC,Z - Move fr-w into w

add w,#literal* 1 C,DC,Z - Add literal into wadd w,fr 1 C,DC,Z - Add fr into wadd fr,w 1 C,DC,Z - Add w into fradd fr,#literal 2 C,DC,Z W Add literal into fradd fr1,fr2 2 C,DC,Z W Add fr2 into fr1

sub fr,w 1 C,DC,Z - Subtract w from frsub fr,#literal 2 C,DC,Z W Subtract literal from frsub fr1,fr2 2 C,DC,Z W Subtract fr2 from fr1

and w,#literal 1 Z - AND literal into wand w,fr 1 Z - AND fr into wand fr,w 1 Z - AND w into frand fr,#literal 2 Z W AND literal into frand fr1,fr2 2 Z W AND fr2 into fr1

or w,#literal 1 Z - OR literal into wor w,fr 1 Z - OR fr into wor fr,w 1 Z - OR w into fror fr,#literal 2 Z W OR literal into fror fr1,fr2 2 Z W OR fr2 into fr1

xor w,#literal 1 Z - XOR literal into wxor w,fr 1 Z - XOR fr into wxor fr,w 1 Z - XOR w into frxor fr,#literal 2 Z W XOR literal into frxor fr1,fr2 2 Z W XOR fr2 into fr1

clr w 1 Z - Clear wclr fr 1 Z - Clear fr

mov w,++fr 1 Z - Move fr+1 into winc fr 1 Z - Increment fr

mov w,�fr 1 Z - Move fr-1 into w

dec fr 1 Z - Decrement fr

mov w,>>fr 1 C - Move right-rotated fr into wrr fr 1 C - Rotate right fr

mov w,<<fr 1 C - Move left-rotated fr into wrl fr 1 C - Rotate left fr

mov w,<>fr 1 - - Move nibble-swapped fr into wswap fr 1 - - Swap nibbles in fr

not w 1 Z - Perform 1�s-complement on wmov w,/fr 1 Z - Move 1�s-complemented fr into wnot fr 1 Z - Perform 1�s-complement on fr

test w 1 Z - Test w for zerotest fr 1 Z - Test fr for zero

Summary of ParallaxInstructions

Page 247: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-9Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Bit-oriented operations

Words Flags W usedaddb fr,bit 2 Z - Add bit into frsubb fr,bit� 2 Z - Subtract bit from fr

clrb bit 1 - - Clear bitclc - - Clear carryclz 1 - - Clear zero

setb bit 1 - - Set bitstc 1 - - Set carrystz 1 - - Set zero

movb bit1,bit2 4 - - Move bit2 into bit1movb bit1,/bit2 4 - - Move not bit2 into bit1

Inc/dec-conditional branches

movsz w,++fr 1 - - Move fr+1 into w and skip if zeroincsz fr 1 - - Increment fr and skip if zeroijnz fr,addr 2 - - Increment fr and jump if not zero

movsz w,�fr 1 - - Move fr-1 into w and skip if zerodecsz fr 1 - - Decrement fr and skip if zerodjnz fr,addr 2 - - Decrement fr and jump if not zero

Compare-conditional branches

csa fr,#literal 3 C,DC,Z W Compare and skip if abovecsa fr1,fr2 3 C,DC,Z W Compare and skip if abovecsae fr,#literal 3 C,DC,Z W Compare and skip if above or equalcsae fr1,fr2 3 C,DC,Z W Compare and skip if above or equalcsb fr,#literal 3 C,DC,Z W Compare and skip if belowcsb fr1,fr2 3 C,DC,Z W Compare and skip if belowcsbe fr,#literal 3 C,DC,Z W Compare and skip if below or equalcsbe fr1,fr2 3 C,DC,Z W Compare and skip if below or equalcse fr,#literal 3 C,DC,Z W Compare and skip if equalcse fr1,fr2 3 C,DC,Z W Compare and skip if equalcsne fr,#literal 3 C,DC,Z W Compare and skip if not equalcsne fr1,fr2 3 C,DC,Z W Compare and skip if not equal

cja fr,#lit,addr 4 C,DC,Z W Compare and jump if abovecja fr1,fr2,addr 4 C,DC,Z W Compare and jump if abovecjae fr,#lit,addr 4 C,DC,Z W Compare and jump if above or equalcjae fr1,fr2,addr 4 C,DC,Z W Compare and jump if above or equalcjb fr,#lit,addr 4 C,DC,Z W Compare and jump if belowcjb fr1,fr2,addr 4 C,DC,Z W Compare and jump if belowcjbe fr,#lit,addr 4 C,DC,Z W Compare and jump if below or equalcjbe fr1,fr2,addr 4 C,DC,Z W Compare and jump if below or equalcje fr,#lit,addr 4 C,DC,Z W Compare and jump if equalcje fr1,fr2,addr 4 C,DC,Z W Compare and jump if equalcjne fr,#lit,addr 4 C,DC,Z W Compare and jump if not equalcjne fr1,fr2,addr 4 C,DC,Z W Compare and jump if not equal

Bit-conditional branches

sb bit 1 - - Skip if bitsc 1 - - Skip if carrysz 1 - - Skip if zero

snb bit 1 - - Skip if not bitsnc 1 - - Skip if not carrysnz 1 - - Skip if not zero

Words Flags W used

Page 248: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-10 ©1998 Sirius microSystems

jb bit,addr 2 - - Jump to address if bitjc addr 2 - - Jump to address if carryjz addr 2 - - Jump to address if zero

jnb bit_addr,addr 2 - - Jump to address if not bitjnc addr 2 - - Jump to address if not carryjnz addr 2 - - Jump to address if not zero

Unconditional branches

skip 1 - - Skip following instruction word(Skip should be followed by a single word instruction)

jmp addr 1 - - Jump to addressjmp pc+w 1 C,DC,Z - Add w into pcljmp w 1 - - Move w into pcl

call add 1 - - Call to addressret 1 - - Return from callretw lit,lit... 1 - - Return from call with literal in w

reti 1 - - Return from interrupt

I/O and control operations

mov !port,w* 1 - - Move w into port�s trismov !port,#lit* 2 - W Move literal into port�s trismov !port,fr* 2 Z W Move fr into port_fr�s tris

mov !option,w* 1 - - Move w into optionmov !option,#lit* 2 - W Move literal into optionmov !option,fr* 2 Z W Move fr into option

clr wdt 1 TO,PD - Clear wdt and prescalersleep 1 TO,PD - Clear wdt and enter sleep mode

nop 1 - - No operation

* Applies to PIC16C71 and PIC16C84 only� PM implementation differs from Parallax� Not implemented by PM

Source & Destination Descriptions:fr & frn represent one of the PIC File Registers (see Chaper 3)w represents the Working Register#literal is an 8-bit numeric constantbit corresponds to a bit in a file register and can also be represented as fr,n where n (from 0-7) represents the nth bit of file register fraddr can be a memory address or address label

Summary of ParallaxInstructions

Page 249: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-11Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

ADD

ADD destination, source

Destination = Destination + Source. Destination may be W or a file register.Source may be W, a file register or a literal (all literals must have a # sign as theirfirst char).

ADD fr,#literal

Add literal into fr. Translates to:

movlw literal ;W=literaladdwf fr1 ;fr=fr+W

Note: Although not explicitly referenced, ADD fr,#literal modifies W.

ADD fr1,fr2

Add fr2 into fr1. Translates to:

movf fr2,0 ;W=fr2addwf fr1 ;fr1=fr1+W

Note: Although not explicitly referenced, ADD fr1,fr2 modifies W.

ADD fr,W

Add W into fr. Translates to:

addwf fr ;W=W+fr

ADD W,#literal

Add literal into W. Translates to:

addlw literal ;W=W+literal

ADD W,fr

Add fr into W. Translates to:

addwf fr,0 ;W=W+fr

ADDB

ADDB destination, bit

If bit = 1, destination = destination + 1. If bit = 0, destination = destination + 0.Destination must be a file register.

ADDB fr,bit

Translates to:

btfsc bit ;if bit=0,PC=PC+2incf fr ;fr=fr+1

Reg./Flags affected: W,C,DC,ZWords: 2Cycles: 2

Reg./Flags affected:C,DC,ZWords: 1Cycles: 1

Reg./Flags affected: W,C,DC,ZWords: 1Cycles: 1

Reg./Flags affected: W,C,DC,ZWords: 1Cycles: 1

Reg./Flags affected: ZWords: 2Cycles: 2

Reg./Flags affected: W,C,DC,ZWords: 2Cycles: 2

Page 250: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-12 ©1998 Sirius microSystems

AND

AND destination, source

Destination=logical and with source. Destination may be fr or W. Source may fr,W or literal (precede literal with a # sign).

AND fr,#literal

AND literal into file register.Translates to:

movlw literal ;W=literalandwf fr ;fr=fr&W

Usefull for masking out or including desired bits. For example, to isolate thebottom three bits in a file register AND the file register with #07h. Eg.

fr = 55h 01010101and fr, #07h and 00000111results in fr = 5h 00000101

Note: Although not explicitly referenced, and fr,#literal modifies W.

AND fr1,fr2

And fr2 into fr1. Translates to:

movf fr2,0 ;W = fr2andwf fr1 ;fr1 = W and fr2

Note: Although not explicitly referenced, and fr,fr2 modifies W.

AND fr,W

And W into fr. Translates to:

andwf fr ;fr=fr&W

AND W,#literal

And literal into W. Translates to:

andlw literal ;W=W&literal

AND W,fr

And fr into W. Translates to:

andwf fr,0 ;W=W&fr

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Page 251: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-13Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Call

Call addr

Calls the subroutine located at address location specified by label addr. Execu-tion will continue at subroutine location until a return instruction executes. Afterreturn execution continues at the intstruction after the CALL.

CALL addr

Call Subroutine. Translates to:

call addr ;push PC:PC=addr

Compare and Jump

Compare and jump if above

CJA fr,#literal,addr

Compare fr to literal and jump if above.Translates to:

movf fr1,0 ;W=fr1subwf, fr2,0 ;W=fr2-Wbtfsc C ;if fr<=literal, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJA fr,#literal,addr modifies W.

CJA fr1,fr2,addr

Compare fr1 to fr2 and jump if aboveto addr. Translates to:

movf fr1,0 ;W=fr1subwf, fr2,0 ;W=fr2-Wbtfss C ;if fr1<=fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJA fr1,fr2,addr modifies W.

Compare and jump if above or equal

CJAE fr,#literal,addr

Compare fr to literal and jumps if aboveor equal to addr. Translates to:

movlw literal ;W=literalsubwf, fr,0 ;W=fr-Wbtfsc C ;if fr<literal, PC=PC+2goto addr ;pc=addr

Reg./Flags affected:noneWords: 1Cycles: 2

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Page 252: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-14 ©1998 Sirius microSystems

CJAE fr1,fr2,addr

Compare fr1 to fr2 and jumps if aboveor equal to addr. Translates to:

movf fr2,0 ;W=fr2subwf, fr1,0 ;W=fr1-Wbtfsc C ;if fr1<fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJAE fr1,fr2,addr modifies W.

Compare and jump if Below

CJB fr1,#literal,addr

Compare fr1 to literal and jump if belowto addr. Translates to:

movlw literal ;W=literalsubwf, fr,0 ;W=fr-Wbtfss C ;if fr>=literal, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJB fr1,#literal,addr modifies W.

CJB fr1,fr2,addr

Compare fr1 to fr2 and jump if belowto addr. Translates to:

movf fr2,0 ;W=literalsubwf, fr1,0 ;W=fr1-Wbtfss C ;if fr>=fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJB fr1,fr2,addr modifies W.

Compare and Jump if below or equal

CJBE fr,#literal,addr

Compare fr1 to literal and jump if belowor equal to addr. Translates to:

movlw ~literal;W=~literaladdwf fr,0 ;W=fr+Wbtfss C ;if fr> literal, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJBE fr,#literal,addr modifies W.

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Page 253: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-15Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

CJBE fr1,fr2,addr

Compare fr1 to fr2 and jump if belowor equal to addr. Translates to:

movf fr1,0 ;W=fr1subwf, fr2,0 ;W=fr2-Wbtfsc C ;if fr>=fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJBE fr1,fr2,addr modifies W.

Compare and jump if equal

CJE fr,#literal,addr

Compare fr to literal and jump if equalto addr. Translates to:

movlw literal ;W=literalsubwf, fr,0 ;W=fr-Wbtfsc Z ;if fr<>literal, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJE fr1,#literal,addr modifies W.

CJE fr1,fr2,addr

Compare fr1 to fr2 and jump if equalto addr. Translates to:

movf fr2,0 ;W=literalsubwf, fr1,0 ;W=fr1-Wbtfsc Z ;if fr<>fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJE fr1,fr2,addr modifies W.

Compare and jump if not equal

CJNE fr,#literal

Compare fr to literal and jump if not equalto addr. Translates to:

movlw literal ;W=literalsubwf, fr,0 ;W=fr-Wbtfss Z ;if fr=literal, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJNE fr,#literal,addr modifies W.

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Page 254: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-16 ©1998 Sirius microSystems

CJNE fr1,fr2,addr

Compare fr1 to fr2 and jump if equalto addr. Translates to:

movf fr2,0 ;W=literalsubwf, fr1,0 ;W=fr1-Wbtfsc Z ;if fr1=fr2, PC=PC+2goto addr ;pc=addr

Note: Although not explicitly referenced, CJNE fr1,fr2,addr modifies W.

Clear Carry

CLC

Clears the carry flag. Translates to:

bcf C ;C=0

Clear

CLR register/flag

Register/flag = 0. Clears the specified register or flag.

CLR fr

Clears fr. Translates to:

clrf fr ;fr=0

CLR W

Clears the working register.Translates to:

clrw ;W=0

CLR WDT

Clears the watchdog timerTranslates to:

clrwdt ;reset WDT

Clear bit

CLRB bit

Clears the specified bit.Translates to:

bcf bit ;bit=0

Reg./Flags affected: CWords: 1Cycles: 1

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected:T0,PDWords: 1Cycles: 1

Reg./Flags affected:noneWords: 1Cycles: 1

Reg./Flags affected: W,C,DC,ZWords: 4Cycles: 4(5 if jump)

Page 255: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-17Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

CLZ

Clears the zero flag.Translates to:

bcf Z

Compare and Skip

Compare and skip if above

CSA fr,#literal

Compare fr to literal and skip nextinstruction if above.Translates to:

movlw ~lit ;W=~literaladdwf fr,W ;W=W+frbtfss C ;If fr>literal, PC=PC+2

Note: Although not explicitly referenced, CSA fr,#literal,addr modifies W.

CSA fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if above.Translates to:

movf fr,0 ;W=~fr1subwf fr2,0 ;W=fr2-Wbtfsc C ;If fr1>fr2, PC=PC+2

Note: Although not explicitly referenced, CSA fr1,fr2,addr modifies W.

Compare and skip if above or equal

CSAE fr,#literal

Compare fr to literal and skip nextinstruction if above or equal .Translates to:

movlw lit ;W=literalsubwf fr,0 ;W=W-frbtfss C ;If fr>=literal, PC=PC+2

Note: Although not explicitly referenced, CSAE fr,#literal,addr modifies W.

CSAE fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if above or equal.Translates to:

movf fr1,0 ;W=fr2subwf fr1,0 ;W=fr1-Wbtfsc C ;If fr1>=fr2, PC=PC+2

Note: Although not explicitly referenced, CSAE fr1,fr2,addr modifies W.

Reg./Flags affected:noneWords: 1Cycles: 1

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Page 256: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-18 ©1998 Sirius microSystems

Compare and skip if below

CSB fr,#literal

Compare fr to literal and skip nextinstruction if below. Translates to:

movlw lit ;W=literalsubwf fr,0 ;W=fr-Wbtfsc C ;If fr<literal, PC=PC+2

Note: Although not explicitly referenced, CSB fr,#literal,addr modifies W.

CSB fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if below. Translates to:

movf fr2,0 ;W=~fr2subwf fr1,0 ;W=fr1-Wbtfsc C ;If fr1<fr2, PC=PC+2

Note: Although not explicitly referenced, CSB fr1,fr2,addr modifies W.

Compare and skip if below or equal

CSBE fr,#literal

Compare fr to literal and skip nextinstruction if below or equal. Translates to:

movlw ~lit ;W=~literaladdwf fr,0 ;W=W+frbtfsc C ;If fr<=literal, PC=PC+2

Note: Although not explicitly referenced, CSBE fr,#literal,addr modifies W.

CSBE fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if below or equal. Translates to:

movf fr1,0 ;W=~fr1subwf fr2,0 ;W=fr2-Wbtfss C ;If fr1<=fr2, PC=PC+2

Note: Although not explicitly referenced, CSBE fr1,fr2,addr modifies W.

Compare and skip if equal

CSE fr,#literal

Compare fr to literal and skip nextinstruction if equal. Translates to:

movlw lit ;W=literalsubwf fr,0 ;W=W-frbtfss C ;If fr=literal, PC=PC+2

Note: Although not explicitly referenced, CSBE fr,#literal,addr modifies W.

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Page 257: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-19Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

CSE fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if equal. Translates to:

movf fr2,0 ;W=fr2subwf fr1,0 ;W=fr1-Wbtfss C ;If fr1=fr2, PC=PC+2

Note: Although not explicitly referenced, CSE fr1,fr2,addr modifies W.

Compare and skip if not equal

CSNE fr,#literal

Compare fr to literal and skip nextinstruction if equal. Translates to:

movlw lit ;W=literalsubwf fr,0 ;W=fr-Wbtfsc C ;If fr<>literal, PC=PC+2

Note: Although not explicitly referenced, CSBE fr,#literal,addr modifies W.

CSNE fr1,fr2

Compare fr1 to fr2 and skip nextinstruction if equal. Translates to:

movf fr2,0 ;W=fr2subwf fr1,0 ;W=fr1-Wbtfss C ;If fr1<>fr2, PC=PC+2

Note: Although not explicitly referenced, CSNE fr1,fr2,addr modifies W.

Decrement

Dec file register

DEC fr

Fr=fr-1. Decrements the specifiedfile register. Translates to:

decf fr ;fr=fr-1

Dec file register and skip if zero

DECSZ fr

Decrement the specified file register andskip next instruction if zero results.Translates to:

decfsz fr ;fr=fr-1:if 0,PC=PC+2

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: W,C,DC,ZWords: 3Cycles: 3 (4 if skip)

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected:noneWords: 1Cycles: 1 (2 if skip)

Page 258: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-20 ©1998 Sirius microSystems

Dec file register and jump if not zero

DJNZ fr,addr

Decrement the specified file register andjump to addr if result is not zero.Translates to:

decfsz fr ;fr=fr-1:If 0,PC=PC+2goto addr ;PC=addr

Increment

Increment file register and jump if not zero

IJNZ fr,addr

fr=fr+1. Increments the specifiedfile register and jump to addr if resultis not zero. Translates to:

incfsz fr ;fr==fr+1: If 0,PC=PC+2goto addr ;PC=addr

Increment file register

INC fr

Increment the specified file register.Translates to:

incf fr ;fr=fr+1

Increment file register and skip if zero

INCSZ fr

fr=fr+1. Increments the specifiedfile register and skips next instruction ifresult is zero. Translates to:

incfsz fr ;fr=fr+1: If 0,PC=PC+2

Jump

Jump if carry

JC addr

Jump if carry bit set to addr.Translates to:

btfsc C ;IF C=0,PC=PC+2goto addr ;PC=addr

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected:noneWords: 1Cycles: 1 (2 if skip)

Reg./Flags affected:noneWords: 1Cycles: 1 (2 if skip)

Page 259: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-21Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Jump to addr

JMP addr

Jump to address.Translates to:

goto addr ;PC=addr

Jump PC + W

JMP PC+W

Skips W+1 instructions.Translates to:

addwf PCL ;PC=PC+W+1

Jump W

JMP W

Jump to W.Translates to:

movwf PCL ;PC=(PCLATH<<8)+W

Jump if not bit

JNB bit,addr

Jump if bit equals 0 to addr.Translates to:

btfss bit ;If bit=1,PC=PC+2goto addr ;PC=addr

Jump if not carry

JNC addr

Jump if carry equals 0 to addr.Translates to:

btfss C ;If C=1,PC=PC+2goto addr ;PC=addr

Jump if not zero

JNZ addr

Jump if Z flag equals 0 to addr.Translates to:

btfss Z ;If Z=1, PC=PC+1goto addr ;PC=addr

Reg./Flags affected:noneWords: 1Cycles: 2

Reg./Flags affected:C,DC,ZWords: 1Cycles: 2

Reg./Flags affected:noneWords: 1Cycles: 2

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Page 260: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-22 ©1998 Sirius microSystems

Jump if zero

JZ addr

Jump if Z flag equals 1 to addr.Translates to:

btfsc Z ;If Z=0.PC=PC+2goto addr ;PC=addr

Long Instructions

Long Call

LCALL addr

Perfroms a long call.

[bcf/bsf PCLTH.4] ;set if 8k code[bcf/bsf PCLTH.3] ;set if 4k or 8k codecall addr

Long Jump

LJMP addr

Performs a long jump.

[bcf/bsf PCLTH.4] ;set if 8k code[bcf/bsf PCLTH.3] ;set if 4k or 8k codegoto addr ;Push PC: PC=addr

Long Set

LSET addr

Perfroms a long set.

[bcf/bsf PCLTH.4] ;set if 8k code[bcf/bsf PCLTH.3] ;set if 4k or 8k code

Move

MOV destination, Source

Moves the source into the destination. Source may be a file register or register.Destination is a file register.

MOV fr,#literal

Move literal into file register.Translates to:

movlw literal ;W=literalmovwf fr ;fr=W

Note: Although not explicitly referenced, MOV fr,#literal modifies W.

Reg./Flags affected:noneWords: 2Cycles: 2(3 if jump)

Reg./Flags affected:noneWords: 1-3Cycles: 2-4

Reg./Flags affected:noneWords: 1-3Cycles: 2-4

Reg./Flags affected:noneWords: 1-3Cycles: 2-4

Reg./Flags affected: WWords: 2Cycles: 2

Page 261: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-23Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

MOV fr1,fr2

Move fr2 into fr1.Translates to:

movf fr2,0 ;W=fr2movwf fr1 ;fr1=W

Note: Although not explicitly referenced, MOV fr1,fr2 modifies W.

MOV fr,W

Move W into fr.Translates to:

movwf fr ;fr=W

MOV OPTION,#literal

Move literal into OPTION register.Translates to:

movlw literal ;W=literaloption ;OPTION=W

Note: Although not explicitly referenced, MOV OPTION,#literal modifies W.Microchip recommends that the OPTION instruction not be used if upwards compatabiltywith future PIC16CXX products is desired.

MOV OPTION,fr

Move fr into OPTION register.Translates to:

movf fr,0 ;W=froption ;OPTION=W

Note: Although not explicitly referenced, MOV OPTION,fr modifies W. Microchiprecommends that the OPTION instruction not be used if upwards compatabilty withfuture PIC16CXX products is desired.

MOV OPTION,W

Move W into OPTION register.Translates to:

option

Note: Microchip recommends that the OPTION instruction not be used if upwardscompatabilty with future PIC16CXX products is desired.

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected:noneWords: 1Cycles: 1

Reg./Flags affected: WWords: 2Cycles: 2

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected:noneWords: 1Cycles: 1

Page 262: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-24 ©1998 Sirius microSystems

MOV !fr,#literal

Move literal into fr’s TRIS register.Translates to:

movlw literal ;W=literaltris fr ;TRIS(fr)=W

Note: Although not explicitly referenced, MOV !fr,#literal modifies W. Micro-chip recommends that the TRIS instruction not be used if upwards compatabilty withfuture PIC16CXX products is desired.

MOV !fr1,fr2

Move fr2 into fr’s TRIS register.Translates to:

movf fr2,0 ;W=fr2tris fr1 ;TRIS(fr1)=W

Note: Although not explicitly referenced, MOV !fr1,fr2 modifies W. Microchiprecommends that the TRIS instruction not be used if upwards compatabilty with futurePIC16CXX products is desired.

MOV !fr,W

Move W into fr’s TRIS register.Translates to:

tris fr ;TRIS(fr)=W

Note: Microchip recommends that the TRIS instruction not be used if upwardscompatabilty with future PIC16CXX products is desired.

MOV W,#literal

Move literal into W register.Translates to:

movlw literal ;W=literal

MOV W,fr

Move fr into W register.Translates to:

movf fr,0 ;W=fr

MOV W,/fr

Move complement of fr into W register.Translates to:

comf fr,0 ;W=~fr

Reg./Flags affected: WWords: 2Cycles: 2

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: WWords: 1Cycles: 1

Reg./Flags affected: WWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Page 263: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-25Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

MOV W,fr-W

Move fr-W into W register.Translates to:

subwf fr,0 ;W=fr-W

Note: Not supported by PM.

MOV W,++fr

Move fr+1 into W register.Translates to:

incf fr,0 ;W=fr+1

MOV W,--fr

Move fr-1 into W register.Translates to:

decf fr,0 ;W=fr-1

MOV W,<<fr

Move value of fr rotated left throughcarry into W register. Translates to:

rlf fr,0 ;C=fr.7:W=(fr<<1)|C

MOV W,>>fr

Move value of fr rotated right throughcarry into W register. Translates to:

rrf fr,0 ;C=fr.7:W=(fr>>1)|C

MOV W,<>fr

Move swapped nibbles of fr into W.Translates to:

swapf fr,0 ;W=fr[3..0]|fr[7..4]

Bit Move

MOVB Destination bit, Source bit

MOVB Bit1,Bit2

Move bit2 into bit1. Translates to:

btfss bit2 ;if bit2=1, pc=pc+2bcf bit1 ;bit1=0btfsc bit2 ;if bit2=0, pc=pc+2bsf bit1 ;bit1=1

Reg./Flags affected: W,C,DC,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,CWords: 1Cycles: 1

Reg./Flags affected: W,CWords: 1Cycles: 1

Reg./Flags affected: WWords: 1Cycles: 1

Reg./Flags affected:noneWords: 4Cycles: 4

Page 264: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-26 ©1998 Sirius microSystems

MOVB Bit1,/Bit2

Move complement of bit2 into bit1.Translates to:

btfsc bit2 ;if bit2=0, pc=pc+2bcf bit1 ;bit1=0btfss bit2 ;if bit2=1, pc=pc+2bsf bit1 ;bit1=1

Move and Skip

Move and skip if zero

MOVSZ W,++fr

Move fr+1 into W and skip if zero.Translates to:

incfsz fr,0 ;W=fr+1:if 0,PC=PC+2

MOVSZ W,--fr

Move fr-1 into W and skip if zero.Translates to:

decfsz fr,0 ;W=fr-1:if 0,PC=PC+2

Negate

NEG fr

Negates fr. Translates to:

comf fr ;fr=~frincf fr ;fr=fr+1

No Operation

NOP

No operation. Translates to:

nop ;do nothing for one machine cycle

Not

Not fr/W

Complement file or working register.

NOT fr

Complements file register specified.Translates to:

comf fr ;fr=~fr

Reg./Flags affected:noneWords: 4Cycles: 4

Reg./Flags affected: WWords: 1Cycles: 1

Reg./Flags affected: WWords: 1Cycles: 1

Reg./Flags affected: ZWords: 2Cycles: 2

Reg./Flags affected: noneWords: 1Cycles: 1

Reg./Flags affected: ZWords: 1Cycles: 1

Page 265: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-27Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

NOT W

Complements working register.Translates to:

xorlw 0ffh ;W=W XOR FFh = ~W

OR

Or Destination, Source

Source is ORed with Destination. Destination may be file or working register.Source may be file or working register or a literal.

OR fr,#literal

OR literal into fr.Translates to:

movlw literal ;W=literaliorwfr fr

OR fr1,fr2

OR fr2 into fr1.Translates to:

movf fr2,0 ;W=fr2iorwf fr1 ;fr1=fr1 OR W

OR fr,W

OR W into fr.Translates to:

iorwf fr ;fr=fr OR W

OR W,#literal

OR literal into WTranslates to:

iorlw literal ;W=W OR literal

OR W,fr

OR fr into W.Translates to:

iorwf fr,0 W=W OR fr

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Page 266: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-28 ©1998 Sirius microSystems

Return

Return from subroutine

RET

Return from subroutine. Pops the valueoff the stack and places the value intothe program counter. Translates to: (12 bit core)

retlw 0 ;W=0: Pop PC

Translates to: (14 bit core)

return ;Pop PC

Return from interrupt

RETI

Return from interrupt subroutine. Pops thevalue off the stack and places the valueinto the program counter. GIE bit is setenabling interrupts. Translates to: (14 bit core only)

retfie ;Pop PC: Set GIE

Return with value in W

RETW #literal,#literal,...

Return from subroutine with value(s) inW. Pops the value off the stack andplaces the value into the program counter.Translates to:

retlw literal1 ;Pop PC: W=literal1retlw literal2 ;Pop PC: W=literal2...

Rotate

RL fr

Rotate fr left through carry.Translates to:

rlf fr ;C=fr.7:fr=(fr<<1)|C

RR fr

Rotate fr right through carry.Translates to:

rrf fr ;C=fr.7:fr=(fr>>1)|C

Reg./Flags affected: noneWords: 1Cycles: 2

Reg./Flags affected: noneWords: 1Cycles: 2

Reg./Flags affected: WWords: 1 - manyCycles: 2 per literal

Reg./Flags affected: CWords: 1Cycles: 1

Reg./Flags affected: CWords: 1Cycles: 1

Page 267: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-29Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

Skip

SB Bit

Skip next instruction if bit set.Translates to:

btfss bit ;if bit=0,PC=PC+2

SC

Skip next instruction if Carry flag set.Translates to:

btfss C ;if C=0,PC=PC+2

SKIP

Skip next instruction.Translates to:

btfss 4,7

SNB bit

Skip next instruction if not bit.Translates to:

btfsc bit ;if bit=0,PC=PC+2

SNC C

Skip next instruction if not Carry.Translates to:

btfsc C ;if C=0,PC=PC+2

SNZ bit

Skip next instruction if not Carry.Translates to:

btfsc Z ;if C=0,PC=PC+2

SZ

Skip next instruction if zero.Translates to:

btfss Z ;if Z=0,PC=PC+2

Reg./Flags affected: noneWords: 1Cycles: 1 (2 if skip)

Reg./Flags affected: noneWords: 1Cycles: 1 (2 if skip)

Reg./Flags affected: noneWords: 1Cycles: 2

Reg./Flags affected: noneWords: 1Cycles: 1(2 if skip)

Reg./Flags affected: noneWords: 1Cycles: 1(2 if skip)

Reg./Flags affected: noneWords: 1Cycles: 1 (2 if skip)

Reg./Flags affected: noneWords: 1Cycles: 1(2 if skip)

Page 268: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-30 ©1998 Sirius microSystems

Set

Set bit

SETB Bit

Bit = 1. Sets the specified bit.Translates to:

bsf bit ;bit=1

Set Carry

STC

Set carry flag.Translates to:

bsf C ;C=1Set Zero

STZ

Set zero flag.Translates to:

bsf Z ;Z=1

Sleep

SLEEP

Enter sleep mode.Translates to:

sleep ;Enter low power mode

Subtract

Sub minuend,subtrahend

Subtracts the subtrahend from the minuend. Minuend must be a file register.Subtrahend may be a file or working register or a literal.

SUB fr,#literal

Subtracts literal from fr.Translates to:

movlw literal ;W=literalsubwf fr ;fr=fr-W

Note: Although not explicitly referenced, SUB fr,#literal modifies W

Reg./Flags affected: noneWords: 1Cycles: 1

Reg./Flags affected: CWords: 1Cycles: 1

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: TO,PDWords: 1Cycles: 1

Reg./Flags affected: W,C,DC,ZWords: 2Cycles: 2

Page 269: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-31Appendix D

Parallax InstructionSet Reference

©1998 Sirius microSystems

SUB fr1,fr2

Subtracts fr2from fr1.Translates to:

movf fr2,0 ;W=fr2subwf fr1 ;fr1=fr1-W

Note: Although not explicitly referenced, SUB fr1,fr2 modifies W.

SUB fr,W

Subtracts W from fr.Translates to:

subwf fr ;fr=fr-W

Subtract Bit

SUBB fr,bit

Subtracts bit from fr.Translates to:

btfsc bitdecf fr

Swap Nibbles

SWAP fr

Swaps nibbles in fr.Translates to:

swap fr ;fr[3..0]|fr7..4]

Test

TEST fr

Tests fr for zero.Translates to:

movf fr ;if fr=0,Z=1 Else Z=0

Reg./Flags affected: W,C,DC,ZWords: 2Cycles: 2

Reg./Flags affected: Z (If bit 1)Words: 2Cycles: 2

Reg./Flags affected: noneWords: 1Cycles: 1

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: C,DC,ZWords: 2Cycles: 2

Page 270: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

D-32 ©1998 Sirius microSystems

XOR

XOR Destination,Source

Exclusive ORs destination with source. Destination may be the working registeror a file register. Source may be a literal, working or file register.

XOR fr,#literal

Exclusive OR literal into fr.Translates to:

movlw literal ;W=literalxorwf fr ;fr=fr XOR W

Note: Although not explicitly referenced, XOR fr,#literal modifies W.

XOR fr1,fr2

Exclusive OR fr2 into fr1.Translates to:

movf fr2,0 ;W=fr2xorwf fr1 ;fr1=fr1 XOR W

XOR fr,W

Exclusive OR W into fr.Translates to:

xorwf fr ;fr=fr XOR W

XOR W,#literal

Exclusive OR literal into W.Translates to:

xorlw literal ;W=W XOR literal

XOR W,fr

Exclusive OR fr into W.Translates to:

xorwf fr,0 ;W=W XOR fr

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: W,ZWords: 2Cycles: 2

Reg./Flags affected: ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Reg./Flags affected: W,ZWords: 1Cycles: 1

Page 271: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 1Program Pull-Out

References

Program Pull-Out ReferencesMicrochip Code

While we can’t promise a solution to all your problems, we do give you a good start!

Page 272: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code2

Copyright © 1996, 1998 Sirius microSystems. All rights reserved.

Second Printing.

Parallax is a Trademark of Parallax, Inc.PICmicro™ is a Registered Trademark of Microchip Technology Inc. in the U.S.A. and other countries.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by anymeans, mechanical, electronic, photocopying, or recording, or otherwise, without the prior written permissionof Sirius microSystems.

Sirius microSystems has taken care to trace ownership of copyright material contained in this text. However,Sirius microSystems will gladly accept any information that enables them to rectify any reference or credit insubsequent editions.

For conditions, permissions and other rights under this copyright, contact Sirius microSystems:

Sirius microSystems172 Harvard RoadWaterloo, ON N2J 3V3Canadatel.: 519.886.4462fax: 519.886.4253http://www.siriusmicro.com

ISBN 0-9681220-0-0 (Training Manual)ISBN 0-9681220-1-9 (Teacher’s Reference)

Disclaimer of Liability

This manual and the program subroutines included herein are written for the Sirius microSystems PICmicro™Development System and are provided on an “as is” basis, without any warranty, either expressed or implied.These materials are provided for educational use only, and Sirius microSystems does not assume any liability fordamages, either incidental or consequential, arising out of the application, use, or misuse of any of its softwareor hardware products. Sirius microSystems reserves the right, without further notice, to make changes to any ofits training materials, software or hardware referred to in this manual in order to improve its function, design orreliability.

Printed in Canada.

Page 273: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 3Program Pull-Out

References

ContentsPIC-MDS Subroutine Library Summary ........................................................ 5

ATOD.LIB .......................................................................................................................................5BIN2BCD.LIB .................................................................................................................................5BIN2DEC.LIB .................................................................................................................................6DEC2BIN.LIB .................................................................................................................................6EEPROM.LIB .................................................................................................................................6KEYPAD.LIB ...................................................................................................................................7LCD.LIB ..........................................................................................................................................7LCD4BIT.LIB...................................................................................................................................7RS232RX.LIB .................................................................................................................................8RS232TX.LIB .................................................................................................................................8SEEPROM.LIB ...............................................................................................................................9

Subroutine Library FilesATOD.LIB - PIC16C711 A/D Subroutine Library .......................................................................... 11BIN2BCD.LIB - Binary to BCD Conversion Library ......................................................................13BIN2DEC.LIB - Binary to Decimal Conversion Library .................................................................15DEC2BIN.LIB - Decimal to Binary Conversion Library .................................................................16EEPROM.LIB - PIC16F84 EEPROM Subroutine Library .............................................................17KEYPAD.LIB - Keypad Subroutine Library ...................................................................................19LCD.LIB - LCD Subroutine Library ............................................................................................... 21LCD4BIT.LIB - 4-bit Interface LCD Subroutine Library.................................................................24LCD71.LIB - PIC16C71/711 LCD Subroutine Library ...................................................................28RS232RX.LIB - RS-232 Receive Subroutine Library ...................................................................31RS232TX.LIB - RS-232 Transmit Subroutine Library ..................................................................34SEEPROM.LIB - Serial EEPROM Subroutine Library ..................................................................37

Chapter Example Program FilesALARM.ASM - Chapter 9 Example Program ...............................................................................43ASCII.ASM - Chapter 12 Example Program ................................................................................45BLIP.ASM - Chapter 8 Example Program ....................................................................................49BOUNCE.ASM - Chapter 9 Example Program ............................................................................51CLOCK.ASM - Chapter 11 Example Program..............................................................................53COUNT.ASM - Chapter 8 Example Program ...............................................................................58CUSTOM.ASM - Chapter 12 Example Program ..........................................................................59DBOUNCE.ASM - Chapter 9 Example Program ..........................................................................63DELAY.ASM - Chapter 8 Example Program .................................................................................65KEY.ASM - Chapter 10 Example Program ...................................................................................66KEYINT.ASM - Chapter 11 Example Program .............................................................................69KEYSCAN.ASM - Chapter 9 Example Program...........................................................................73KEYSCLB.ASM - Chapter 10 Example Program .........................................................................76NVMEM.ASM - Chapter 13 Example Program ............................................................................79OUTPUT.ASM - Chapter 5 Example Program .............................................................................84RECV232.ASM - Chapter 15 Example Program ..........................................................................85SEETEST.ASM - Chapter 17 Example Program..........................................................................88TIMEOUT.ASM - Chapter 18 Example Program ..........................................................................97VMETER.ASM - Chapter 16 Example Program .........................................................................101

Page 274: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code4

WDTIMER.ASM - Chapter 18 Example Program ......................................................................107XMIT232.ASM - Chapter 15 Example Program ......................................................................... 111

Page 275: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 5Program Pull-Out

References

PIC-MDS Subroutine Library Summary

This section provides a quick reference to the function, requirements if any, anduse of each subroutine library file included with the PIC-MDS. All variables shownas belonging to a subroutine library are not defined in the library code. These vari-ables must be defined (in the form of an EQUate statement) by the program thatcalls the library. For more details on library subroutines and operation, see the indi-vidual library pull-out programs and the chapters using the libraries.

ATOD.LIB

Provides subroutine function calls for analog-to-digital (A/D) converter operationin the PIC16C71/711.

Variables: none

Requirements: ADRES (09h) is used as a temporary register. Read ADRES con-tents before changing the A/D port, A/D clock divisor, or initiatinga new conversion.

Use: To convert a voltage on an A/D input pin into a binary number:1. CALL AD_Port to initialize Port A and turn on A/D. (opt.)2. Load W with a clock divisor, below, and CALL AD_Clock. (opt.)

ADCLK2 - oscillator/2ADCLK8 - oscillator/8ADCLK32 - oscillator/32ADCLKRC - internal RC oscillator

3. Load W with a pin number, below, and call AD_Channel. (opt.)ADCH0 - channel 0, pin RA0/AN0ADCH1 - channel 1, pin RA1/AN1ADCH2 - channel 2, pin RA2/AN2ADCH3 - channel 3, pin RA3/AN3

4. CALL AD_Poll to start the conversion.5. Read the conversion result from ADRES.

BIN2BCD.LIB

Converts a 16-bit binary number into five BCD nybbles.

Variables: HighByte - upper eight bits of the 16-bit number to convertLowByte - lower eight bits of the 16-bit number to convertTenThous - ten-thousands digit of result stored in lower nybbleThouHund - thousands digit and hundreds digit of resultTensOnes - tens digit and ones digit of resultShiftCounter - a counter used to count shifts during a conversion

Requirements: none

Use: To convert a 16-bit number into five BCD digits:1. Move a 16-bit binary number into HighByte and LowByte.2. CALL BIN_BCD to initiate the conversion.3. Read conversion results from TenThous, ThouHund, & TensOnes.

Steps marked with (opt.)are necessary when firstcalling the library and areunneccessary for subse-quent calls provided that noother libraries are called inbetween. For example,calling LCD_Port aftercalling AD_Port willreconfigure Port A fordigital I/O. Before callingAD_Poll, AD_Port must becalled.

Page 276: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code6

BIN2DEC.LIB

Converts an 8-bit binary number into three binary digits.

Variables: Hundreds - hundreds digit of the resultTens - tens digit of the resultOnes - ones digit of the result

Requirements: none

Use: To convert an 8-bit binary number into three binary digits:1. Load W with the binary number to be converted.2. CALL BIN_DEC to initiate the conversion.3. Read the results from Hundreds, Tens & Ones.

DEC2BIN.LIB

Converts three binary decimal (with values less than 10) digits into an 8-bit binarynumber.

Variables: Hundreds - hundreds digit of the initial numberTens - tens digit of the initial numberOnes - ones digit of the initial number

Requirements: none

Use: To convert three binary digits into an 8-bit binary number:1. Load Hundreds, Tens & Ones with the numbers to be converted.2. CALL DEC_BIN to initiate the conversion.3. Read the result from W.

EEPROM.LIB

Provides function calls for the internal data EEPROM in the PIC16C/F84.

Variables: none

Requirements: none

Use: To write data into an EEPROM address:1. Move an EEPROM address into EEADR.2. Move a data byte into EEDATA.3. CALL EE_Write.

To wait for EEPROM write completion:1. CALL EE_Wait.

To read data from an EEPROM address:1. Move an EEPROM address into EEADR.2. CALL EE_Read.3. Read the data from EEDATA.

Page 277: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 7Program Pull-Out

References

KEYPAD.LIB

Provides function calls for keypad scanning on the PIC-MDS. Returns a key codecorresponding to the key number of any one key being pressed. A return code of 0indicates no keys are pressed. This library does not implement key debouncing.

Variables: Key - contains the key code following a key scan

Requirements: none

Use: To scan for a key press:1. CALL KB_Port to configure Port B for keypad use. (opt.)2. CALL KB_Scan to scan for a key press.3. Read the key code from Key.

LCD.LIB

Provides function calls for LCD operation in 8-bit mode (this is the default mode forPIC-MDS programs).

Variables: none

Requirements: 1. Two free levels of processor stack are required for nested calls.2. The calling program must provide a 5 ms (minimum) time delayroutine called Delay_5ms.

Use: To initialize the LCD display after power-up:1. CALL LCD_Port to configure Port A and Port B for the LCD.2. CALL LCD_Init to initialize the LCD controller.

To write a character to the current LCD cursor position:1. CALL LCD_Port to configure Ports A and B for the LCD. (opt.)2. Load W with the ASCII value of the character.3. CALL LCD_Data to display the character.

To write a command or character address to the LCD controller:1. CALL LCD_Port to configure Ports A and B for the LCD. (opt.)2. Load W with the command or character address.3. CALL LCD_Reg to write the data into the LCD controller.

Some important LCD commands (see the library file for others):LCDLine1 - character address for the start of line 1LCDLine2 - character address for the start of line 2LCDCLR - clears the LCD display memoryLCDInc - sets automatic cursor increment modeCursOn - displays the LCD cursorCursOff - disables display of the LCD cursor

LCD4BIT.LIB

Same as LCD.LIB but operates in 4-bit mode. Requirements and Use are as above.

Variables: LCDTemp - stores commands and data for transmission.

Page 278: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code8

RS232RX.LIB

Provides function calls to receive RS-232 serial data without handshaking. The de-fault RS-232 data rate is 9600 bps, although this can by changed by modifying theBit_Time variable in RS232RX.LIB. Subroutines are provided to wait for a serialcharacter, or to begin reception after the calling program detects a start bit. If aframing error occurs during reception, the Receive byte will be cleared (00h).

Variables: Counter - delay counter for bit time delay loopBitCounter - counts number of received bitsReceive - holds received serial character

Requirements: Two free levels of processor stack are required for nested calls.

Use: To wait for and receive a serial character:1. CALL Receive_Port to configure Port A.4 for input.2. CALL Receive_Wait to wait for the next serial character.3. Read the received character from Receive.

To receive a serial character after detecting a start bit:1. CALL Receive_Port prior to waiting for a start bit.2. CALL Receive_Data after detecting a start bit.3. Read the received character from Receive.

RS232TX.LIB

Provides function calls to transmit RS-232 serial data without handshaking. Thedefault RS-232 data rate is 9600 bps, although this can be changed by modifying theBit_Time variable in RS232TX.LIB.

Variables: Counter - delay counter for bit time delay loopBitCounter - counts number of transmitted bitsTransmit - stores the serial character to be transmitted

Requirements: Two free levels of processor stack are required for nested calls.

Use: To transmit a serial character:1. CALL Transmit_Port to configure Port A.4 for output.2. Move the byte to be transmitted into Transmit.3. CALL Transmit_Data to send the serial byte.

Page 279: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 9Program Pull-Out

References

SEEPROM.LIB

Provides function calls for interfacing to 93LC56 (256-byte) and 93LC66 (512-byte)serial EEPROMs (SEEPROMs) in 8-bit mode only.

Variables: SEEClock - clock counter register for serial data frameSEEData - SEEPROM data byte storage registerSEEAddrh - SEEPROM high address byteSEEAddrl - SEEPROM low address byte

Requirements: Two free levels of processor stack are required for nested calls.

Use: To enable or disable SEEPROM write access:1. CALL SEE_Port to configure Ports A & B. (opt.)2. Move SEEEWEN (enable) or SEEEWDS (disable) into W.3. CALL SEE_Command to send the command to the SEEPROM.

To write a data byte into a SEEPROM address:1. CALL SEE_Port to configure Ports A & B. (opt.)2. Load SEEAddrh with the high byte of the SEEPROM address.3. Load SEEAddrl with the low byte of the SEEPROM address.4. Load SEEData with the data byte to be written.5. Move the SEEWrite constant into W.6. CALL SEE_Command to initiate the write operation.7. CALL SEE_Wait to wait for the completion of the write. (opt.)

To read a data byte from a SEEPROM address:1. CALL SEE_Port to configure Ports A & B. (opt.)2. Load SEEAddrh with the high byte of the SEEPROM address.3. Load SEEAddrl with the low byte of the SEEPROM address.4. Move the SEERead constant into W.5. CALL SEE_Command to initiate the write operation.6. Read the data byte from SEEData.

See the library pull-out for information on the Erase, Erase All, andWrite All commands.

Page 280: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code10

Page 281: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 11Program Pull-Out

References

ATOD.LIB - PIC16C711 A/D Subroutine Library

;ATOD.LIB V1.2 Last Modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine library provides calls for A/D converter operation,; including:; - Port configuration; - A/D Channel selection; - Conversion Clock selection; - A/D conversion routine with polling

;Variables

; No file register variables are required by this subroutine library.; ADRES (09h) is used for temporary storage.

;Requirements

; ADRES (09h) is used as a temporary register before conversion. Ensure; that its data has been read before calling the library functions for; the next conversion. ADRES normally holds the A/D conversion result.

; Calling programs may require shorting jumpers over RA0 and RA1 on the; JU6 header. These jumpers physically connect potentiometers VR3 and; VR4 to the RA0 and RA1 inputs on the PIC16C711. Normally these jumpers; are not installed to minimize the effect of an analog voltage source; (from the potentiometers) on the digital I/O lines.

;Use

; 1. Call AD_Port to initialize Port A for A/D operation and turn on A/D; 2. Move a clock divisor constant into W and call AD_Clock; 3. Move a channel selector constant into W and call AD_Channel; 4. Call AD_Poll; 5. Read the result from ADRES

;A/D Clock Divisor Software Constants

ADCLK2 EQU 00000000b ;A/D clock=oscillator/2ADCLK8 EQU 01000000b ;A/D clock=oscillator/8ADCLK32 EQU 10000000b ;A/D clock=oscillator/32ADCLKRC EQU 11000000b ;A/D clock from internal RC osc.

;One A/D clock (TAD) must be greater than 2 microseconds. Choose a clock;divider from above based on your oscillator frequency.

;eg. 16 MHz oscillator 1 oscillator clock = T = 62.5 ns;; TAD / T = Clock divider; 2 us / 62.5 ns = 32;; Therefore, a 16 MHz oscillator must be divided by 32 to; produce the correct A/D clock.;

Page 282: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code12

;An A/D conversion completes in 10 TAD. For the example above, the;conversion will finish in 20 microseconds.

;Using the internal oscillator allows a conversion to be performed during;SLEEP for greatest accuracy. Use interrupt to wake processor when the;conversion finishes. Conversion time with the RC oscillator is nominally;40 microseconds but varies between individual processors.

;A/D Channel Selector Software Constants

ADCH0 EQU 00000000b ;A/D conversion on RA0ADCH1 EQU 00001000b ;A/D conversion on RA1ADCH2 EQU 00010000b ;A/D conversion on RA2ADCH3 EQU 00011000b ;A/D conversion on RA3

;A/D conversion channels 2 and 3 are not implemented on the PIC-MDS but;can be accessed through the screw terminal strip or PICBUS.

AD_Port ;Initializes ADCON1 for analog input on RA0 and RA1 with ;VDD as the voltage reference and turns A/D converter on.

BSF RP0 ;Select memory page 1 MOVLW 00000011b ;OR this byte with TRISA to enable IORWF TRISA ;required analog pins as inputs MOVLW 02h ;Make RA0 and RA1 analog inputs by MOVWF ADCON1 ;writing this byte to ADCON1 (88h) BCF RP0 ;Back to page 0 BSF ADON ;Turn A/D converter on RETURN

AD_Clock ;Sets ACDS0 and ADCS1 bits in ADCON0 based on the number ;in W. Load W with a clock divider constant from the ;list, above. Read ADRES before calling AD_Clock.

MOVWF ADRES ;Use ADRES as temporary storage MOVLW 3Fh ;Load W with 0011 1111 ANDWF ADCON0,1 ;AND with ADCON0 to clear high bits MOVF ADRES,0 ;Get clock divider bits from ADRES IORWF ADCON0,1 ;OR with ADCON0 to set clock bits RETURN

AD_Channel ;Sets CHS0 and CHS1 bits in ADCON0 based on the number in ;W when AD_Channel was called. Load W from channel constants ;list, above. Read ADRES before calling AD_Channel.

MOVWF ADRES ;Use ADRES as temporary storage MOVLW 11100111b ;Load W with 1110 0111 and ANDWF ADCON0,1 ;AND with ADCON0 to clear CHS0/1 MOVF ADRES,0 ;Get channel select bits from ADRES IORWF ADCON0,1 ;OR with ADCON0 to set channel bits RETURN

AD_Poll ;Sets GO_DONE bit in ADCON0 to start the A/D conversion ;and keeps polling the bit until the conversion is ;complete. Get the result of the conversion from ADRES.

BSF GO_DONE ;Start A/D conversion:Loop BTFSC GO_DONE ;Check GO_DONE for end of conversion GOTO :Loop ;and keep checking until done RETURN

ATOD.LIB - PIC16C711 A/D Subroutine Library

Page 283: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 13Program Pull-Out

References

BIN2BCD.LIB - Binary to BCD Conversion Library

;BIN2BCD.LIB V1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine library converts 16-bit binary numbers to five BCD; digits stored in three file register locations. The result registers; are TenThous to hold the ten-thousands digit, ThouHund to hold the; thousands and hundreds digits, and TensOnes to hold the tens and ones; digits. This subroutine is useful for displaying a 16-bit variable as; five decimal digits on the LCD display.

; This routine takes 458 clock cycles to complete. If you don�t need; 16-bit accuracy�for example for a 12-bit A/D converter�you can; redefine the BinBits (Binary Bits) variable for the number of bits of; accuracy that are required. This results in shorter conversion times.

; Note also that the contents of HighByte and LowByte are corrupted during; the conversion and therefore their contents will have changed upon; returning to the calling program.

;Variables

; The following variables must be defined as file register locations in; your calling program. Use the format:

; Variable name EQU File Register location (0Ch to 2Fh)

; HighByte - the high byte of the 16-bit number to convert; LowByte - the low byte of the 16-bit number to convert; TenThous - the ten-thousands digit of the result; ThouHund - the thousands and hundreds digits of the result; TensOnes - the tens and ones digits of the result; ShiftCounter - a counter used to count shifts during the conversion

; The following variable is a Software variable that defines the number; of bits to be converted. By default, this is 16 bits.

; BinBits - equated to 16. Change this in the program to; convert fewer digits

;Use

; 1. Move the binary number into HighByte and LowByte; 2. Call BIN_BCD; 3. Retreive your results from TenThous, ThouHund, and TensOnes

;Software Equate

BinBits EQU 16 ;Number of binary bits to convert

BIN_BCD ;This conversion subroutine uses the add-3 algorithm to ;convert binary to BCD. The binary number is shifted into ;the BCD registers one bit at a time. After each shift, each

Page 284: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code14

;BCD digit is checked to see if it is greater than or equal;to five. If so, three is added to the BCD digit. The original;number is the shifted again before each digit is checked to;see if it equals or exceeds 5. After 16 shifts, the result;is complete.

MOVLW BinBits ;Save the number binary digits in theMOVWF ShiftCounter ;number into the ShiftCounter register

CLRF TensOnes ;Clear all BCD digits before startingCLRF ThouHundCLRF TenThous

GOTO ShiftBits ;Start by shifting bits into BCD regs.

Adj_BCD MOVLW 03h ;Preload W with 03 and add to lowerADDWF TensOnes ;nybble in TensOnes registerBTFSS TensOnes.3 ;Check for a result greater than 7SUBWF TensOnes ;If not, subtract three from nybbleMOVLW 30h ;Preload W to add 03 to upper nybbleADDWF TensOnes ;in TensOnes registerBTFSS TensOnes.7 ;Check for a result greater than 7SUBWF TensOnes ;If not, subtract three from nybble

MOVLW 03h ;Preload W with 03 and add to lowerADDWF ThouHund ;nybble in ThouHund registerBTFSS ThouHund.3 ;Check for a result greater than 7SUBWF ThouHund ;If not, subtract three from nybbleMOVLW 30h ;Preload W to add 03 to upper nybbleADDWF ThouHund ;in ThouHund registerBTFSS ThouHund.7 ;Check for a result greater than 7SUBWF ThouHund ;If not, subtract three from nybble

MOVLW 03h ;Preload W with 03 and add to lowerADDWF TenThous ;nybble in TenThous registerBTFSS TenThous.3 ;Check for a result greater than 7SUBWF TenThous ;If not, subtract three from nybble

ShiftBits BCF C ;Clear Carry before first shiftRLF LowByte ;Shift Low Byte left, C into HighByteRLF HighByte ;Shift High Byte left, C into TensOnesRLF TensOnes ;Shift TensOnes left, C into ThouHundRLF ThouHund ;Shift ThouHund left, C into TenThousRLF TenThous ;Shift TenThous left

DECFSZ ShiftCounter ;Check if all bits have been shiftedGOTO Adj_BCD ;If not, adjust digits and shift againRETURN

BIN2BCD.LIB - Binary to BCD Conversion Library

Page 285: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 15Program Pull-Out

References

BIN2DEC.LIB - Binary to Decimal Conversion Library

;BIN2DEC.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine library converts 8-bit binary numbers to a three-digit; decimal code (ie. 0-0-0 - 2-5-5) and stores the result in three file; register locations. This subroutine is useful for displaying a binary; number as three decimal digits on the LCD display.

;Variables

; The following variables must be defined as file register locations in; your calling program. Use the format:

; Variable name EQU File Register location (0Ch to 2Fh)

; HUNDREDS - the hundreds digit counter; TENS - the tens digit counter; ONES - the ones remainder

;Use

; 1. Move the binary number into W; 2. Call BIN_DEC; 3. Retreive your results from Hundreds, Tens and Ones

BIN_DEC ;This conversion program attempts to subtract 100 from;the binary number until the result is negative. Each;subtraction increments the HUNDREDS digit. When it can�t;subtract 100, the program subtracts 10 from the remainder;until the result once again is negative, incrementing the;TENS digit for each subtraction. The remainder of the;subtraction becomes the ONES digit.

CLRF HUNDREDS ;Reset the hundreds counterCLRF TENS ;and the tens counterMOVWF ONES ;Ones digit holds results

:Hundred MOVLW 100 ;Load W with 100 andSUBWF ONES,W ;subtract it from the numberBTFSS C ;If result is negativeGOTO :Ten ;check for any tensINCF HUNDREDS ;otherwise count 1 hundredMOVWF ONES ;Remainder becomes resultGOTO :Hundred ;Check for another hundred

:Ten MOVLW 10 ;Load W with 10 andSUBWF ONES,W ;subtract it from the numberBTFSS C ;If result is negativeRETURN ;we�re done, ONES holds remainderINCF TENS ;otherwise count 1 tenMOVWF ONES ;Remainder becomes resultGOTO :Ten ;Check for another ten

Page 286: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code16

DEC2BIN.LIB - Decimal to Binary Conversion Library

;DEC2BIN.LIB v1.2 Last Modified on July 9, 1999

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine library converts a three-digit decimal code to an; 8-bit binary number and returns the number in W. The three digits are; loaded from three file register locations and should not represent a; number larger than 255 (no error checking is done). This routine is; useful for storing user input as a byte of data.

;Variables

; The following variables must be defined as file register locations in; your calling program. Use the format:

; Variable name EQU File Register location (0Ch to 2Fh)

; HUNDREDS - the hundreds digit counter; TENS - the tens digit counter; ONES - the ones remainder

;Use

; 1. Move three decimal numbers into Hundreds, Tens and Ones; 2. Call Dec_Bin; 3. Retrieve the binary number from W

Dec_Bin ;This conversion program starts by clearing W. 100 is added;to W for each Hundreds digit. Hundreds digits are counted;by decrementing the Hundreds digit until it reaches 0. Next,;10 is added to W for each Tens digit. Finally, the Ones;digit is added to W to get the result.

CLRW ;Clear W to store resultMOVF Hundreds,1 ;Move Hundreds register to itselfBTFSC Z ;to check for zeroGOTO :Tens ;If no hundreds digit check tens digit

:Add_Hundred ADDLW 100 ;Add 100 to W since there are hundredsDECFSZ Hundreds,1 ;Decrement hundreds digit, check for 0GOTO :Add_Hundred ;If more hundreds, add another 100

:Tens MOVF Tens,1 ;Move Tens register to itselfBTFSC Z ;to check for zeroGOTO :Ones ;If no tens digit check ones digit

:Add_Ten ADDLW 10 ;Add 10 to W since there are tensDECFSZ Tens,1 ;Decrement tens digit, check for 0GOTO :Add_Ten ;If more tens, add another 10

:Ones ADDWF Ones,0 ;Add contents of Ones register to WRETURN ;All Done!

Page 287: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 17Program Pull-Out

References

;EEPROM.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for PIC16F84 EEPROM operation including:; - EEPROM data write; - EEPROM data read; - Wait for EEPROM write to finish

;Variables

; None

;Requirements

; None

;Use

; To write data to the EEPROM:; 1. Move an EEPROM address into EEADR; 2. Move the data to be written into EEDATA; 3. CALL EE_Write

; To wait for EEPROM write completion:; 1. CALL EE_Wait (on RETURN, EEPROM write is complete)

; To read data from the EEPROM:; 1. Move an EEPROM address into EEADR; 2. CALL EE_Read (the data will be available in EEDATA)

;Notes

; Instead of waiting for the EEPROM write to finish, EEIF can generate; an interrupt. When using interrupts, some precautions must be taken:

; 1. Disable GIE (all interrupts) before calling EE_Write.; 2. On exit from EE_Write, re-enable interrupts

; Microchip strongly recommends that interrupts be disabled during; the EEPROM write sequence.

EE_Read ;Sets the RD bit in EECON1 to read the contents of EEADR;into EEDATA.

BSF RP0 ;Select memory register page 1BSF RD ;Set the EECON1.RD bit to readBCF RP0 ;Return to memory register page 0RETURN

EE_Write ;Writes the contents of EEDATA to EEADR as specified in;the PIC16F84 data sheets after enabling WREN. After;writing the data, WREN is cleared, disabling accidental

EEPROM.LIB - PIC16F84 EEPROM Subroutine Library

Page 288: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code18

;writes.

BSF RP0 ;Select memory register page 1BSF WREN ;Enable EEPROM writesMOVLW 55hMOVWF EECON2 ;Write 55h to EECON2MOVLW 0aahMOVWF EECON2 ;Write AAh to EECON2BSF WR ;Set EECON1.WR bitBCF WREN ;Disable any further writesBCF RP0 ;Return to memory register page 0RETURN

EE_Wait ;Wait for an EE_Write to finish by checking the EEIF;flag bit in EECON1.

BSF RP0 ;Select memory register page 1:Wait BTFSS EEIF ;Check EEIF for a high (1=finished)

GOTO :Wait ;If low, wait for EEIF to go highBCF EEIF ;Clear EEIF after write is doneBCF RP0 ;Return to memory register page 0RETURN

EEPROM.LIB - PIC16F84 EEPROM Subroutine Library

Page 289: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 19Program Pull-Out

References

;KEYPAD.LIB v1.2 Last Modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine library provides calls for keyboard scanning, including:; - Keypad port configuration; - Key code retrieval

;Variables

; Key - key code return register (EQU to a file register)

;Requirements

; Ensure that your calling program defines KEY as a hardware register.; After calling KB_Scan, the KEY register contains the number of the; key pressed. If no key was pressed, KEY contains the number 0.

;Use

; 1. Call KB_Port to initialize Port B for the keyboard; 2. Call KB_Scan to scan for a key press; 3. Retrieve the Key code from the Key variable

;Notes: You should add a key debouncing routine to your calling program.; Each time a key is pressed, the mechanical contacts �bounce� for; a short time, alternately making and breaking the key connection.; Key bounce would be read by the microcontroller as a series of; rapid key presses instead of one single key press. Keys and buttons; can be debounced by reading the keys once, and then again after; a short debouncing delay:;; 1. Call KB_Port to initialize Port B for keypad use; 2. Call KB_Scan to scan for a key press; 3. Save the Key code variable in a temporary register; 4. Call a delay routine of 20 ms; 5. Call KB_Scan again to scan for a key press; 6. Compare the new Key code value to the Key code saved in the; temporary register. If they�re the same the key press is valid,; otherwise discard the key press.

KB_Port ;Initializes Port B for keyboard input by setting RB0-3 as;output and RB4-7 as inputs with pull-up resistors enabled.

BSF RP0 ;Select memory page 1MOVLW 0F0h ;Set high nibble to input andMOVWF TRISB ; low nibble to outputBSF RBPU ;Enable pull-ups on inputsBCF RP0 ;Select memory page 0RETURN ;Done, return to calling program

KB_Scan ;Scans the keyboard by:; 1. Setting the Key variable to a 1 for the first key code; 2. Setting all row outputs except row 1 to a high (row 1

KEYPAD.LIB - Keypad Subroutine Library

Page 290: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code20

; gets set to a low.; 3. Checking each column input in turn for the low on row 1.; If no key is pressed, the column will read high due to; the pull-up resistors. If a key is pressed, the column; will read low.; 4. Repeatedly setting all row outputs except the next row; high and repeating step 3 for each row.

;If a key press is detected, the routine exits with the key;number in the Key variable. Key numbers are (in decimal):

; Col. 1 2 3 4; Row +----+----+----+----+; 1 | 1 | 2 | 3 | 4 |; +----+----+----+----+; 2 | 5 | 6 | 7 | 8 |; +----+----+----+----+; 3 | 9 | 10 | 11 | 12 |; +----+----+----+----+; 4 | 13 | 14 | 15 | 16 |; +----+----+----+----+;If no key press is detected, the routine exits with the;number 0 in the Key variable. This makes it easy to check;for no key presses by testing the Z flag.

;The KB_Scan routine checks for key presses in the sequence;indicated by the key numbers, above. If two or more keys;are pressed simultaneously, only the first key in the;sequence will be returned.

CLRF Key ;Clear Key register and thenINCF Key ;set Key to first return codeMOVLW 0Eh ;Output 0 to first row only,MOVWF PORTB ;Output to Port BNOP ;and wait for signals to settle

:Col_Check BTFSS PORTB.4 ;Check first column for lowRETURN ;and exit on key pressINCF Key ;If no key press, increment key numberBTFSS PORTB.5 ;Check second column for lowRETURN ;and exit on key pressINCF Key ;If no key press, increment key numberBTFSS PORTB.6 ;Check third column for lowRETURN ;and exit on key pressINCF Key ;If no key press, increment key numberBTFSS PORTB.7 ;Check fourth column for lowRETURN ;and exit on key pressINCF Key ;If no key press, increment key number

:Row_Set MOVLW 11h ;Load W with number of keys + 1SUBWF Key,0 ;and compare with current key valueBTFSC Z ;If keys + 1 = current key thenGOTO :No_Keys ;no key was pressedBSF C ;Set carry bit to make first row highRLF PORTB ;and rotate row outputsGOTO :Col_Check

:No_Keys CLRF Key ;Set Key variable to 0 andRETURN ;return to calling program

KEYPAD.LIB - Keypad Subroutine Library

Page 291: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 21Program Pull-Out

References

;LCD.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for LCD operation including:; - Port Configuration; - Register mode commands; - LCD Busy check; - LCD Enable toggle

;Variables

; None

;Requirements

; Two free levels of processor stack are required for nested calls.

; The LCD_Init subroutine requires a minimum 5ms delay to initialize; the LCD. Delays longer than 5ms are acceptable. LCD_Init calls a; subroutine by the name of Delay_5ms which must be included in your; calling program. If your calling program contains a delay loop of; longer than 5ms, you can use that delay by adding a Delay_5ms; label before the routine.

;Use

; To initialize the LCD display after power-up:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Call LCD_Init to initialize the LCD controller

; To write a command or character to the LCD display:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Move an LCD command or ASCII character into W; 3. Call LCD_Reg or LCD_Data to send the command or; character to the LCD.

;LCD Hardware Equates

LCDRS EQU PORTA.0 ;LCD Register SelectLCDRW EQU PORTA.1 ;LCD Read/~WriteLCDE EQU PORTA.2 ;LCD Enable

;LCD Software Commands (Constants)

LCDLine1 EQU 80h ;Line 1 starting addressLCDLine2 EQU 0C0h ;Line 2 starting addressLCDCLR EQU 01h ;Clear Display, cursor homeLCDHome EQU 02h ;Cursor home, DDRAM unchangedLCDInc EQU 06h ;Cursor increment modeLCDDec EQU 04h ;Cursor decrement modeLCDOn EQU 0Ch ;Display OnLCDOff EQU 08h ;Display Off

LCD.LIB - LCD Subroutine Library

Page 292: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code22

CursOn EQU 0Eh ;Display On and Cursor OnCursOff EQU 0Ch ;Display On and Cursor OffCursBlink EQU 0Fh ;Display On and Cursor BlinkingLCDLeft EQU 18h ;Shift Display LeftLCDRight EQU 1Ch ;Shift Display RightCursLeft EQU 10h ;Move Cursor LeftCursRight EQU 14h ;Move Cursor RightLCDFunction EQU 38h ;8-bit function register init. commandLCDInit EQU 38h ;LCD initialization commandLCDCGRAM EQU 40h ;CGRAM starting address

LCD_Port ;Initializes the Port B tristate buffers as outputs for;LCD data lines. Sets Port A to digital (on PIC16C711) and;sets the LCD Register Select, Read/~Write, and Enable;lines to outputs.

BSF RP0 ;Select memory register page 1

;the next two lines are for the PIC16C711 only and should be;removed for the PIC16F84 (PM produces an error when this;is assembled for the �84).

;MOVLW 03h ;1�s set Port A to digital;MOVWF ADCON1 ;Write W to ADCON1 (88h)

MOVLW 11111000b ;Set lower 3 bits of RA toANDWF TRISA ;digital output in TRISACLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0BCF LCDE ;Keep LCD Enable line offRETURN ;Ports are now set up for LCD

LCD_Init ;LCD initialization instructions from the Optrex data book.;Sets LCD functions for DMC16207 display, performs soft-;ware reset, clears memory and turns the display on.

MOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCDCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDFunction ;Load W with initialize 8-bit codeCALL LCD_Reg ;and send it to LCDCALL Delay_5ms ;...and wait

;Change the constant in the next line to set how the display;is activated. eg. LCDOn, CursOn, CursBlink. The Constant is;from the LCD software commands, above.

MOVLW LCDOn ;Command for display on & cursor off

CALL LCD_Reg ;Send it to LCDMOVLW LCDCLR ;Load W with clear LCD codeCALL LCD_Reg ;and send it to LCDMOVLW LCDInc ;Load W with increment mode codeCALL LCD_Reg ;and send it to LCDRETURN

LCD_Reg_Init ;Used only for initialization prior to setting function;register. In this time, the LCD busy flag cannot be checked.

LCD.LIB - LCD Subroutine Library

Page 293: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 23Program Pull-Out

References

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD reg. on Port BGOTO LCD_Enable ;Send register command

LCD_Reg ;Load W with LCD software constant from table, above.;LCD_Reg outputs the command to the LCD and blips the;enable line with LCD_Enable to complete the command.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD reg. on Port BCALL LCD_Check ;Check LCD busy flagGOTO LCD_Enable ;Send register command

LCD_Data ;Load W with the ASCII character code to send to LCD.;LCD_Data outputs the character to the LCD and blips;the enable line with LCD_Enable to complete the send.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD on Port BCALL LCD_Check ;Check LCD busy flagBSF LCDRS ;Enter ASCII modeGOTO LCD_Enable ;Send ASCII character

LCD_Check ;Checks the state of the LCD Busy flag and waits for any;previous command to finish before returning to the;calling routine.

BSF LCDRW ;Set LCD read modeBSF RP0 ;Select memory page 1MOVLW 0FFh ;Set Port B to input andMOVWF TRISB ;disable tristate buffersBCF RP0 ;Back to memory page 0BSF LCDE ;Enable LCDNOP ;and wait for an extra cycle

:Loop BTFSC PORTB.7 ;Check LCD busy bit andGOTO :Loop ;wait if high. (Busy=1)BCF LCDE ;Disable LCDBSF RP0 ;Select memory page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Back to memory page 0BCF LCDRW ;Back to LCD write modeRETURN ;LCD is now free

LCD_Enable ;Sends a 500 ns enable pulse to the LCD to complete the;register or character write operation. The NOP instruction;is only required for processors faster than 8 MHz. For;processors faster than 16 MHz, add a second NOP.

BSF LCDE ;Set enable lineNOP ;and pause for an extra 250nsBCF LCDE ;Reset the enable lineRETURN ;Done!

LCD.LIB - LCD Subroutine Library

Page 294: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code24

;LCD4BIT.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for LCD operation in 4-bit mode; including:; - Port Configuration; - Register mode commands; - LCD Busy check; - LCD Enable toggle

;Variables

; LCDTemp - Temporary command byte storage register

;Requirements

; Two free levels of processor stack are required for nested calls.

; The LCD_Init subroutine requires a minimum 5ms delay to initialize; the LCD. Delays longer than 5ms are acceptable. LCD_Init calls a; subroutine by the name of Delay_5ms which must be included in your; calling program. If your calling program contains a delay loop of; longer than 5ms, you can use that delay by adding a Delay_5ms; label before the routine.

;Use

; To initialize the LCD display after power-up:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Call LCD_Init to initialize the LCD controller

; To write a command or character to the LCD display:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Move an LCD command or ASCII character into W; 3. Call LCD_Reg or LCD_Data to send the command or; character to the LCD.

;LCD Hardware Equates

LCDRS EQU PORTA.0 ;LCD Register SelectLCDRW EQU PORTA.1 ;LCD Read/~WriteLCDE EQU PORTA.2 ;LCD Enable

;LCD Software Commands (Constants)

LCDLine1 EQU 80h ;Line 1 starting addressLCDLine2 EQU 0C0h ;Line 2 starting addressLCDCLR EQU 01h ;Clear Display, cursor homeLCDHome EQU 02h ;Cursor home, DDRAM unchangedLCDInc EQU 06h ;Cursor increment modeLCDDec EQU 04h ;Cursor decrement modeLCDOn EQU 0Ch ;Display On

LCD4BIT.LIB - 4-bit Interface LCD Subroutine Library

Page 295: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 25Program Pull-Out

References

LCDOff EQU 08h ;Display OffCursOn EQU 0Eh ;Display On and Cursor OnCursOff EQU 0Ch ;Display On and Cursor OffCursBlink EQU 0Fh ;Display On and Cursor BlinkingLCDLeft EQU 18h ;Shift Display LeftLCDRight EQU 1Ch ;Shift Display RightCursLeft EQU 10h ;Move Cursor LeftCursRight EQU 14h ;Move Cursor RightLCDFunction EQU 28h ;4-bit function register init. commandLCDInit EQU 38h ;LCD InitializationLCDCGRAM EQU 40h ;CGRAM starting address

LCD_Port ;Initializes the top 4 Port B tristate buffers as outputs for;LCD data lines. Sets Port A to digital (on PIC16C711) and;sets the LCD Register Select, Read/~Write, and Enable;lines to outputs.

BSF RP0 ;Select memory register page 1

;the next two lines are for the PIC16C711 only and should be;removed for the PIC16F84 (PM produces an error when this;is assembled for the �84).

;MOVLW 03h ;1�s set Port A to digital;MOVWF ADCON1 ;Write W to ADCON1 (88h)

MOVLW 11111000b ;Set lower 3 bits of RA toANDWF TRISA ;digital output in TRISAMOVLW 00001111b ;Set upper 4 bits of TRISB toANDWF TRISB ;digital outputBCF RP0 ;Go back to register page 0BCF LCDE ;Keep LCD Enable line offRETURN ;Ports are now set up for LCD

LCD_Init ;LCD initialization instructions from the Optrex data book.;Sets LCD functions for DMC16207 display, performs soft-;ware reset, sets 4-bit mode, clears memory and turns the;display on.

MOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCDCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDFunction ;Load W with initialize 4-bit modeCALL LCD_Reg_Init ;and send it to LCDCALL Delay_5ms ;...and waitMOVLW LCDFunction ;Load W with initialize 4-bit modeCALL LCD_Reg ;and send it to LCDCALL Delay_5ms ;...and wait

;Change the constant in the next line to set how the display;is activated. eg. LCDOn, CursOn, CursBlink. The Constant is;from the LCD software commands, above.

MOVLW LCDOn ;Command for display on & cursor offCALL LCD_Reg ;Send it to LCDMOVLW LCDCLR ;Load W with clear LCD codeCALL LCD_Reg ;and send it to LCDMOVLW LCDInc ;Load W with increment mode codeCALL LCD_Reg ;and send it to LCDRETURN

LCD4BIT.LIB - 4-bit Interface LCD Subroutine Library

Page 296: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code26

LCD_Reg_Init ;Used only for initialization prior to setting 4-bit mode.;W is loaded with the 8-bit initialization string (38h) of;which only the top 4 bits (3h) are sent to the LCD.

MOVWF LCDTemp ;Store command in temporary registerMOVLW 0Fh ;Load W with value to clearANDWF PORTB ;upper 4 bits of Port BBCF LCDRS ;Enter register modeMOVF LCDTemp,0 ;Load W with command byteANDLW 11110000b ;Keep upper 4 bits of W andIORWF PORTB ;OR with PORT BGOTO LCD_Enable ;and send first nybble of command

LCD_Reg ;Load W with LCD software constant from table, above.;LCD_Reg outputs the command to the LCD as two separate;nybbles (first the upper 4 bits, then the lower 4 bits) and;blips the enable line with LCD_Enable to finish the command.

MOVWF LCDTemp ;Store command byte in temp registerMOVLW 0Fh ;Load W with value to clearANDWF PORTB ;upper 4 bits of Port BBCF LCDRS ;Enter register modeMOVF LCDTemp,0 ;Load W with command byteANDLW 11110000b ;Keep upper 4 bits of W andIORWF PORTB ;OR with PORT BCALL LCD_Check ;Check LCD busy flagCALL LCD_Enable ;and send first part of commandMOVLW 0Fh ;Load W with value to clearANDWF PORTB ;upper 4 bits of Port BSWAPF LCDTemp,0 ;Load W with lower nybble of commandANDLW 11110000b ;Keep upper 4 bits of W andIORWF PORTB ;OR with PORT BGOTO LCD_Enable ;Send second part of command & return

LCD_Data ;Load W with the ASCII character code to send to LCD.;LCD_Data outputs the character to the LCD and blips;the enable line with LCD_Enable to complete the send.

MOVWF LCDTemp ;Store data byte in temporary registerMOVLW 0Fh ;Load W with value to clearANDWF PORTB ;upper 4 bits of Port BBCF LCDRS ;Enter register modeMOVF LCDTemp,0 ;Load W with command byteANDLW 11110000b ;Keep upper 4 bits of W andIORWF PORTB ;OR with PORT BCALL LCD_Check ;Check LCD busy flagBSF LCDRS ;Set RS to ASCII modeCALL LCD_Enable ;and send upper nybble of characterMOVLW 0Fh ;Load W with value to clearANDWF PORTB ;upper 4 bits of Port BBCF LCDRS ;Set RS to register modeSWAPF LCDTemp,0 ;Load W with lower nybble of commandANDLW 11110000b ;Keep upper 4 bits of W andIORWF PORTB ;OR with PORT BBSF LCDRS ;Set RS to ASCII modeGOTO LCD_Enable ;Send second part of command & return

LCD_Check ;Checks the state of the LCD Busy flag and waits for any;previous command to finish before returning to the;calling routine.

BSF LCDRW ;Set LCD read modeBSF RP0 ;Select memory page 1

LCD4BIT.LIB - 4-bit Interface LCD Subroutine Library

Page 297: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 27Program Pull-Out

References

MOVLW 0F0h ;Set upper 4 bits of Port B to inputIORWF TRISB ;in tristate buffers by ORingBCF RP0 ;Back to memory page 0BSF LCDE ;Enable LCDNOP ;and wait for an extra cycle

:Loop BTFSC PORTB.7 ;Check LCD busy bit andGOTO :Loop ;wait if high. (Busy=1)BCF LCDE ;Disable LCDBSF RP0 ;Select memory page 1MOVLW 0Fh ;Set upper 4 bits of Port B back toANDWF TRISB ;output by ANDingBCF RP0 ;Back to memory page 0BCF LCDRW ;Back to LCD write modeRETURN ;LCD is now free

LCD_Enable ;Sends a 500 ns enable pulse to the LCD to complete the;register or character write operation. The NOP instruction;is only required for processors faster than 8 MHz. For;processors faster than 16 MHz, add a second NOP.

BSF LCDE ;Set enable lineNOP ;and pause for an extra 250nsBCF LCDE ;Reset the enable lineRETURN ;Done!

LCD4BIT.LIB - 4-bit Interface LCD Subroutine Library

Page 298: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code28

;LCD71.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for PIC16C711 LCD operation including:; - Port Configuration; - Register mode commands; - LCD Busy check; - LCD Enable toggle

;Variables

; None

;Requirements

; Two free levels of processor stack are required for nested calls.

; The LCD_Init subroutine requires a minimum 5ms delay to initialize; the LCD. Delays longer than 5ms are acceptable. LCD_Init calls a; subroutine by the name of Delay_5ms which must be included in your; calling program. If your calling program contains a delay loop of; longer than 5ms, you can use that delay by adding a Delay_5ms; label before the routine.

;Use

; To initialize the LCD display after power-up:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Call LCD_Init to initialize the LCD controller

; To write a command or character to the LCD display:; 1. Call LCD_Port to initialize Port A and Port B for the LCD display; 2. Move an LCD command or ASCII character into W; 3. Call LCD_Reg or LCD_Data to send the command or; character to the LCD.

;LCD Hardware Equates

LCDRS EQU PORTA.0 ;LCD Register SelectLCDRW EQU PORTA.1 ;LCD Read/~WriteLCDE EQU PORTA.2 ;LCD Enable

;LCD Software Commands (Constants)

LCDLine1 EQU 80h ;Line 1 starting addressLCDLine2 EQU 0C0h ;Line 2 starting addressLCDCLR EQU 01h ;Clear Display, cursor homeLCDHome EQU 02h ;Cursor home, DDRAM unchangedLCDInc EQU 06h ;Cursor increment modeLCDDec EQU 04h ;Cursor decrement modeLCDOn EQU 0Ch ;Display OnLCDOff EQU 08h ;Display Off

LCD71.LIB - PIC16C71/711 LCD Subroutine Library

Page 299: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 29Program Pull-Out

References

CursOn EQU 0Eh ;Display On and Cursor OnCursOff EQU 0Ch ;Display On and Cursor OffCursBlink EQU 0Fh ;Display On and Cursor BlinkingLCDLeft EQU 18h ;Shift Display LeftLCDRight EQU 1Ch ;Shift Display RightCursLeft EQU 10h ;Move Cursor LeftCursRight EQU 14h ;Move Cursor RightLCDFunction EQU 38h ;8-bit function register init. commandLCDInit EQU 38h ;LCD initialization commandLCDCGRAM EQU 40h ;CGRAM starting address

LCD_Port ;Initializes the Port B tristate buffers as outputs for;LCD data lines. Sets Port A to digital (on PIC16C711) and;sets the LCD Register Select, Read/~Write, and Enable;lines to outputs.

BSF RP0 ;Select memory register page 1

;the next two lines are for the PIC16C711 only and should be;removed for the PIC16F84 (PM produces an error when this;is assembled for the �84).

MOVLW 03h ;1�s set Port A to digitalMOVWF ADCON1 ;Write W to ADCON1 (88h)

MOVLW 11111000b ;Set lower 3 bits of RA toANDWF TRISA ;digital output in TRISACLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0BCF LCDE ;Keep LCD Enable line offRETURN ;Ports are now set up for LCD

LCD_Init ;LCD initialization instructions from the Optrex data book.;Sets LCD functions for DMC16207 display, performs soft-;ware reset, clears memory and turns the display on.

MOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCDCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDInit ;Load W with initialize LCD codeCALL LCD_Reg_Init ;and send it to LCD againCALL Delay_5ms ;...and waitMOVLW LCDFunction ;Load W with initialize 8-bit codeCALL LCD_Reg ;and send it to LCDCALL Delay_5ms ;...and wait

;Change the constant in the next line to set how the display;is activated. eg. LCDOn, CursOn, CursBlink. The Constant is;from the LCD software commands, above.

MOVLW LCDOn ;Command for display on & cursor off

CALL LCD_Reg ;Send it to LCDMOVLW LCDCLR ;Load W with clear LCD codeCALL LCD_Reg ;and send it to LCDMOVLW LCDInc ;Load W with increment mode codeCALL LCD_Reg ;and send it to LCDRETURN

LCD_Reg_Init ;Used only for initialization prior to setting function;register. In this time, the LCD busy flag cannot be checked.

LCD71.LIB - PIC16C71/711 LCD Subroutine Library

Page 300: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code30

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD reg. on Port BGOTO LCD_Enable ;Send register command

LCD_Reg ;Load W with LCD software constant from table, above.;LCD_Reg outputs the command to the LCD and blips the;enable line with LCD_Enable to complete the command.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD reg. on Port BCALL LCD_Check ;Check LCD busy flagGOTO LCD_Enable ;Send register command

LCD_Data ;Load W with the ASCII character code to send to LCD.;LCD_Data outputs the character to the LCD and blips;the enable line with LCD_Enable to complete the send.

BCF LCDRS ;Enter register modeMOVWF PORTB ;and send W to LCD on Port BCALL LCD_Check ;Check LCD busy flagBSF LCDRS ;Enter ASCII modeGOTO LCD_Enable ;Send ASCII character

LCD_Check ;Checks the state of the LCD Busy flag and waits for any;previous command to finish before returning to the;calling routine.

BSF LCDRW ;Set LCD read modeBSF RP0 ;Select memory page 1MOVLW 0FFh ;Set Port B to input andMOVWF TRISB ;disable tristate buffersBCF RP0 ;Back to memory page 0BSF LCDE ;Enable LCDNOP ;and wait for an extra cycle

:Loop BTFSC PORTB.7 ;Check LCD busy bit andGOTO :Loop ;wait if high. (Busy=1)BCF LCDE ;Disable LCDBSF RP0 ;Select memory page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Back to memory page 0BCF LCDRW ;Back to LCD write modeRETURN ;LCD is now free

LCD_Enable ;Sends a 500 ns enable pulse to the LCD to complete the;register or character write operation. The NOP instruction;is only required for processors faster than 8 MHz. For;processors faster than 16 MHz, add a second NOP.

BSF LCDE ;Set enable lineNOP ;and pause for an extra 250nsBCF LCDE ;Reset the enable lineRETURN ;Done!

LCD71.LIB - PIC16C71/711 LCD Subroutine Library

Page 301: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 31Program Pull-Out

References

;RS232RX.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for the PIC-MDS to receive RS-232; characters through the serial header (H3), including:; - variable Baud rates and data bits; - receive bit setup; - wait for a serial start bit; - receive a serial character

;Variables

; Each of the variables below must be equated to a file register by; the calling program:;; Counter - Used by bit time delay loop; BitCounter - Counts number of received bits; Receive - Stores the received serial byte

;Requirements

; Two free levels of processor stack for nested subroutine calls;; An external RS-232 serial terminal or a computer with an appropriate; connection to the PIC-MDS serial input header (H3). For testing we; used a cable wired as follows and communicated with the MS Windows; Terminal program in Windows for Work Groups 3.11:;; Computer DB-25 PIC-MDS; Transmit pin 2 �> H3.3 - Rx; Receive pin 3 �> H3.1 - Tx; Ground pin 7 �> H3.2 - Gnd

;Use

; To receive serial characters:; 1. Call Receive_Port to initialize PortA.4 as an input; 2. Call Receive_Wait to wait for and receive one serial byte; 3. (Optional) Check the Receive register for 00h indicating a; serial framing error has occurred.

; Since PortA.4 is the serial input and the input for TMR0, this; serial library can be interrupt enabled. To receive via TMR0; interrupts, do the following:; 1. Enable TMR0 interrupt (see Chapter 11), with external input,; no prescaler, and falling-edge trigger; 2. Pre-load TMR0 with FFh. The next falling edge on PortA.4; increments TMR0 to 00h generating an interrupt.; 3. Enable GIE (Global Interrupt Enable); 4. When a TMR0 interrupt is generated, have your ISR Call; Receive_Data to receive the character. Depending on the Baud

RS232RX.LIB - RS-232 Receive Subroutine Library

Page 302: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code32

; rate and the number of cycles of your ISR, you may have to; adjust the value of Half_Bit. Reduce Half_Bit by one for every; four cycles of code taken by your ISR.

;RS232RX.LIB Hardware Equates for PIC-MDS

Serial_Input EQU PORTA.4 ;Serial input pin on PIC-MDS

;Software Equates

; DataBits and Bit_Time may be commented out to allow the calling; program to select equates governing the number of data bits as; well as the received baud rate. Or, change DataBits and Bit_Time; below to your defaults.

DataBits EQU 08h ;8 data bits

;Set Bit_Time, below, with a value from the table corresponding to your;PIC�s clock speed and the serial Baud rate required. To ensure accurate;serial bit timing, use a crystal oscillator and not a ceramic resonator;or RC combination to generate the processor clock.

;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;|Clk\ Bd| 300 | 600 | 1200| 2400| 4800| 9600|14400|19200|28800|38400|57600|;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;| 1 MHz | 0CEh| 65h | 31h | 17h | 0Ah | 04h*| --- | --- | --- | --- | --- |;| 2 MHz | --- | 0CEh| 65h | 31h | 17h | 0Ah | 06h | 04h*| --- | --- | --- |;| 4 MHz | --- | --- | 0CEh| 65h | 31h | 17h | 0Fh | 0Ah | 06h | 04h*| --- |;| 8 MHz | --- | --- | --- | 0CEh| 65h | 31h | 20h | 17h | 0Fh | 0Ah | 06h |;| 10 MHz| --- | --- | --- | FFh*| 7Fh | 3Eh | 29h | 1Eh | 13h | 0Eh | 08h |;| 16 MHz| --- | --- | --- | --- | 0CEh| 65h | 43h | 31h | 20h | 17h | 0Fh |;| 20 MHz| --- | --- | --- | --- | FFh*| 7Fh | 54h | 3Eh | 29h | 1Eh | 13h |;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;*Timing inaccuracies using these delay constants may cause serial errors.

Bit_Time EQU 3Eh ;Serial Bit delay from table aboveHalf_Bit EQU Bit_Time/2 ;Half of the Bit delay

Receive_Port ;Sets PORTA.4 to input. Make sure PIC-MDS JU5 is set to Rx!

BSF RP0 ;Select memory register page 1MOVLW 00010000b ;Load W with bit to make RA.4 inputIORWF TRISA ;and OR with Port A tristate reg.BCF RP0 ;Return to memory register page 0RETURN

Receive_Wait ;Waits for an RS-232 start bit indicated by RA.4 going low.

BTFSC Serial_Input ;Check serial input pinGOTO Receive_Wait ;If high, wait for low

Receive_Data ;Delay for half the Bit_Time and confirm the presence of the;start bit. Then wait for Bit_Time and read each bit into;Carry. Rotate Carry into the Receive byte and repeat the;delay, Carry and rotate until number of DataBits have been;received. The Receive register stores the received byte. If;framing error occurs (only a simple check for a stop bit is;done) the contents of the Receive register will be 00h.

MOVLW DataBits ;Load W with number of data bitsMOVWF BitCounter ;and save in BitCounter registerMOVLW Half_Bit ;Load W with half of bit delay timeCALL BitDelay ;and wait for 1/2 bitBTFSC Serial_Input ;Check for low start bit again

RS232RX.LIB - RS-232 Receive Subroutine Library

Page 303: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 33Program Pull-Out

References

GOTO Receive_Data ;If high, error occurred-keep waiting

:Next_Bit MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until middle of next bitBTFSS Serial_Input ;Check serial input pin for 1BCF C ;If serial input is 0, clear CarryBTFSC Serial_Input ;Check serial input pin for 0BSF C ;If serial input is 1, set CarryRRF Receive ;Rotate Carry into received data byteDECFSZ BitCounter ;Decrement bit counter & check for 0GOTO :Next_Bit ;If not 0, get the next bit

MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until middle of stop bitBTFSS Serial_Input ;Check for high stop bitGOTO Receive_Error ;If low, we have a framing errorRETURN ;Otherwise, return

Receive_Error ;Simply clears Receive buffer if no stop bit is found.

CLRF Receive ;If a framing error occurs, clearRETURN ;Receive register before returning

BitDelay ;RS-232 Bit time period delay

MOVWF Counter ;Move delay time in W to Counter:Loop NOP ;Pad loop to 4 cycles

DECFSZ Counter,1 ;Decrement bit counterGOTO :Loop ;and do it until zeroRETURN

RS232RX.LIB - RS-232 Receive Subroutine Library

Page 304: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code34

;RS232TX.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems byphone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising outof;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls for the PIC-MDS to transmit RS-232; characters through the serial header (H3), including:; - variable Baud rates and data bits; - selectable transmit pin; - transmit a serial character

;Variables

; Each of the variables below must be equated to a file register by; the calling program:;; Counter - Used by bit time delay loop; BitCounter - Counts number of transmitted bits; Transmit - Stores the serial byte to be transmitted

;Requirements

; Two free levels of processor stack for nested subroutine calls;; An external RS-232 serial terminal or a computer with an appropriate; connection to the PIC-MDS serial input header (H3). For testing we; used a cable wired as follows and communicated with the MS Windows; Terminal program in Windows for Work Groups 3.11:;; Computer DB-25 PIC-MDS; Transmit pin 2 �> H3.3 - Rx; Receive pin 3 �> H3.1 - Tx; Ground pin 7 �> H3.2 - Gnd

;Use

; To transmit serial characters:; 1. Call Transmit_Port to initialize PortA.4 as an output; 2. Move the data byte to be sent to the Transmit register; 3. Call Transmit_Data to send the serial byte

;RS232RX.LIB Hardware Equates for PIC-MDS

Serial_Output EQU PORTA.4 ;Serial input pin on PIC-MDS

;Software Equates

; DataBits and Bit_Time may be commented out to allow the calling; program to select equates governing the number of data bits as; well as the transmit baud rate. Or, change DataBits and Bit_Time

RS232TX.LIB - RS-232 Transmit Subroutine Library

Page 305: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 35Program Pull-Out

References

; below to your defaults.

DataBits EQU 08h ;8 data bits

;Set Bit_Time, below, with a value from the table corresponding to your;PIC�s clock speed and the serial Baud rate required. To ensure accurate;serial bit timing, use a crystal oscillator and not a ceramic resonator;or RC combination to generate the processor clock.

;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;|Clk\ Bd| 300 | 600 | 1200| 2400| 4800| 9600|14400|19200|28800|38400|57600|;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;| 1 MHz | 0CEh| 65h | 31h | 17h | 0Ah | 04h*| --- | --- | --- | --- | --- |;| 2 MHz | --- | 0CEh| 65h | 31h | 17h | 0Ah | 06h | 04h*| --- | --- | --- |;| 4 MHz | --- | --- | 0CEh| 65h | 31h | 17h | 0Fh | 0Ah | 06h | 04h*| --- |;| 8 MHz | --- | --- | --- | 0CEh| 65h | 31h | 20h | 17h | 0Fh | 0Ah | 06h |;| 10 MHz| --- | --- | --- | FFh*| 7Fh | 3Eh | 29h | 1Eh | 13h | 0Eh | 08h |;| 16 MHz| --- | --- | --- | --- | 0CEh| 65h | 43h | 31h | 20h | 17h | 0Fh |;| 20 MHz| --- | --- | --- | --- | FFh*| 7Fh | 54h | 3Eh | 29h | 1Eh | 13h |;+-------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+;*Timing inaccuracies using these delay constants may cause serial errors.

Bit_Time EQU 03Eh ;Serial Bit delay from table aboveHalf_Bit EQU Bit_Time/2 ;Half of the Bit delay

Transmit_Port ;Sets PORTA.4 to output. Make sure PIC-MDS JU5 is set to Tx!

BSF RP0 ;Select memory register page 1MOVLW 00001111b ;Load W with bit to make RA.4 outputANDWF TRISA ;and OR with Port A tristate reg.BCF RP0 ;Return to memory register page 0BSF Serial_Output ;Set serial line highRETURN

Transmit_Data ;Drop PortA.4 from high to low to indicate the Start Bit and;delay for one Bit_Time. Rotate the Transmit buffer right;into Carry and set or clear the serial output pin based on;Carry. Wait for another bit time and continue rotating and;transmitting until all eight bits have been sent. Finally,;send a stop bit.

MOVWF Transmit ;Save character in W to bufferMOVLW DataBits ;Load W with number of data bitsMOVWF BitCounter ;and save in BitCounter registerBCF Serial_Output ;Send Start bitNOP ;and pad routine to be same lengthNOP ;as :Next_Bit code so Bit_Time isNOP ;accurateNOPNOPNOPNOP

:Next_Bit MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait one bit durationRRF Transmit ;Rotate Transmit byte into CBTFSS C ;Check Carry for a 1BCF Serial_Output ;If C=0, clear serial outputBTFSC C ;Check Carry for a 0BSF Serial_Output ;If C=1, set serial outputDECFSZ BitCounter ;Decrement bit counter & check for 0GOTO :Next_Bit ;If not 0, get the next bit

MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait until end of last bitBSF Serial_Output ;Set serial line high for Stop bit

RS232TX.LIB - RS-232 Transmit Subroutine Library

Page 306: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code36

MOVLW Bit_Time ;Load W with bit delay timeCALL BitDelay ;and wait a bitRETURN

BitDelay ;RS-232 Bit time period delay

MOVWF Counter ;Move delay time in W to Counter:Loop NOP ;Pad loop to 4 cycles

DECFSZ Counter,1 ;Decrement bit counterGOTO :Loop ;and do it until zeroRETURN

RS232TX.LIB - RS-232 Transmit Subroutine Library

Page 307: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 37Program Pull-Out

References

;SEEPROM.LIB v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This subroutine provides calls to access the 93LC56 or 93LC66 Serial; EEPROM (SEEPROM) for long-term data or variable storage. Serial EEPROMs; are non-volatile and maintain their data even while power is off. The; SEEPROM connects to the PIC microcontroller using three wires: Chip; Select (SEECS), Clock (SEECLK) and Data In/Data Out (SEEDIDO).

; To write a byte to the SEEPROM, the PIC must serially transmit a start; bit, a command op-code, a storage address, and data on SEEDIDO while; toggling SEECLK. To read data back from the SEEPROM, the PIC clocks out; the start bit, the command op-code, the storage address, and then keeps; toggling SEECLK while reading the data on SEEDIDO.

; A full frame of serial data is shown below. Full frames are used by the; Read, Write and Write All commands. The other four commands, Erase,; Erase All, Erase-Write Enable, and Erase-Write Disable use a partial; data frame and omit the data bits.

; +--+---+---+----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+; |SB|OP1|OP0|X/A8|A7|A6|A5|A4|A3|A2|A1|A0|D7|D6|D5|D4|D3|D2|D1|D0|; +--+---+---+----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+; |<- partial frame for non-data instr. ->|; |<- full frame for data instruction ->|

; SB=Start bit, OPn=Op-code bit, An=Address bit, Dn=Data bit, X=don�t care

; The presence of the A8 bit allows addressing of up to 512 bytes. Because; the size of the data frame is constant, addressing a 256 byte SEEPROM; requires a don�t care bit (X) to be transmitted in place of A8.

; +-------+---------------+----+-------------------+; |SEEPROM| Size X Org. | A8 | A7-A0 |; +-------+---------------+----+-------------------+; |93LC56 | 256 X 8-bit | X | Valid Address |; +-------+---------------+----+-------------------+; |93LC66 | 512 X 8-bit | Valid Address |; +-------+---------------+----+-------------------+

; These subroutines support the 93LC56 (256 byte) and 93LC66 (512 byte); SEEPROMs, in 8-bit data mode (X8 organization) only, and include; subroutines for:; - Port configuration; - SEEPROM erase or write enable and disable; - SEEPROM data write to a specific SEEPROM address; - SEEPROM data read from a specific SEEPROM address; - SEEPROM global write and erase; - Wait for SEEPROM Erase/Write completion

; 16-bit data mode (X16 organization) is not supported. For 16-bit; mode, modify the SEE_Clk subroutine according to the Microchip Data; book for the 93LC46/56/66 series of serial SEEPROMs.

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 308: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code38

;Variables

; The following variables must be defined by the calling program:

; SEEClock - SEEPROM serial clock counter register; SEEData - Data byte storage register; SEEAddrh - SEEPROM high address register; SEEAddrl - SEEPROM low address register

;Requirements

; These routines require two levels of processor stack as well as the; variables defined above.

;Use

; To set up Port A for Serial EEPROM use:; 1. Call SEE_Port

; To read data from or to write data or a command to the Serial EEPROM:; 1. Load low address byte into SEEAddrl or clear SEEAddrl; 2. Load high address byte into SEEAddrh or clear SEEAddrh; 3. For a data write operation, load data byte into SEEData; 4. Move the SEEPROM Command Op-code into W using a MOVLW instruction; 5. CALL SEE_Command; 6. For a data read operation, retrieve the data byte from SEEData

; To wait for the completion of a write operation:; 1. CALL SEE_Wait. A RETURN is issued when the SEEPROM operations are; complete. Typical ERASE and WRITE operations take 4 ms to complete,; ERAL takes 8 ms, and WRAL takes 16 ms.

;SEEPROM Commands

; Below is a list of the SEEPROM Command Op-codes indicating which ones; require a valid address and the direction of data transfer:

; Op XOP Address Bits; Code Code Instruction Description X/A8 A7 A6-A0 Data Bits; ---------------------------------------------------------------------; 00 00 EWDS -Erase/Write Disable XOP XOP X -; 00 01 WRAL -Write All XOP XOP X to SEEPROM; 00 10 ERAL -Erase All XOP XOP X -; 00 11 EWEN -Erase/Write Enable XOP XOP X -; 01 WRITE -byte to address X/A8 A7 A6-A0 to SEEPROM; 10 READ -byte from address X/A8 A7 A6-A0 from SEEPROM; 11 ERASE -contents of address X/A8 A7 A6-A0 -

; Note that for all 00 Op-Codes, a two bit extended op-code (XOP) takes; the place of the A8 and A7 bits. The remaining address bits are don�t; care bits, but must be transmitted to complete the instruction.

;SEEPROM Hardware Equates

SEECLK EQU PORTA.0 ;SEEPROM Serial Clock pinSEEDIDO EQU PORTA.1 ;SEEPROM Data In and Data Out pinsSEECS EQU PORTA.3 ;SEEPROM Chip Select pin

;SEEPROM Software Commands (Constants)

SEERead EQU 0C0h ;Read data op-codeSEEEWEN EQU 9Ch ;Erase/Write Enable op-codeSEEErase EQU 0E0h ;Erase data op-codeSEEERAL EQU 94h ;Erase All op-code

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 309: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 39Program Pull-Out

References

SEEWrite EQU 0A0h ;Write data op-codeSEEWRAL EQU 8Ch ;Write All op-codeSEEEWDS EQU 84h ;Erase/Write Disable op-code

SEE_Port ;Configures Port A to digital (on PIC16C71), sets the SEEPROM ;Chip Select and Serial Clock lines to output, and sets the ;Data line to input. Chip Select is left de-activated.

MOVLW 14h ;Make sure SEECS, SEECLK and SEEDIDO ANDWF PORTA ;pins are 0 before making them outputs BSF RP0 ;Select memory page 1

;Remove comments from the following two lines if your program ;uses the PIC16C71 with the A/D converter enabled. ;MOVLW 03h ;1�s set Port A to digital, ;MOVWF ADCON1 ;write to ADCON1 (88h)

MOVLW 14h ;Set SEECS, SEECLK & SEEDIDO pins of ANDWF TRISA ;Port A to digital output BCF RP0 ;Select memory page 0 RETURN

SEE_Command ;This subroutine parses the SEEPROM command op-code, completes ;op-code formatting and calls the appropriate routine to clock

;the op-code, address, and data (if necessary) to the SEEPROM.

;The op-code command is stored in the upper 4-6 bits of SEEAddrh ;according to the diagram shown below. For non-extended op-

;codes, SEEAddrh stores the Start-Bit, two Op-code bits and A8. ;The top four bits of SEEAddrh and the contents of SEEAddrl are ;later shifted out to the SEEPROM by the SEE_Clk subroutine, ;which transmits these as a partial serial data frame.

; SEEAddrh SEEAddrl ;+--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ ;|SB|OP|OP|A8| | | | | |A7|A6|A5|A4|A3|A2|A1|A0| ;+--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+

;For extended op-codes, SEEAddrh stores the Start-Bit, four Op- ;code bits (two op-code bits, plus two extended op-code bits) ;and a flag bit (7B) indicating that only 7 dummy address bits ;need to be sent. In this case, SEE_Clk transmits the upper five ;bits of SEEAddrh and the lower seven bits of SEEAddrl.

; SEEAddrh SEEAddrl ;+--+--+--+---+---+--+--+--+ +--+--+--+--+--+--+--+--+ ;|SB|OP|OP|XOP|XOP|7B| | | |A7|A6|A5|A4|A3|A2|A1|A0| ;+--+--+--+---+---+--+--+--+ +--+--+--+--+--+--+--+--+

IORWF SEEAddrh ;Store command to top bits of SEEAddrh BTFSS SEEAddrh.6 ;Check bit 6 for a 1 GOTO :Check_5 ;If 0, find command by checking bit 5 CALL SEE_SetA8 ;Set A8 and counter for SEEAddrh BTFSS SEEAddrh.5 ;Check bit 5 for a 1 GOTO SEE_Read ;If 0, goto SEEPROM Read routine CALL SEE_Clk ;Do clocking for ERASE instruction GOTO SEE_Done ;and clean up before Returning

:Check_5 MOVLW 05h ;Load W with 5 to shift 5 top bits of MOVWF SEEClock ;SEEAddrh during clocking BTFSS SEEAddrh.5 ;Check bit 5 for 1 GOTO :Check_4 ;If bit 5=0, check bit 4 CALL SEE_SetA8 ;Otherwise, set counter and A8 for GOTO SEE_Write ;SEEPROM WRITE instruction

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 310: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code40

:Check_4 BTFSS SEEAddrh.4 ;If 0, check bit 4 for a 1 GOTO :Check_3 ;If bit4=0, check bit 3 CALL SEE_Clk ;If bit4=1, send EWEN or ERAL commands GOTO SEE_Done ;and clean up before Returning

:Check_3 BTFSC SEEAddrh.3 ;Check bit3 for a 0 GOTO SEE_Write ;If bit3=1, WRAL using SEEPROM Write CALL SEE_Clk ;otherwise, send EWDS command and GOTO SEE_Done ;clean up before Returning

SEE_SetA8 ;Moves A8 bit from bit position 0 of SEEAddrh to bit 4 and ;sets SEEClock to 4 to clock out top 4 bits of SEEAddrh only:

; SEEAddrh ; +--+--+--+--+--+--+--+--+ ; |SB|OP|OP|A8| | | |A8| <-original A8 gets moved to bit 4 ; +--+--+--+--+--+--+--+--+

MOVLW 04h ;Load W with 4 to shift only top 4 MOVWF SEEClock ;bits of SEEAddrh during clocking BTFSS SEEAddrh.0 ;Check A8 bit for a 1 RETURN ;If A8=0, Return BSF SEEAddrh.4 ;otherwise, move A8 bit from 0 to 4 RETURN

SEE_Read ;Reads the byte from the specified address location of the ;SEEPROM into the SEEData register.

CALL SEE_Clk ;Clock op-code and address to SEEPROM

BSF RP0 ;Select memory register page 1 MOVLW 00000010b ;and load W with 00000010b to IORWF TRISA ;set SEEDIDO line to input BCF RP0 ;Return to register page 0 MOVLW 08h ;Load the clock counter with 8 MOVWF SEEClock ;to clock data out of SEEPROM CLRF SEEData ;Clear Data receive byte before read

:ClkData BSF SEECLK ;Set serial clock to read bits NOP ;and wait for data output to settle BTFSS SEEDIDO ;Check SEEPROM Data Out for a 1 BCF C ;If DO=0, clear Carry BTFSC SEEDIDO ;Check SEEPROM Data Out for a 0 BSF C ;If DO=1, set Carry BCF SEECLK ;Clear SEECLK line RLF SEEData ;Shift Carry into SEEData register DECFSZ SEEClock ;Decrement clock counter to clock in GOTO :ClkData ;all 8 bits of SEEData

BCF SEECS ;Disable SEEPROM Chip Select

GOTO SEE_Port ;Return after re-enabling outputs

SEE_Write ;Stores the byte in SEEData to the address in the SEEPROM ;specified by SEEAddrh and SEEAddrl.

CALL SEE_Clk ;Clock Op-code and address to SEEPROM

MOVLW 08h ;Load the clock counter with 8 to MOVWF SEEClock ;clock out 8 data bits from SEEData

:ClkData BCF SEECLK ;Clear serial clock between bits RLF SEEData ;Rotate high bit of SEEData into C BTFSS C ;Check Carry for a 1 BCF SEEDIDO ;If C=0, clear SEEPROM Data line

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 311: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 41Program Pull-Out

References

BTFSC C ;Check Carry for a 0 BSF SEEDIDO ;If C=1, set SEEPROM Data line NOP ;and wait for it to settle BSF SEECLK ;Clock bit in by setting SEECLK DECFSZ SEEClock ;Decrement clock counter to clock out GOTO :ClkData ;all 8 bits of SEEData

BCF SEECLK ;Clear SEEPROM Serial Clock and GOTO SEE_Done ;clean up before Returning

SEE_Clk ;This subroutine writes the Start bit, Op-code and Address to ;the SEEPROM by serially shifting SEEAddrh and SEEAddrl into ;the SEEPROM. The calling routine determines how many bits ;of SEEAddrh are transmitted.

BCF SEECLK ;Ensure SEEPROM serial clock is clear BSF SEECS ;before enabling SEEPROM Chip Select

:ClkAddrh BCF SEECLK ;Clear serial clock between bits RLF SEEAddrh ;Rotate high bit of SEEAddrh into C BTFSS C ;Check Carry for a 1 BCF SEEDIDO ;If C=0, clear SEEPROM Data line BTFSC C ;Check Carry for a 0 BSF SEEDIDO ;If C=1, set SEEPROM Data line NOP ;and wait for it to settle BSF SEECLK ;Clock bit in by setting SEECLK DECFSZ SEEClock ;Decrement clock counter to clock out GOTO :ClkAddrh ;the top 4 bits of the instruction

MOVLW 08h ;If SEEClock was 0, reload the clock MOVWF SEEClock ;counter with 8 for SEEAddrl RLF SEEAddrh ;Rotate SEEAddrh once more to check BTFSC C ;C for the 7-bit dummy address flag DECF SEEClock ;If 7B flag set, decrement bit counter

:ClkAddrl BCF SEECLK ;Clear serial clock between bits RLF SEEAddrl ;Rotate high bit of SEEAddrl into C BTFSS C ;Check Carry for a 1 BCF SEEDIDO ;If C=0, clear SEEPROM Data line BTFSC C ;Check Carry for a 0 BSF SEEDIDO ;If C=1, set SEEPROM Data line NOP ;and wait for it to settle BSF SEECLK ;Clock bit in by setting SEECLK DECFSZ SEEClock ;Decrement clock counter to clock out GOTO :ClkAddrl ;all 8 bits of SEEAddrl

BCF SEECLK ;Clear SEEPROM serial clock to finish RETURN

SEE_Done ;It is important that the upper bits of SEEAddrh are cleared ;before initiating a new SEEPROM command. To save a calling ;program from clearing SEEAddrh between successive commands, ;SEEAddrh and SEEAddrl are automatically cleared after de- ;selecting the SEEPROM.

BCF SEECS ;Clear Chip Select to end command

CLRF SEEAddrh ;Clear contents of SEEAddrh and CLRF SEEAddrl ;SEEAddrl after use and RETURN ;Return to the calling program

SEE_Wait ;Waits until the SEEPROM RDY/BSY flag is set, indicating ;the SEEPROM Erase or Write operation has finished.

BSF SEECS ;Set SEEPROM Chip Select and

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 312: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code42

NOP ;Wait for set-up time:Wait BTFSS SEEDIDO ;Check for 1 on DI/DO pin GOTO :Wait ;If 0, SEEPROM is still busy RETURN

SEEPROM.LIB - Serial EEPROM Subroutine Library

Page 313: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 43Program Pull-Out

References

;ALARM.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates port input. It initializes port B bit 0; as an input and port B bit 1 as an output. When the user; disconnects bit 0 from ground, the LED connected to bit 1; illuminates. Note that port B has built-in pull-up resistors; and therefore requires no external pull-ups.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; Attach a small piece of wire to the third screw terminal (CON1-3).; Connect this wire to the ninth screw terminal (CON1-9).; When this wire is disconnected the LED on Port B bit 1 (RB1); will light. The LED on RB0 displays the state of the input.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �ALRM�

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 00000001b ;Load W with desired I/O patternMOVWF TRISB ;Move W to TRISB to make bit 0 input

;(1=input, 0=output)BCF RBPU ;Enable Port B pull-up resistors

;(OPTION.7 on register page 1)BCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDs

Main BTFSC PORTB.0 ;Check Port B bit 0 for a lowGOTO LED_On ;If we�re here, bit 0 is highBCF PORTB.1 ;If bit 0 is low, turn off LEDGOTO Main ;Check bit 0 again

ALARM.ASM - Chapter 9 Example Program

Page 314: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code44

LED_On BSF PORTB.1 ;Turn on LED on bit 1GOTO Main ;Check bit 0 again

ALARM.ASM - Chapter 9 Example Program

Page 315: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 45Program Pull-Out

References

;ASCII.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

;; This program illustrates how to use the LCD.LIB, KEYPAD.LIB and; DEC2BIN.LIB subroutine libraries. A user enters three key strokes; representing a binary number (from 000 to 255, but no error checking; is done). The key strokes are displayed as well as the equivalent; ASCII character generated by the LCD.;; Use this program to determine LCD character codes for programs.;; The keypad is remapped after being called by KB_Scan to return; the following numbers. Key remapping as well as displaying a; message on the LCD demonstrate ROM data table reads.;; Old key from KB_Scan gets remapped to new key values:; +----+----+----+----+ +----+----+----+----+; | 1 | 2 | 3 | 4 | | 1 | 2 | 3 | 0 |; +----+----+----+----+ +----+----+----+----+; | 5 | 6 | 7 | 8 | | 4 | 5 | 6 | 0 |; +----+----+----+----+ +----+----+----+----+; | 9 | 10 | 11 | 12 | | 7 | 8 | 9 | 0 |; +----+----+----+----+ +----+----+----+----+; | 13 | 14 | 15 | 16 | | 0 | 0 | 0 | 0 |; +----+----+----+----+ +----+----+----+----+;

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �ASCI�

ASCII.ASM - Chapter 12 Example Program

Page 316: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code46

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Other equatesCounter DS 1 ;LCD character counter

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

Key DS 1 ;Key return code variable

Digit DS 1 ;ASCII digit counter variable

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key return variableCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �DEC2BIN.LIB� ;Decimal to Binary conversion routineInclude �KEYPAD.LIB� ;Keypad scanning subroutine libraryInclude �LCD.LIB� ;LCD subroutine library

Initialize ;This subroutine initializes the LCD display and writes;a message on to line 1 and �=� on to line 2. The cursor;is turned on to indicate where input will be shown.

CLRF Digit ;Clear digit counterCALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Init ;Send first line

Send_Equals MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 0Ah ;and offset cursor to position 11CALL LCD_REG ;Send cursor position to LCDMOVLW �=� ;Load W with ASCII �=�CALL LCD_Data ;and send to LCD for display

Set_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 06h ;and offset cursor to position 7CALL LCD_REG ;Send cursor position to LCD

Cursor_On MOVLW CursOn ;Load W with cursor on command (0Eh)CALL LCD_REG ;and send to LCD

CALL KB_Port ;Configures Port B for keypad

Main ;Main waits for a valid key press. When a valid key returns,;the keypad is scanned again after a debounce delay. The Key;value is remapped to the keypad numbers shown in the;description, above. Key values are successively stored in;the Hundreds, Tens and Ones registers and displayed on line;two of the LCD. When three keys have been entered, the key;codes are converted to binary and displayed on the LCD as;the character code for that key combination.

Get_Key CALL KB_Scan ;Get Key return code

ASCII.ASM - Chapter 12 Example Program

Page 317: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 47Program Pull-Out

References

MOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try again

CALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

CALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Key_Remap ;and Remap key codesMOVWF Key ;Save new Key code to key

MOVF Digit,0 ;Get digit count in WADDWF PCL ;and offset PC with digitGOTO Digit1 ;First time through, write HundredsGOTO Digit2 ;next, to TensGOTO Digit3 ;then, Ones

Digit1 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Hundreds ;and store in Hundreds variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCDINCF Digit ;Add one to digit counterGOTO Release ;Wait for user to release key

Digit2 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Tens ;and store in Tens variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCDINCF Digit ;Add one to digit counterGOTO Release ;Wait for user to release key

Digit3 CALL LCD_Port ;Configure Ports for LCDMOVF Key,0 ;Get Key return codeMOVWF Ones ;and store in Ones variableADDLW 30h ;Convert Key to ASCIICALL LCD_Data ;and display on LCD

Move_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 0Ch ;and offset cursor to position 13CALL LCD_REG ;Send cursor position to LCD

CALL Dec_Bin ;Converts Hundreds, Tens Ones to binaryCALL LCD_Data ;and display on LCD

CLRF Digit ;Reset digit counter

Reset_Cursor MOVLW LCDLine2 ;Load W with address of line 2 (C0h)ADDLW 06h ;and offset cursor to position 7CALL LCD_REG ;Send cursor position to LCD

Release ;This is the opposite of the first key check. It waits for;the Key code to be zero and pauses for the debounce delay.

CALL KB_Port ;Set Port B for keypad useWait CALL KB_Scan ;Scan keypad

MOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has been releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5msGOTO Main ;Get next digit

ASCII.ASM - Chapter 12 Example Program

Page 318: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code48

Disp_Init ;Writes �ASCII Code Char.� to the first line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counterGet_Char MOVF Counter,0 ;Get character offset into W

CALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for the next character

Message ADDWF PCL ;Offset program counter by adding WRETLW �A� ;MessageRETLW �S�RETLW �C�RETLW �I�RETLW �I�RETLW � �RETLW �C�RETLW �o�RETLW �d�RETLW �e�RETLW �=�RETLW �C�RETLW �h�RETLW �a�RETLW �r�RETLW �.�RETLW 0 ;End of message

Key_Remap ADDWF PCL ;Use old Key to offset PCNOP ;No Key=0 codeRETLW 1 ;old key code 1 remapped to new key 1RETLW 2 ;old key code 2 remapped to new key 2RETLW 3 ;old key code 3 remapped to new key 3RETLW 0 ;old key code 4 remapped to new key 0RETLW 4 ;old key code 5 remapped to new key 4RETLW 5 ;old key code 6 remapped to new key 5RETLW 6 ;old key code 7 remapped to new key 6RETLW 0 ;old key code 8 remapped to new key 0RETLW 7 ;old key code 9 remapped to new key 7RETLW 8 ;old key code 10 remapped to new key 8RETLW 9 ;old key code 11 remapped to new key 9RETLW 0 ;old key code 12 remapped to new key 0RETLW 0 ;old key code 13 remapped to new key 0RETLW 0 ;old key code 14 remapped to new key 0RETLW 0 ;old key code 15 remapped to new key 0RETLW 0 ;old key code 16 remapped to new key 0

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

ASCII.ASM - Chapter 12 Example Program

Page 319: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 49Program Pull-Out

References

;BLIP.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates looping for Chapter 8. It initializes all; port B pins to be outputs, keeps all LEDs lit for a short time, delays; for a longer time and then repeats.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This is a simple program that requires no prior setup.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �BLIP�

;Hardware Equates

Counter1 EQU 0Ch ;First delay counter registerCounter2 EQU 0Dh ;Second delay counter registerCounter3 EQU 0Eh ;Third delay counter register

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vectorORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Clear Port B registerCLRF Counter1 ;Clear Counter1 register (0Ch)CLRF Counter2 ;and Counter2 register (0Dh)

Main MOVLW 0FFh ;Load W with ones to turn on LEDsMOVWF PORTB ;and write to Port B registerMOVLW 03h ;Load W with 3MOVWF Counter2 ;and preset Counter2 before Loop_On

Loop_On DECFSZ Counter1 ;Decrement Counter1 and check for 0

BLIP.ASM - Chapter 8 Example Program

Page 320: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code50

GOTO Loop_On ;If not 0, decrement Counter1 againDECFSZ Counter2 ;If 0, decrement Counter2GOTO Loop_On ;If not 0, do Counter1 loop

CLRF PORTB ;Turn off LEDs by clearing Port BMOVLW 0Dh ;Load W with 13MOVWF Counter3 ;and preset Counter3 before Loop_Off

Loop_Off DECFSZ Counter1 ;Decrement Counter1 and check for 0GOTO Loop_Off ;If not 0, decrement Counter 1 againDECFSZ Counter2 ;If Counter1=0, decrement Counter2GOTO Loop_Off ;If not 0, do Counter1 loopDECFSZ Counter3 ;If Counter2=0, decrement Counter3GOTO Loop_Off ;If not 0, do Counter1 & 2 loopsGOTO Main ;If 0, go to Main

BLIP.ASM - Chapter 8 Example Program

Page 321: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 51Program Pull-Out

References

;BOUNCE.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates switch contact bounce. It initializes port A; bit 4 as an input and port B as output. When the user connects port A; bit 4 to ground, the LEDs display the number of contact bounces that; occur. The count accumulates until the RESET button is pressed.; Note that port A has no internal pull-up capability. However the; PIC-MDS has an external pull-up pre-wired to Port A bit 4 (RA4).

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; Attach a small piece of wire to the third screw terminal (CON1-3).; When this grounded wire is connected to the 8th screw terminal; (CON1-8) the LEDs on port B reflect the number of bounces.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �BOUN�

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 00010000b ;Load W with the desired I/O patternMOVWF TRISA ;Make Port A bit 4 input

;(1=input, 0=output)CLRF TRISB ;Make Port B outputBCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDs

Main BTFSC PORTA.4 ;Check Port A bit 4 for a lowGOTO Main ;If we�re here, bit 4 is highINCF PORTB ;If bit 4 is low, increment Port B

Wait_for_High BTFSS PORTA.4 ;Check Port A bit 4 for a high

BOUNCE.ASM - Chapter 9 Example Program

Page 322: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code52

GOTO Wait_for_High ;If we�re here, bit 4 is still lowGOTO Main ;Bit 4 went high, wait for next bounce

BOUNCE.ASM - Chapter 9 Example Program

Page 323: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 53Program Pull-Out

References

;CLOCK.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

;; This program demonstrates interrupt driven timing while running a; separate task. A TMR0 interrupt is generated 60 times per second; and is used to update the elapsed time on the LCD display. When not; updating the display, a single LED is scanned across Port B.

; Since PortB is used by both the ISR and the Main routine, the ISR; saves and restores all port registers.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; None

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �CLK �

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Equates required to keep time:Hours DS 1 ;Holds elapsed hoursMinutes DS 1 ;Holds elapsed minutesSeconds DS 1 ;Holds elapsed secondsSixtieth DS 1 ;Holds sixtieths of a second

;Other equatesCounter DS 1 ;LCD character counter

CLOCK.ASM - Chapter 11 Example Program

Page 324: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code54

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

Counter3 DS 1 ;general purpose delay counterCounter4 DS 1 ;general purpose delay counter

Temp_W DS 1 ;Temporary registersTemp_Status DS 1 ;used to save values during interruptTemp_TRISB DS 1 ;service routine (ISR) The ISRTemp_TRISA DS 1 ;will save their values on entryTemp_PortB DS 1 ;and restore them on exit.Temp_PortA DS 1

Key DS 1 ;Key return code variable

ORG 00h ;Start program at Reset Vector

CLRF Hours ;Set hours to 00CLRF Minutes ;Set minutes to 00CLRF Seconds ;Set seconds to 00GOTO Initialize ;Continue with initialize routine

ORG 04h ;Interrupt Service Routine (ISR);starts at Interrupt Vector

Check_T0IF ;When an interrupt occurs, Check_T0IF confirms it was;generated by a TMR0 overflow. If not, and other interrupts;are enabled, they must get serviced in the Other_Int;routine. When TMR0 overflows Sixtieth is decremented and;checked for equaling zero. If Zero then Seconds, Minutes;and Hours are updated and displayed. Otherwise, interrupts;are re-enabled and execution continues.

Save MOVWF Temp_W ;Save W in Temp_WSWAPF Status,0 ;Swap Status halves into WMOVWF Temp_Status ;and save Status in Temp_Status

MOVF PORTA,0 ;Load W with Port and TRIS contentsMOVWF Temp_PortA ;and save to temporary registersMOVF PORTB,0MOVWF Temp_PortBBSF RP0MOVF TRISA,0MOVWF Temp_TRISAMOVF TRISB,0MOVWF Temp_TRISBBCF RP0

ISR BTFSS T0IF ;Check for TMR0 interruptGOTO Other_Int ;If cleared, check other interrupts

DECFSZ Sixtieth ;Has 1 second elapsed?GOTO Exit ;If not, use Exit to leave ISRMOVLW 60 ;If zero, reset sixtieth counterMOVWF Sixtieth ;to 60INCF Seconds ;Update seconds andSUBWF Seconds,0 ;check for overflow (Seconds=60)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLRF Seconds ;If Z=1, Seconds is 60, reset to 0MOVLW 60 ;reload W with 60INCF Minutes ;Update Minutes andSUBWF Minutes,0 ;check for overflow (Minutes=60)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLOCK.ASM - Chapter 11 Example Program

Page 325: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 55Program Pull-Out

References

CLRF Minutes ;If Z=1, Minutes is 60, reset to 0MOVLW 24 ;Load W with 24INCF Hours ;Update Hours andSUBWF Hours,0 ;check for overflow (Hours=24)BTFSS Z ;by testing ZGOTO Update_Clock ;If Z=0, update clock with new time

CLRF Hours ;If Z=1, reset hours to 00

Update_Clock CALL LCD_Port ;Reconfigure Ports for LCD andCALL Disp_Time ;display the new time

Exit ;Reloads TMR0 so the next 60th second time-out can generate;an interrupt and restores all registers.

MOVLW 93 ;Preload W for 60 Hz delayMOVWF TMR0 ;and save to TMR0BCF T0IF ;Clear TMR0 interrupt flag andBSF T0IE ;enable TMR0 interrupt

Restore MOVF Temp_PortA,0 ;Restore registers from temporaryMOVWF PORTA ;registersMOVF Temp_PortB,0MOVWF PORTBBSF RP0MOVF Temp_TRISA,0MOVWF TRISAMOVF Temp_TRISB,0MOVWF TRISBBCF RP0

SWAPF Temp_Status,0 ;Swap Status halves to WMOVWF Status ;and return Status to pre-interrupt

;valueSWAPF Temp_W,1 ;Swap halves of Temp_WSWAPF Temp_W,0 ;Swap Temp_W back to W

RETFIE ;Return and enable interrupts

Other_Int MOVLW 20h ;Set only TMR0 interruptMOVWF INTCON ;and write to interrupt registerRETFIE ;Return and enable global interrupts

Initialize CLRF Counter ;Clear countersCLRF Counter1CLRF Counter2CLRF Counter3CLRF Counter4MOVLW 60 ;Preload sixtiethsMOVWF Sixtieth ;with 60

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Init ;Display �Elapsed time:� on line 1CALL Disp_Time ;Display time on line 2

CALL TMR0_Init ;Initialize Real Time Clock Counter;Timer 0 (TMR0) and enable interrupts.

BSF RP0 ;Select Register Page 1CLRF TRISB ;Make Port B outputBCF RP0 ;Back to Register Page 0

MOVLW 01h ;Light up the first LEDMOVWF PORTB ;on Port BBCF C ;Clear the Carry

CLOCK.ASM - Chapter 11 Example Program

Page 326: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code56

Main ;This code runs when the Interrupt service routine isn�t;running and cycles a single LED across the display.

:Loop DECFSZ Counter3,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter4,1 ;Decrement, second counterGOTO :Loop ;from constant, above

RLF PORTB ;Rotate PORTB to the leftGOTO Main ;Do it again and again and ...

Disp_Init ;Writes �Elapsed time:� to first line of LCD display using;LCD display library (LCD.LIB).

MOVLW LCDCLR ;Send LCD clear display codeCALL LCD_REG ;to LCD as a commandMOVLW LCDLine1 ;Send LCD line one address toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Get_Char MOVF Counter,0 ;Get character offset into WCALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for the next character

Message ADDWF PCL ;Offset program counter by adding WRETLW �E� ;MessageRETLW �l�RETLW �a�RETLW �p�RETLW �s�RETLW �e�RETLW �d�RETLW � �RETLW �t�RETLW �i�RETLW �m�RETLW �e�RETLW �:�RETLW 0 ;End of message

Disp_Time ;Converts binary Hours, Minutes and Seconds digits to BCD;and then to ASCII and displays them on LCD separated by;colons.

MOVLW LCDLine2 ;Send LCD line two address toCALL LCD_REG ;LCD as a commandMOVF Hours,0 ;Load W with Hours valueCALL Disp_Digits ;and output to LCDMOVLW �:� ;Load W with ASCII value of �:�CALL LCD_Data ;and display on LCDMOVF Minutes,0 ;Load W with Minutes valueCALL Disp_Digits ;and output to LCDMOVLW �:� ;Load W with ASCII value of �:�CALL LCD_Data ;and display on LCDMOVF Seconds,0 ;Load W with Seconds valueCALL Disp_Digits ;and output to LCDRETURN

Disp_Digits ;Converts and displays value in W as two digits on LCD.

CLOCK.ASM - Chapter 11 Example Program

Page 327: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 57Program Pull-Out

References

CALL BIN_DEC ;and convert to tens and onesMOVLW 30h ;Load W with ASCII offsetADDWF Tens,1 ;and add to Tens digitADDWF Ones,1 ;and Ones to change to ASCIIMOVF Tens,0 ;Load W with Tens valueCALL LCD_Data ;and display on LCDMOVF Ones,0 ;Load W with Ones valueCALL LCD_Data ;and display on LCDRETURN

TMR0_Init ;Assign prescaler to TMR0 and preload TMR0 for 60 Hz;interrupts.

CLRWDT ;Clear WDT and prescalerBSF RP0 ;Select register page 1MOVF OPTION,0 ;Load W with current OPTION reg.ANDLW 11000111b ;Clear T0CS, T0SE and PSA bits

;T0CS=OPTION.5, Counter select;0=Timer mode, 1=Counter mode;T0SE=OPTION.4, Source Edge select;0=Rising edge, 1=Falling edge;PSA=OPTION.3, Prescaler Assignment;0=TMR0, 1=WDT

IORLW 00000111b ;Set PS2, PS1 and PS0;000=/2, 001=/4, ...111=/256

MOVWF OPTION ;Set OPTION register with new valueBCF RP0 ;Return to register page 0

MOVLW 93 ;Load W with 93 because incrementingMOVWF TMR0 ;TMR0 from 93-256 takes 1/60s

MOVLW 20h ;Enable only the TMR0 interruptMOVWF INTCON ;and write to INTCON

RETFIE ;Return and enable global interrupts

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

Include �BIN2DEC.LIB� ;Binary to Decimal conversion routineInclude �LCD.LIB� ;LCD subroutine library

CLOCK.ASM - Chapter 11 Example Program

Page 328: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code58

;COUNT.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates port output. It initializes all port B pins; to be outputs and then counts from 0 to 255 (FFh) repeatedly.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This is a simple program that requires no prior setup.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �CNT �

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Turn off LEDs by clearing Port B

Loop INCF PORTB ;Add 1 to Port B registerGOTO Loop ;and do it again, and again...

Done SLEEP ;Stop executing the program

COUNT.ASM - Chapter 8 Example Program

Page 329: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 59Program Pull-Out

References

;CUSTOM.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

;; This program demonstrates how to create & use custom LCD characters.; Four Truck and four Man characters are created from bitmaps. The; Man character is used to show cursor cell animation and the Truck; demonstrates line scrolling.;

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; None

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �CUST�

;Hardware Equates

ORG 0Ch ;Start of File register area

Counter DS 1 ;LCD character counterPosition DS 1 ;LCD position counter

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

ORG 00h ;Start program at Reset Vector

CLRF Counter ;Clear LCD character counterCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �LCD.LIB� ;LCD subroutine library

CUSTOM.ASM - Chapter 12 Example Program

Page 330: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code60

Initialize ;This subroutine initializes the LCD display and programs;the custom characters by calling Prog_Character.

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Prog_Character ;Load LCD with custom charactersMOVLW LCDLine1 ;Load W with Line 1 addressMOVWF Position ;Save W in Position registerCALL LCD_REG ;and send to LCD as commandMOVLW 04h ;Load W with Man1 Character codeMOVWF Counter ;and save in LCD character counter

Walk ;Makes a little man walk across the screen by successively;writing each of the 4 Man characters into the same cursor;position and then moving the cursor 1 position to the;right before repeating.

MOVF Counter,0 ;Get current Man CharacterCALL LCD_Data ;and send to LCDMOVLW CursLeft ;Load W with Cursor Left shiftCALL LCD_Reg ;command and send to LCDCALL Delay ;Wait a bitINCF Counter ;Increment to next Man CharacterMOVLW 08h ;Load W with number of last ManSUBWF Counter,0 ;and check for last countBTFSS Z ;by checking ZGOTO Walk ;If not at last Man, display next man

MOVLW � � ;If at last Man, Load W with � �CALL LCD_Data ;to clear characterMOVLW 04h ;Load W with Man1 CharacterMOVWF Counter ;and save to character counterINCF Position ;Increment cursor position variableMOVLW 90h ;Load W with last visible positionSUBWF Position,0 ;and compare with PositionBTFSS Z ;by checking ZGOTO Walk ;If not at last position, do it again

CALL Delay ;If done, wait before rolling Truck

Roll ;Scrolls a Truck back across the screen continuously by;writing the 4 Truck characters off the screen (cursor was;left at position 90h by Walk) and then scrolling the;screen to the left. Since the display was cleared earlier;you will see only the Truck. The line length is 40 chars.;Every 40 display shifts, the Truck comes around again.

CLRF Counter ;Clear character counter variable:Next MOVF Counter,0 ;Load W with counter

CALL LCD_Data ;and send character to LCDINCF Counter ;Increment Counter registerMOVLW 04h ;Load W with number of Truck chars.SUBWF Counter,0 ;and compare with counterBTFSS Z ;by checking ZGOTO :Next ;If not done, send next Truck char.

:Loop MOVLW LCDLeft ;If done, load W with LCD shift leftCALL LCD_Reg ;command and send to LCDCALL Delay ;Wait a bitGOTO :Loop ;Keep scrolling the display

Prog_Character ;Loads the custom character data into the LCD Character;Generator RAM. CGRAM is ASCII characters 0-7. Each character;is loaded as a bit-map, one line at a time. The cursor;auto-increments to the next CGRAM location after each;write.

CUSTOM.ASM - Chapter 12 Example Program

Page 331: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 61Program Pull-Out

References

MOVLW LCDCGRAM ;Send LCD CGRAM address (40h) toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Get_Char MOVF Counter,0 ;Get character offset into WCALL Characters ;use it to get character dataCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterMOVLW 64 ;Load W with number of char. bytesSUBWF Counter,0 ;and compare with CounterBTFSC Z ;by checking Z flagRETURN ;If Counter=64, we�re doneGOTO Get_Char ;Do it again for the next character

Characters ADDWF PCL ;Offset PC with Counter in W

Truck1 RETLW 00000000b ;Row 1, ASCII character 00RETLW 00000011b ;Row 2, ASCII character 00RETLW 00000011b ;Row 3, ASCII character 00RETLW 00001111b ;etc.RETLW 00001111bRETLW 00011010bRETLW 00000111bRETLW 00000010b

Truck2 RETLW 00001111b ;Row 1, ASCII character 01RETLW 00001111b ;Row 2, ASCII character 01RETLW 00001111b ;etc.RETLW 00001111bRETLW 00011111bRETLW 00001010bRETLW 00011111bRETLW 00001010b

Truck3 RETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00000000bRETLW 00000000bRETLW 00000000b

Truck4 RETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00011111bRETLW 00001010bRETLW 00011111bRETLW 00001010b

Man1 RETLW 00000000bRETLW 00000000bRETLW 00010000bRETLW 00011000bRETLW 00010000bRETLW 00001000bRETLW 00001000bRETLW 00000000b

Man2 RETLW 00000000bRETLW 00000000bRETLW 00000000bRETLW 00001000bRETLW 00011100bRETLW 00001000bRETLW 00011000b

CUSTOM.ASM - Chapter 12 Example Program

Page 332: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code62

RETLW 00001000b

Man3 RETLW 00000000bRETLW 00000000bRETLW 00000000bRETLW 00000100bRETLW 00000110bRETLW 00000100bRETLW 00001010bRETLW 00001010b

Man4 RETLW 00000000b ;Row 1, ASCII character 07RETLW 00000000b ;Row 2, ASCII character 07RETLW 00000001bRETLW 00000011bRETLW 00000001bRETLW 00000011bRETLW 00000001bRETLW 00000000b ;Row 8, ASCII character 07

Delay ;Delay between Man & Truck movements

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;256 more timesRETURN

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

CUSTOM.ASM - Chapter 12 Example Program

Page 333: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 63Program Pull-Out

References

;DBOUNCE.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates switch contact debouncing. It initializes; port A bit 4 as an input and port B as output. Each time the user; connects port A bit 4 to ground, the LEDs increment, displaying the; number of contact closures. The count accumulates until the RESET; button is pressed. Note that port A has no internal pull-up; capability. However the PIC-MDS has an external pull-up pre-wired to; Port A bit 4.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; Attach a small piece of wire to the third screw terminal (CON1-3).; When this grounded wire is connected to the 8th screw terminal; (CON1-8) the LEDs on port B increment, reflecting the number of switch; closures.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �DBNC�

;Hardware Equates

Counter1 EQU 0Ch ;First delay counter variableCounter2 EQU 0Dh ;Second delay counter variable

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 00010000b ;Load W with the desired I/O patternMOVWF TRISA ;Make Port A bit 4 input

;(1=input, 0=output)CLRF TRISB ;Make Port B output

DBOUNCE.ASM - Chapter 9 Example Program

Page 334: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code64

BCF RP0 ;Back to register page 0CLRF PORTB ;Turn off all LEDsCLRF Counter1 ;Clear location Counter1 (0Ch)MOVLW 40h ;Load W with preset for counter 2MOVWF Counter2 ;Store W to Counter2 (0Dh)

Main BTFSC PORTA.4 ;Check Port A bit 4 for a lowGOTO Main ;If we�re here, bit 4 is high

Delay DECFSZ Counter1 ;If we�re here, bit 4 is lowGOTO Delay ;Let�s wait at least 20 ms for theDECFSZ Counter2 ;contacts to settleGOTO Delay

MOVLW 40h ;Once delay is done, reset counter 2MOVWF Counter2 ;Store W to Counter2 (0Dh)

BTFSS PORTA.4 ;Is Port A bit 4 still low?INCF PORTB ;If so, increment Port B

Wait_for_High BTFSS PORTA.4 ;Wait for Port A bit 4 to go highGOTO Wait_for_High ;If low, keep checkingGOTO Main ;If high, go back to Main

DBOUNCE.ASM - Chapter 9 Example Program

Page 335: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 65Program Pull-Out

References

;DELAY.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates port output. It initializes all port B pins; to be outputs and then counts from 0 to 255 (FFh) repeatedly with a; delay of 65536 decrements between each count.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This is a simple program that requires no prior setup.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �DELA�

;Hardware Equates

Counter1 EQU 0Ch ;First delay counter registerCounter2 EQU 0Dh ;Second delay counter register

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0CLRF PORTB ;Clear Port B registerCLRF Counter1 ;Clear Counter1 register (0Ch)CLRF Counter2 ;and Counter2 register(0Dh)

Main INCF PORTB ;Add 1 to Port B registerLoop DECFSZ Counter1 ;Decrement Counter1 and check for 0

GOTO Loop ;If not 0, decrement Counter 1 againDECFSZ Counter2 ;If 0, decrement Counter2GOTO Loop ;If Counter2 is not 0, decrement

;Counter1 another 256 timesGOTO Main ;Update the LEDs after 65536 counts

DELAY.ASM - Chapter 8 Example Program

Page 336: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code66

;KEY.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; Col. 1 2 3 4; Row +----+----+----+----+; Port B.0----1---| 1 | 2 | 3 | 4 |; +----+----+----+----+; Port B.1----2---| 5 | 6 | 7 | 8 |; +----+----+----+----+; Port B.2----3---| 9 | 10 | 11 | 12 |; +----+----+----+----+; Port B.3----4---| 13 | 14 | 15 | 16 |; +----+----+----+----+; Port B.4----------+ | | |; | | |; Port B.5---------------+ | |; | |; Port B.6--------------------+ |; |; Port B.7-------------------------+;; This program demonstrates matrix keypad scanning along with LCD; output using included subroutine libraries. The keypad is scanned; continuously. Key return codes are converted to ASCII and displayed; by their key digit (from the above diagram) on the LCD display.; The key code will display for as long as it is valid.;; This program uses the DS (Define Space) directive instead of EQU; (Equate) to define RAM registers. The advantage of this approach; is that hardware registers can be created and removed from this; program without manually re-locating their addresses. The drawback; is that the physical location of the register is defined by the; assembler, not the user.;; Also, notice that this program utilizes the space from memory; location 0000h to the interrupt vector at 0004h. It�s not much; space, but you can cram an extra 3 words into your program by; doing this (the 4th word is the GOTO which jumps the interrupt; vector, and is not really useful as storage).

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

KEY.ASM - Chapter 10 Example Program

Page 337: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 67Program Pull-Out

References

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �KEY �

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by KEYPAD.LIB:Key DS 1 ;Key code return register

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Other equatesCounter DS 1 ;character counter for LCDCounter1 DS 1 ;general purpose counterCounter2 DS 1 ;general purpose counterCounter3 DS 1 ;general purpose counter

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key storage registerCALL LCD_Port ;Set up ports for LCD outputCALL LCD_Init ;Initialize LCD and clear screenGOTO Initialize ;Continue with initialize routine

ORG 05h ;Continue after interrupt vector

Include �LCD.LIB� ;LCD subroutines go hereInclude �KEYPAD.LIB� ;followed by Keypad subroutinesInclude �BIN2DEC.LIB� ;and Binary to Decimal conversion

Initialize CALL DisplayInit ;Display �Key Pressed:� on LCD

Main ;This program loop scans the keypad using KEYPAD.LIB and;gets the key value from Key register. BIN2DEC.LIB is used;to convert the binary key number to three decimal digits.;Each decimal digit is converted to ASCII by adding 30h and;is sent to the LCD display.

MOVF Key,0 ;Get key code in WCALL BIN_DEC ;and convert to decimalCALL LCD_Port ;Set up ports for LCD outputMOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to LCD display data RAMMOVLW 30h ;Load constant to convert to ASCIIADDWF Hundreds,1 ;and add to hundreds digitADDWF Tens,1 ;add to tens digitADDWF Ones,1 ;and add to ones digitMOVF Hundreds,0 ;Get hundreds digit into WCALL LCD_Data ;and send it to LCDMOVF Tens,0 ;Get tens digit into WCALL LCD_Data ;and send it to LCDMOVF Ones,0 ;Get ones digit into WCALL LCD_Data ;and send it to LCDCALL KB_Port ;Set up Port B for keypad input

KEY.ASM - Chapter 10 Example Program

Page 338: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code68

CALL KB_Scan ;Read Port B for key pressGOTO Main ;Do it again!

DisplayInit ;Writes �Key Pressed:� to first line of LCD using;LCD display library (LCD.LIB).

MOVLW LCDCLR ;Send LCD clear display codeCALL LCD_REG ;to LCD as a commandMOVLW LCDLine1 ;Send LCD line one address toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Get_Char MOVF Counter,0 ;Get character offset into WCALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for next character

Message ADDWF PCL ;Offset program counter by adding WRETLW �K� ;MessageRETLW �e�RETLW �y�RETLW � �RETLW �P�RETLW �r�RETLW �e�RETLW �s�RETLW �s�RETLW �e�RETLW �d�RETLW �:�RETLW 0 ;End of message marker

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with Timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

KEY.ASM - Chapter 10 Example Program

Page 339: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 69Program Pull-Out

References

;KEYINT.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; Col. 1 2 3 4; Row +----+----+----+----+; Port B.0----1---| 1 | 2 | 3 | 4 |; +----+----+----+----+; Port B.1----2---| 5 | 6 | 7 | 8 |; +----+----+----+----+; Port B.2----3---| 9 | 10 | 11 | 12 |; +----+----+----+----+; Port B.3----4---| 13 | 14 | 15 | 16 |; +----+----+----+----+; Port B.4----------+ | | |; | | |; Port B.5---------------+ | |; | |; Port B.6--------------------+ |; |; Port B.7-------------------------+;; This program demonstrates interrupt driven matrix keypad scanning; along with LCD output using included subroutine libraries. This; program is functionally equivalent to KEY.ASM in its operation, but; puts the microcontroller to sleep in between operations. Sleep mode; allows for ultra-low power consumption and is useful for extending; the battery life or portable applications.;; The program first initializes the LCD and displays �Key Pressed:�.; Next, assuming the microcontroller will shortly be sleeping, the; letters �ZZZ� replace the key code number. Then, port B is; reconfigured for keypad input with the pull-up resistors enabled.; Finally, the RB Port Change interrupt is enabled after clearing; the interrupt flag (just in case). After setting the Global; Interrupt Enable flag, the microcontroller goes to sleep.;; When a key on the keypad is pressed, it pulls one of the RB4-7; input pins low, generating an interrupt. The microcontroller begins; to execute the code at 0004h�the interrupt vector. Here, the RB; port change interrupt is disabled, Port B is used to scan the keys; for a key press, and the result is converted to ASCII and displayed; on the LCD. By this point, the user is likely still holding the key; on, and the microcontroller is once more put to sleep with the RB; port change interrupt enabled. When the key is released, the code; at 0004h again executes, updating the display.;; This program uses the DS (Define Space) directive instead of EQU; (Equate) to define RAM registers. The advantage of this approach; is that hardware registers can be created and removed from this; program without manually re-locating their addresses. The drawback; is that the physical location of the register is defined by the; assembler, not the user.;; Also, notice that this program utilizes the space from memory

KEYINT.ASM - Chapter 11 Example Program

Page 340: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code70

; location 0000h to the interrupt vector at 0004h. It�s not much; space, but you can cram an extra 3 words into your program by; doing this (the 4th word is the GOTO which jumps the interrupt; vector, and is not really useful as storage).

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �KEYI�

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by KEYPAD.LIB:Key DS 1 ;Key code return register

;Equates required by BIN2DEC.LIB and DEC2BIN.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Other equatesCounter DS 1 ;character counter for LCDCounter1 DS 1 ;general purpose counterCounter2 DS 1 ;general purpose counterCounter3 DS 1 ;general purpose counter

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear key storage registerCALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenGOTO Initialize ;Continue with initialize routine

ORG 04h ;Interrupt service routine starts here

Check_RBIF ;When an interrupt occurs, Check_RBIF confirms it was;generated by RB Port Change. If not, and other interrupts;are enabled, they must get serviced in the Other_Int;routine. When a valid key arrives, it gets displayed,;then the port is re-configured for keypad input. Exiting;this interrupt service routine, re-enables interrupts.

BTFSS RBIF ;Check for RB port change interrupt

KEYINT.ASM - Chapter 11 Example Program

Page 341: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 71Program Pull-Out

References

GOTO Other_Int ;If cleared, check other interruptsCALL Delay_5ms ;Wait for key to settleCALL Delay_5ms ;10 ms should be enough timeCALL KB_Port ;Set up Port B for keypad scanningCALL KB_Scan ;Scan keys for key pressMOVF Key,0 ;Check Key register for 0 - no keyBTFSC Z ;by testing the Z flagGOTO Nap_Time ;If no key was returned, user let go

;so we display ZZZ to indicate sleep

CALL BIN_DEC ;If key returned, convert to decimalCALL LCD_Port ;Set up ports for LCD outputMOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to display data RAMMOVLW 30h ;Load constant to convert to ASCIIADDWF Hundreds,1 ;and add to hundreds digit,ADDWF Tens,1 ;add to tens digitADDWF Ones,1 ;and add to ones digitMOVF Hundreds,0 ;Gets hundreds digit into W andCALL LCD_Data ;send it to LCDMOVF Tens,0 ;Get tens digit into W andCALL LCD_Data ;send it to LCDMOVF Ones,0 ;Get ones digit into W andCALL LCD_Data ;send it to LCD

CALL KB_Port ;Set up Port B for keypad scanningCLRF PORTB ;and get ready for Port B ChangeMOVF PORTB,0 ;Update Port B input latchesBCF RBIF ;Clear the interrupt flagRETFIE ;and return

Other_Int RETFIE ;Return and enable global interrupts

Initialize CALL DisplayInit ;Display �Key Pressed:� on LCD

Nap_Time MOVLW 8Dh ;Send address of hundreds digitCALL LCD_REG ;to display data RAMMOVLW �Z� ;Load ASCII character ZCALL LCD_Data ;and send it to LCDMOVLW �Z� ;Re-load ASCII character ZCALL LCD_Data ;and send it to LCDMOVLW �Z� ;One more time!CALL LCD_Data ;and send it to LCD

CALL Init_Port_B ;Get Port B ready for interrupts

Main SLEEP ;Shut down and wait for key pressNOPGOTO Main

DisplayInit ;Writes �Key Pressed:� to first line of LCD display using;LCD display library (LCD.LIB).

MOVLW LCDCLR ;Send LCD clear display codeCALL LCD_REG ;to LCD as a commandMOVLW LCDLine1 ;Send LCD line one address toCALL LCD_REG ;LCD as a commandCLRF Counter ;Reset character counter

Get_Char MOVF Counter,0 ;Get character offset into WCALL Message ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO Get_Char ;Do it again for the next character

KEYINT.ASM - Chapter 11 Example Program

Page 342: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code72

Message ADDWF PCL ;Offset program conter by adding WRETLW �K� ;MessageRETLW �e�RETLW �y�RETLW � �RETLW �P�RETLW �r�RETLW �e�RETLW �s�RETLW �s�RETLW �e�RETLW �d�RETLW �:�RETLW 0 ;End of message

Init_Port_B ;Sets Port B up for keypad scanning. RB0-3 are low outputs;and RB4-7 are inputs with pull-ups enabled. When a key;press occurs, one of the RB4-7 inputs goes low, generating;and interrupt.

CALL KB_Port ;Set Port B for keypad scanningCLRF PORTB ;Make outputs lowMOVLW 08h ;Set only RB port change interruptMOVWF INTCON ;and write to interrupt registerRETFIE ;Return and enable interrupts

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

Include �BIN2DEC.LIB� ;Binary to Decimal conversion routineInclude �KEYPAD.LIB� ;Key pad scanning routinesInclude �LCD.LIB� ;LCD subroutine library

KEYINT.ASM - Chapter 11 Example Program

Page 343: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 73Program Pull-Out

References

;KEYSCAN.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; Col. 1 2 3 4; Row +----+----+----+----+; Port B.0----1---| 1 | 2 | 3 | 4 |; +----+----+----+----+; Port B.1----2---| 5 | 6 | 7 | 8 |; +----+----+----+----+; Port B.2----3---| 9 | 10 | 11 | 12 |; +----+----+----+----+; Port B.3----4---| 13 | 14 | 15 | 16 |; +----+----+----+----+; Port B.4----------+ | | |; | | |; Port B.5---------------+ | |; | |; Port B.6--------------------+ |; |; Port B.7-------------------------+;; This program demonstrates matrix keypad scanning. Port B.0-3 connect; to the keypad rows and are set as outputs. Port B.4-7 connect to the; keypad columns and are set as inputs with the internal pull-up; resistors enabled. To read the keypad, a row is set low. While the; row is low, each column input is examined. Columns normally are high; because of the pull-up resistors. If a column is low, the key at that; row-column intersection is pressed. If no column is found low, the; program advances to the next row.;; When a key press is detected, that row-column combination assigns a; number from 1-16 (according to the above diagram) to the Key variable.; The binary value in the Key variable is displayed on the LEDs. Note; that the same Port B pins have two functions: most of the time they; are scanning the keypad, with Port B.4-7 as inputs and Port B.0-3 as; outputs. When a key is pressed Port B is temporarily set to output to; display the key value. The key will display for a short period of; time. When a key is not pressed, you will notice the key scanning; taking place.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

KEYSCAN.ASM - Chapter 9 Example Program

Page 344: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code74

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �KSCN�

;Hardware Equates

Counter1 EQU 0Ch ;Delay counter registerCounter2 EQU 0Dh ;Delay counter registerCounter3 EQU 0Eh ;Delay counter registerKey EQU 0Fh ;This register will hold a number from

;0-15 representing the last key pressed

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select register page 1MOVLW 0F0h ;Set keypad column connections to input

;(Port B.4-7) and row connections to;output (Port B.0-3)

MOVWF TRISB ;Write to Port B tristate registerBSF RBPU ;Enable pull-ups on inputsBCF RP0 ;Go back to register page 0CLRF Counter1 ;Clear delay loop countersCLRF Counter2MOVLW 08h ;Preload Counter3 delay loop counterMOVWF Counter3 ;for 1/2 second delay

Main CLRF Key ;Clear Key register andINCF Key ;Increment KeyMOVLW 0Eh ;Output 0 to first row only,MOVWF PORTB ;Output to Port BNOP ;Wait for signals to settle

Col_Check BTFSS PORTB.4 ;Check first column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.5 ;Check second column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.6 ;Check third column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key numberBTFSS PORTB.7 ;Check fourth column for lowGOTO Dispkey ;and if low, display keyINCF Key ;If no key press, increment key number

Row_Set MOVLW 11h ;Load W with number of keys + 1SUBWF Key,0 ;and compare with current key valueBTFSC Z ;If keys + 1 = current key thenGOTO Main ;no key was pressed

BSF C ;Set carry bitRLF PORTB ;so that row 1 is high during rotateGOTO Col_Check ;and check next column

Dispkey BSF RP0 ;Select register page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0

KEYSCAN.ASM - Chapter 9 Example Program

Page 345: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 75Program Pull-Out

References

MOVF Key,0 ;Put value of Key into WMOVWF PORTB ;and display on LEDs

Delay DECFSZ Counter1 ;3-level nested loopGOTO Delay ;gives approx. 1/2 second delayDECFSZ Counter2GOTO DelayDECFSZ Counter3GOTO Delay

GOTO Initialize ;We�re done. Reset Port B and delay;counters

KEYSCAN.ASM - Chapter 9 Example Program

Page 346: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code76

;KEYSCLB.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; Col. 1 2 3 4; Row +----+----+----+----+; Port B.0----1---| 1 | 2 | 3 | 4 |; +----+----+----+----+; Port B.1----2---| 5 | 6 | 7 | 8 |; +----+----+----+----+; Port B.2----3---| 9 | 10 | 11 | 12 |; +----+----+----+----+; Port B.3----4---| 13 | 14 | 15 | 16 |; +----+----+----+----+; Port B.4----------+ | | |; | | |; Port B.5---------------+ | |; | |; Port B.6--------------------+ |; |; Port B.7-------------------------+;; This program demonstrates matrix keypad scanning using calls to an; included subroutine library. It is functionally equivalent to the; KEYSCAN.ASM program.;; The following description is from KEYSCAN.ASM. Port B.0-3 connect; to the keypad rows and are set as outputs. Port B.4-7 connect to the; keypad columns and are set as inputs with the internal pull-up; resistors enabled. To read the keypad, a row is set low. While the; row is low, each column input is examined. Columns normally are high; because of the pull-up resistors. If a column is low, the key at that; row-column intersection is pressed. If no column is found low, the; program advances to the next row.;; When a key press is detected, that row-column combination assigns a; number from 1-16 (according to the above diagram) to the Key variable.; The binary value in the Key variable is displayed on the LEDs. Note; that the same Port B pins have two functions: most of the time they; are scanning the keypad, with Port B.4-7 as inputs and Port B.0-3 as; outputs. When a key is pressed Port B is temporarily set to output to; display the key value. The key will display for a short period of; time. When a key is not pressed, you will notice the key scanning; taking place.;; KEYSCLB.ASM differs from KEYSCAN.ASM in that the keypad port control; and scanning routines are called from KEYPAD.LIB. Since all of the; actual keypad logic is contained in the KEYPAD.LIB file, KEYSCLB.ASM; is a much shorter source file than KEYSCAN.ASM. This makes program; creation simpler, since a programmer needs only to concentrate on; the �real� logic of the program, and not the nitty-gritty details.;; Subroutine libraries often require variables to be defined. Variables; described in the subroutine library need to be defined in the calling; program. This way, all variable definitions reside in the calling

KEYSCLB.ASM - Chapter 10 Example Program

Page 347: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 77Program Pull-Out

References

; program.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �KSLB�

;Hardware Equates

Counter1 EQU 0Ch ;Delay counter registerCounter2 EQU 0Dh ;Delay counter registerCounter3 EQU 0Eh ;Delay counter register

;Equates required by KEYPAD.LIBKey EQU 0Fh ;This register will hold a number from

;0-15 representing the last key pressed

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Include �KEYPAD.LIB� ;KEYPAD.LIB subroutines go here

Initialize CALL KB_Port ;Library call to initialize Port B for;keypad input

CLRF Counter1 ;Clear delay loop countersCLRF Counter2MOVLW 08h ;Preload Counter3 delay loop counterMOVWF Counter3 ;for 1/2 second delay

Main CALL KB_Scan ;Library call to scan keypadMOVF Key,0 ;Load value of Key into WBTFSC Z ;Check for no keyGOTO Main ;If Z set, no key so scan again

Dispkey BSF RP0 ;Select register page 1CLRF TRISB ;Set Port B to outputBCF RP0 ;Go back to register page 0

MOVF Key,0 ;Put value of Key into WMOVWF PORTB ;and display on LEDs

Delay DECFSZ Counter1 ;3-level nested loopGOTO Delay ;gives approx. 1/2 second delayDECFSZ Counter2GOTO Delay

KEYSCLB.ASM - Chapter 10 Example Program

Page 348: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code78

DECFSZ Counter3GOTO Delay

GOTO Initialize ;We�re done. Reset Port B and delay;counters

KEYSCLB.ASM - Chapter 10 Example Program

Page 349: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 79Program Pull-Out

References

;NVMEM.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates how to use EEPROM.LIB to store important; data in the PIC16F84�s non-volatile EEPROM memory. NVMEM simply; displays the contents of the first four EEPROM memory locations on; the LCD display and expects you to enter a 4-digit number from the; keypad. This 4-digit number (which could represent a pass-code) is; stored into EEPROM and a message indicating that you should remove; power from the PIC-MDS is displayed. Remove power from the PIC-MDS,; and upon powering up, the number you entered will be displayed.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �NVME�

;Hardware Equates

ORG 0Ch ;Start of File register area

Counter DS 1 ;LCD character counter

Counter1 DS 1 ;LCD delay counterCounter2 DS 1 ;LCD delay counter

Key DS 1 ;Key return code variable

Digit DS 1 ;ASCII digit counter variable

ORG 00h ;Start program at Reset Vector

NVMEM.ASM - Chapter 13 Example Program

Page 350: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code80

CLRF Key ;Clear Key return variableCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �EEPROM.LIB� ;EEPROM subroutine libraryInclude �KEYPAD.LIB� ;Keypad scanning subroutine libraryInclude �LCD.LIB� ;LCD subroutine library

Initialize ;This subroutine initializes the LCD display and writes;a message on to line 1 and �=� on to line 2. The cursor;is turned on to indicate where input will be shown.

CLRF Digit ;Clear digit counterCALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenCALL Disp_Line1 ;Send first line message to LCD

Send_Old ;Reads EEPROM addresses 0-3 and writes the contents to the;LCD display.

CLRF EEADR ;Select EEPROM address 00:Loop CALL EE_Read ;Call EE_Read to place data into

MOVF EEDATA,0 ;EEDATA, and read EEDATA into WCALL LCD_Data ;Copy W to LCD DDRAMINCF EEADR ;Increment to next EEPROM addressMOVLW 04h ;Load W with number of data bytesSUBWF EEADR,0 ;and compare with EEADRBTFSS Z ;by checking ZGOTO :Loop ;If not at EEADR 04, get next data

Line2 MOVLW LCDLine2 ;Load W with line 2 DDRAM addressCALL LCD_Reg ;and write to LCDCALL Disp_Line2 ;Send second line message to LCD

MOVLW CursOn ;Load W with Cursor On commandCALL LCD_Reg ;and write to LCD

Get_New ;Wait for key presses and after a debounce delay stores the;ASCII value of the current key codes in EEPROM memory from;address 0-3.

CLRF EEADR ;Reset EEADR to the beginningCALL KB_Port ;Configure Port B for keypad

Get_Key CALL KB_Scan ;Get Key return codeMOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try againCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

CALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Key_Remap ;and Remap key codes

MOVWF EEDATA ;Save new Key code in EEDATACALL EE_Write ;Write key data to current EEADRCALL EE_Wait ;and wait for write to finish

CALL EE_Read ;Read current EEADR to check;that EEDATA was written properly

CALL LCD_Port ;Configure Ports for LCD

NVMEM.ASM - Chapter 13 Example Program

Page 351: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 81Program Pull-Out

References

MOVF EEDATA,0 ;Get saved Key code from EEPROMCALL LCD_Data ;and display on LCD

CALL KB_Port ;Set Port B for keypad useWait CALL KB_Scan ;Scan keypad

MOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has been releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay_5ms ;Wait for key to settleCALL Delay_5msCALL Delay_5msCALL Delay_5ms

INCF EEADR ;Increment to next EEPROM addressMOVLW 04h ;Load W with number of data bytesSUBWF EEADR,0 ;and compare with EEADRBTFSS Z ;by checking ZGOTO Get_Key ;If not at EEADR 04, get next dataCALL LCD_Port ;Reconfigure ports for LCDMOVLW LCDLine1 ;Load W with line 1 DDRAM addressCALL LCD_Reg ;and write to LCDCALL Disp_Done ;Display done messageSLEEP

Key_Remap ;Changes key codes into ASCII values.

ADDWF PCL ;Use old Key to offset PCNOP ;No Key=0 codeRETLW 30h ;key 1 remapped to ASCII 30h �0�RETLW 31h ;key 2 remapped to ASCII 31h �1�RETLW 32h ;key 3 remapped to ASCII 32h �2�RETLW 33h ;key 4 remapped to ASCII 33h �3�RETLW 34h ;key 5 remapped to ASCII 34h �4�RETLW 35h ;key 6 remapped to ASCII 35h �5�RETLW 36h ;key 7 remapped to ASCII 36h �6�RETLW 37h ;key 8 remapped to ASCII 37h �7�RETLW 38h ;key 9 remapped to ASCII 38h �8�RETLW 39h ;key 10 remapped to ASCII 39h �9�RETLW 41h ;key 11 remapped to ASCII 41h �A�RETLW 42h ;key 12 remapped to ASCII 42h �B�RETLW 43h ;key 13 remapped to ASCII 43h �C�RETLW 44h ;key 14 remapped to ASCII 44h �D�RETLW 45h ;key 15 remapped to ASCII 45h �E�RETLW 46h ;key 16 remapped to ASCII 46h �F�

Disp_Line1 ;Writes �Old Data: � to the first line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counter:Get_Char MOVF Counter,0 ;Get character offset into W

CALL Message1 ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO :Get_Char ;Do it again for the next character

Message1 ADDWF PCL ;Offset program counter by adding WRETLW �O� ;Message1RETLW �l�RETLW �d�RETLW � �RETLW �D�RETLW �a�

NVMEM.ASM - Chapter 13 Example Program

Page 352: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code82

RETLW �t�RETLW �a�RETLW �:�RETLW � �RETLW 0 ;End of message

Disp_Line2 ;Writes �New Data: � to the second line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counter:Get_Char MOVF Counter,0 ;Get character offset into W

CALL Message2 ;use it to get characterIORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO :Get_Char ;Do it again for the next character

Message2 ADDWF PCL ;Offset program counter by adding WRETLW �N� ;Message2RETLW �e�RETLW �w�RETLW � �RETLW �D�RETLW �a�RETLW �t�RETLW �a�RETLW �:�RETLW � �RETLW 0 ;End of message

Disp_Done ;Writes �Power down now.� to the first line of the LCD;display using LCD display library (LCD.LIB).

CLRF Counter ;Reset character counter:Get_Char MOVF Counter,0 ;Get character offset into W

MOVLW HI Message3 ;Move the High Byte of Message3;location into W

MOVWF PCLATH ;and Move it into PCLATHMOVLW Message3+1 ;Move message address + 1 into WADDWF Counter,0 ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Message3 ;Jump to the data table

IORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Counter,1 ;Add 1 to CounterGOTO :Get_Char ;Do it again for the next character

Message3 MOVWF PCL ;W contains low program counter;byte and points to next location;plus Counter offset

RETLW �P�RETLW �o�RETLW �w�RETLW �e�RETLW �r�RETLW � �RETLW �d�RETLW �o�RETLW �w�RETLW �n�

NVMEM.ASM - Chapter 13 Example Program

Page 353: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 83Program Pull-Out

References

RETLW � �RETLW �n�RETLW �o�RETLW �w�RETLW �.�RETLW � �RETLW 0 ;End of message

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

NVMEM.ASM - Chapter 13 Example Program

Page 354: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code84

;OUTPUT.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates port output. It initializes all port B pins; to be outputs and then places a pattern on port B to illuminate LEDs.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This is a simple program that requires no prior setup.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �OUTP�

ORG 00h ;Reset Vector locationGOTO Initialize ;Start program after Interrupt vector

ORG 05h ;One location past Interrupt vector

Initialize BSF RP0 ;Select memory register page 1CLRF TRISB ;Make Port B output by clearing TRISBBCF RP0 ;Go back to register page 0

Main MOVLW 01010101b ;Move 01010101b into W andMOVWF PORTB ;output pattern to LEDs on Port

Done SLEEP ;Stop executing the program

OUTPUT.ASM - Chapter 5 Example Program

Page 355: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 85Program Pull-Out

References

;RECV232.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates serial port polling and software timed; RS-232 signal reception. Serial characters are received at the serial; header (H3), translated from RS-232 to TTL levels by the MAX232,; and routed through the serial Transmit/Receive select jumper (JU5); to RA.4 on the PIC. Once characters are received, they are scrolled; across the LCD display. RA.4 was chosen to receive serial characters; because it can generate a TMR0 interrupt in response to a change in; the signal level applied to it.;; To ensure accurate serial bit timing, use a crystal oscillator and; not a ceramic resonator to generate the processor clock.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select RX

;Requirements

; An external RS-232 serial terminal or a computer with an appropriate; connection to the PIC-MDS serial input header (H3). For testing we; used a cable wired as follows:;; Computer DB-25 PIC-MDS; Transmit pin 2 �> H3.3 - Rx; Receive pin 3 �> H3.1 - Tx; Ground pin 7 �> H3.2 - Gnd

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �232R�

;Hardware Equates

ORG 0Ch ;Start of File register area

;Counter equatesCharAddress DS 1 ;Holds current LCD DDRAM addressCharCounter DS 1 ;Counts characters before scrollingCounter1 DS 1 ;Delay counter for Delay_5ms

RECV232.ASM - Chapter 15 Example Program

Page 356: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code86

Counter2 DS 1 ;Delay counter for Delay_5ms

;Equates required by RS232RX.LIBCounter DS 1 ;Bit delay counterBitCounter DS 1 ;RS232 bit counter registerReceive DS 1 ;Received byte storage register

;Other equatesLCD_Length EQU 16 ;Number of characters per LCD line

ORG 00h ;Start program at Reset Vector

CALL LCD_Port ;Set up ports for LCD use CALL LCD_Init ;Initialize LCD and clear screen

CALL Receive_Port ;Set RA.4 for serial inputGOTO Initialize ;Jump over interrupt vector

ORG 05h ;Program starts after interrupt vector

Include �LCD.LIB� ;LCD subroutine libraryInclude �RS232RX.LIB� ;RS-232 receive library

Initialize ;Prepare character counters and LCD for data

MOVLW LCD_Length ;Load W with number of LCD characters MOVWF CharCounter ;and save in CharCounter DECF CharCounter ;-1 from CharCounter to account for 0 MOVLW CursBlink ;Load W with constant to blink cursor CALL LCD_Reg ;and write to LCD as a command

MOVLW LCDLine1 ;Load W with DDRAM address of line 1 MOVWF CharAddress ;and save in CharAddress variable CALL LCD_Reg ;before writing it to the LCD

Main ;Receive serial characters in Receive buffer

CALL Receive_Wait ;Wait for and receive one serial byte

MOVF Receive,0 ;After receiving, check character forBTFSC Z ;and error (Receive=00h)GOTO Main ;If no character, wait again

LCD_Write ;Write the character in Receive buffer to LCD display

MOVF Receive,0 ;Move received character into W & CALL LCD_Data ;write to current DDRAM address INCF CharAddress ;Add 1 to DDRAM address counter MOVLW 0A8h ;Load W with last DDRAM address +1 SUBWF CharAddress,0 ;and subtract from CharAddress BTFSC Z ;to see if 40 characters are full GOTO Line_Reset ;If so, reset LCD to start of line

MOVF CharCounter,1 ;Check Character counter for end BTFSC Z ;of visible screen by checking Z GOTO Scroll ;If at end, scroll display left DECF CharCounter ;If not, decrement CharCounter GOTO Main ;and wait for next character

Scroll ;Scroll display left to keep new characters in LCD window

MOVLW LCDLeft ;Load W with LCD shift left commandCALL LCD_Reg ;and send to LCD

GOTO Main ;Wait for next character

Line_Reset ;If 40 characters have been written to DDRAM, scroll the;display contents left and reset DDRAM to line 1.

RECV232.ASM - Chapter 15 Example Program

Page 357: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 87Program Pull-Out

References

MOVLW LCDLeft ;Load W with LCD shift left commandCALL LCD_Reg ;and write to LCDMOVLW LCDLine1 ;Load W with first DDRAM addressMOVWF CharAddress ;and save in CharAddress registerCALL LCD_Reg ;before writing it to LCD

GOTO Main ;Wait for more serial data

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Clear Counter1MOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

RECV232.ASM - Chapter 15 Example Program

Page 358: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code88

;SEETEST.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone:at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; SEETEST is a utility to test and program 93LC56 (256 byte) and 93LC66; (512 byte) serial EEPROMs (SEEPROMs) in the Sirius PICmicro Devemopment; System. SEEPROM address and data are displayed in Hex on the top line of; the LCD display. The lower line displays the prompts �Dwn Up Sel Chg�.; The top row of buttons on the keypad acts as soft keys for the prompts; on the LCD. Selecting the �Dwn� or �Up� buttons decrements or increments; the SEEPROM address. For each address, the data stored at that address; is displayed. Pressing �Sel� allows you to enter a 3-digit address (000-; 1FF) to view or change. Pressing �Chg� allows you to enter a 2-digit hex; byte into the current address.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select X8; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; If you are using the EPIC programmer and the In-Circuit programming; cable, you must remove this cable from the PIC-MDS to ensure proper; program execution. Otherwise, keys in column 4 will not be read.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84, HS_OSC, WDT_OFF, PROTECT_OFF, PWRT_ONID �SEET�

;Hardware Equates

ORG 0Ch ;Start of File register area

Digit DS 1 ;Hex digit registerCharacter DS 1 ;LCD message character offsetCounter1 DS 1 ;LCD delay/keystroke delay counterCounter2 DS 1 ;LCD delay/keystroke delay counterDelay DS 1 ;Keystroke delay durationKeyTemp DS 1 ;Temporary Key register

Addrh DS 1 ;Temporary SEEPROM high address byteAddrl DS 1 ;Temporary SEEPROM low address byte

SEETEST.ASM - Chapter 17 Example Program

Page 359: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 89Program Pull-Out

References

;Equates required by KEYPAD.LIB

Key DS 1 ;Key return code variable

;Equates required by SEEPROM.LIB

SEEAddrh DS 1 ;SEEPROM high address byteSEEAddrl DS 1 ;SEEPROM low address byteSEEClock DS 1 ;SEEPROM clock counter registerSEEData DS 1 ;SEEPROM data storage byte

;Software Equates

Menu_Msg EQU 0 ;Menu message offsetStatus_Msg EQU 16 ;Status display message offsetAddr_Msg EQU 31 ;�Enter Address� message offsetData_Msg EQU 47 ;�Enter Data� message offset

Address EQU 5 ;Cursor offset for address displayData EQU 14 ;Cursor offset for data display

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key return variableCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �SEEPROM.LIB� ;EEPROM subroutine libraryInclude �LCD.LIB� ;LCD subroutine libraryInclude �KEYPAD.LIB� ;Keypad scanning subroutine library

Initialize ;Continue setting variables and initialize the LCD display.

CLRF Digit ;Clear hex digit registerCLRF Addrl ;Clear program low and high addressCLRF Addrh ;bytes to set initial address to 000h

Update_Status ;Displays the current SEEPROM address and data on the top line;of the LCD and the Menu options on the bottom line.

CALL LCD_Port ;Set up ports for LCD useCALL LCD_Init ;Initialize LCD and clear screenMOVLW LCDLine1 ;Send line 1 starting characterCALL LCD_Reg ;address to LCDMOVLW Status_Msg ;Load W with Status message offsetCALL Disp_Message ;and call display message routineMOVLW LCDLine1+Address ;Set LCD character position toCALL LCD_Reg ;start of address display area

MOVF Addrh,W ;Load W with high address byteANDLW 0Fh ;Clear upper nybbleCALL Hex_Remap ;and convert to ASCII for LCDCALL LCD_Data ;and display on LCD

MOVF Addrl,W ;Load W with low address byteMOVWF Digit ;and save a copy in Digit register

SWAPF Digit,W ;Switch nybbles and copy to WANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVF Addrl,W ;Load W with low address byte againANDLW 0Fh ;Clear upper nybble before

SEETEST.ASM - Chapter 17 Example Program

Page 360: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code90

CALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

CALL SEE_Port ;Set up Port A for SEEPROM use MOVF Addrl,W ;Copy low address byte to

MOVWF SEEAddrl ;SEEPROM low address byte MOVF Addrh,W ;Copy high address byte to

MOVWF SEEAddrh ;SEEPROM high address byteMOVLW SEERead ;Send SEEPROM Read byte commandCALL SEE_Command ;to SEEPROM

CALL LCD_Port ;Set up Ports for LCD useMOVLW LCDLine1+Data ;Set LCD character position toCALL LCD_Reg ;start of data display area

SWAPF SEEData,W ;Switch nybbles of SEEPROM data to WANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVF SEEData,W ;Load W with SEEPROM data byteANDLW 0Fh ;Clear upper nybble beforeCALL Hex_Remap ;converting to ASCII forCALL LCD_Data ;display on LCD

MOVLW LCDLine2 ;Send LCD line 2 character addressCALL LCD_Reg ;to LCD as a commandMOVLW Menu_Msg ;Load W with Menu message offsetCALL Disp_Message ;and call display message routine

CALL KB_Port ;Set Port B for keypad useCALL KB_Scan ;and scan keys for key press

MOVF Key,W ;Load Key return code into WMOVWF KeyTemp ;and save in temporary register

MOVLW 01h ;Copy short key repeat delay intoMOVWF Delay ;Delay register

Wait_for_Key ;Waits for a top-row key press and determines the action that;follows the key press.

CALL KB_Scan ;Get Key return code MOVF Key,W ;Load Key code into W to set flags

BTFSC Z ;and check for 0 (0=no key)GOTO Wait_for_Key ;If no key pressed, try again

:Key1 DECFSZ Key ;Check for Key=1 by subtractingGOTO :Key2 ;If not 0, check for Key=2

MOVF KeyTemp,W ;Load W with previous key codeSUBLW 01h ;and check for equality with 1BTFSC Z ;If not equal, key not held so skipGOTO :Delay1 ;If equal, key held. Use short delay.MOVLW 20h ;Copy long delay intoMOVWF Delay ;Delay register

:Delay1 CALL Repeat_Delay ;and wait for delayCALL Addr_Down ;If 0, decrment SEEPROM addressGOTO Update_Status ;and redisplay Status screen

:Key2 DECFSZ Key ;Check for Key=2 by subtractingGOTO :Key3 ;If not 0, check for Key=3

MOVF KeyTemp,W ;Load W with previous key codeSUBLW 02h ;and check for equality with 1BTFSC Z ;If not equal, key not held so skipGOTO :Delay2 ;If equal, key held. Use short delay.MOVLW 20h ;Copy long delay intoMOVWF Delay ;Delay register

:Delay2 CALL Repeat_Delay ;and wait for delayCALL Addr_Up ;If 0, increment SEEPROM address

SEETEST.ASM - Chapter 17 Example Program

Page 361: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 91Program Pull-Out

References

GOTO Update_Status ;and redisplay Status screen

:Key3 DECFSZ Key ;Check for Key=3 by subtractingGOTO :Key4 ;If not 0, check for Key=4CALL Addr_Set ;If 0, allow user to set addressCALL KB_Port ;Set Port B for keypad useCALL Key_Release ;and wait for all keys to be releasedGOTO Update_Status ;Redisplay Status screen

:Key4 DECFSZ Key ;Check for Key=4 by subtractingGOTO Wait_for_Key ;If not 0, ignore other keysCALL Data_Set ;If 0, allow user to set dataCALL KB_Port ;Set Port B for keypad useCALL Key_Release ;and wait for all keys to be releasedGOTO Update_Status ;Redisplay Status screen

Addr_Down ;Decrements the current 9-bit SEEPROM address.

MOVF Addrl,1 ;Check Addrl for 0 by moving it ontoBTFSC Z ;itself and checking the Z flagGOTO :Check_Addrh ;If Addrl is 0, check AddrhDECF Addrl ;Otherwise, decrement Addrl andRETURN ;return to calling program

:Check_Addrh MOVF Addrh,1 ;Check Addrh for 0 by moving it ontoBTFSC Z ;itself and checking the Z flagRETURN ;If Addrh=0 & Addrl=0, don�t decrementDECF Addrh ;Otherwise, decrement Addrh andDECF Addrl ;Addrl before returningRETURN

Addr_Up ;Increments the current 9-bit SEEPROM address.

INCF Addrl ;Increment Addrl and check for aBTFSS Z ;roll-over to 0RETURN ;If no roll-over, returnMOVF Addrh,1 ;Check Addrh for 0 by moving it ontoBTFSS Z ;itself and chekcing the Z flagGOTO :Fix_Addrl ;If Addrl=0 & Addrh=1, decrement AddrlINCF Addrh ;Otherwise, increment AddrhRETURN ;and return

:Fix_Addrl DECF Addrl ;Decrement Addrl to highest possibleRETURN ;address of 1FF and return

Addr_Set ;Allows the user to enter the 9-bit SEEPROM Address.

CALL LCD_Port ;Set Port A and Port B for LCD useMOVLW LCDLine2 ;Set LCD charcter position to lineCALL LCD_Reg ;two and send command to LCDMOVLW Addr_Msg ;Load W with Address message offsetCALL Disp_Message ;and call display message routine

MOVLW LCDLine1+Address ;Set LCD character position toCALL LCD_Reg ;start of address display areaMOVLW �?� ;Load W with �?� characterCALL LCD_Data ;and send to LCD three times toMOVLW �?� ;indicate address entry fieldCALL LCD_DataMOVLW �?�CALL LCD_DataMOVLW LCDLine1+Address ;Set LCD character position toCALL LCD_Reg ;start of address display areaMOVLW CursBlink ;and set blinking cursorCALL LCD_Reg ;Send command to LCD

SEETEST.ASM - Chapter 17 Example Program

Page 362: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code92

CLRF Addrh ;Clear high and lowCLRF Addrl ;SEEPROM address bytesCALL KB_Port ;Set Port B for keypad use andCALL Key_Release ;make sure that no keys are pressed

:Digit1 CALL KB_Scan ;Scan keys for a keystroke MOVF Key,W ;Load Key into W to check for keypress

BTFSC Z ;and check Z flagGOTO :Digit1 ;If Z=0, no key pressed. Scan againCALL Key_Remap ;Convert key stroke to binary nybbleMOVWF Digit ;and save in Digit registerMOVF Digit,1 ;Reread Digit to set flagsBTFSC Z ;Check for Digit=0 by testing ZGOTO :Store1 ;If Digit was 0, store & display it

DECF Digit,W ;Otherwise, check for Digit=1 byBTFSS Z ;decrementing and checking ZGOTO :Digit1 ;If not 0 or 1 wait for valid Digit

:Store1 CALL LCD_Port ;Set Port A and Port B for LCD use MOVF Digit,W ;Copy saved Digit to

MOVWF Addrh ;Addrh registerCALL Hex_Remap ;and convert to ASCII valueCALL LCD_Data ;Display Digit code on LCD

CALL KB_Port ;Set Port B for keypad use andCALL Key_Release ;make sure that no keys are pressed

:Digit2 CALL KB_Scan ;Scan keys for a keystroke MOVF Key,W ;Load Key into W to check for keypress

BTFSC Z ;and check Z flagGOTO :Digit2 ;If Z=0, no key pressed. Scan againCALL Key_Remap ;Convert key stroke to binary nybbleMOVWF Digit ;Save result to Digit register andMOVWF Addrl ;save in top of Addrl registerSWAPF Addrl,1 ;by swapping nybbles of AddrlCALL LCD_Port ;Set Port A and Port B for LCD use

MOVF Digit,W ;Load W with Digit valueCALL Hex_Remap ;and convert to ASCIICALL LCD_Data ;Display Digit code on LCD

CALL KB_Port ;Set Port B for keypad use andCALL Key_Release ;make sure that no keys are pressed

:Digit3 CALL KB_Scan ;Scan keys for a keystroke MOVF Key,W ;Load Key into W to check for keypress

BTFSC Z ;and check Z flagGOTO :Digit3 ;If Z=0, no key pressed. Scan againCALL Key_Remap ;Convert key stroke to binary nybbleMOVWF Digit ;Save result to Digit register andIORWF Addrl ;save in bottom of AddrlCALL LCD_Port ;Set Port A and Port B for LCD useMOVLW CursOff ;Send LCD command to turn offCALL LCD_Reg ;blinking cursor

MOVF Digit,W ;Load W with Digit valueCALL Hex_Remap ;and convert to ASCIICALL LCD_Data ;Display Digit code on LCD

RETURN

Data_Set ;Allows the user to enter the 8-bit SEEPROM data.

CALL LCD_Port ;Set Port A and Port B for LCD useMOVLW LCDLine2 ;Set LCD charcter position to lineCALL LCD_Reg ;two and send command to LCDMOVLW Data_Msg ;Load W with Data message offsetCALL Disp_Message ;and call display message routine

MOVLW LCDLine1+Data ;Set LCD character position toCALL LCD_Reg ;start of data display area

SEETEST.ASM - Chapter 17 Example Program

Page 363: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 93Program Pull-Out

References

MOVLW �?� ;Load W with �?� characterCALL LCD_Data ;and send to LCD two times toMOVLW �?� ;indicate data entry fieldCALL LCD_DataMOVLW LCDLine1+Data ;Reset LCD character position toCALL LCD_Reg ;start of address display areaMOVLW CursBlink ;and set blinking cursorCALL LCD_Reg ;Send command to LCD

CLRF SEEData ;Clear SEEPROM data byteCALL KB_Port ;Set Port B for keypad use andCALL Key_Release ;make sure that no keys are pressed

:Digit1 CALL KB_Scan ;Scan keys for a keystroke MOVF Key,W ;Load Key into W to check for keypress

BTFSC Z ;and check Z flagGOTO :Digit1 ;If Z=0, no key pressed. Scan againCALL Key_Remap ;Convert key stroke to binary nybbleMOVWF Digit ;Save Key code in Digit registerMOVWF SEEData ;and also in top of SEEData registerSWAPF SEEData,1 ;by swapping nybbles of SEEDataCALL LCD_Port ;Set Port A and Port B for LCD use

MOVF DIgit,W ;Load W with Digit valueCALL Hex_Remap ;and convert to ASCIICALL LCD_Data ;Display key code on LCD

CALL KB_Port ;Set Port B for keypad use andCALL Key_Release ;make sure that no keys are pressed

:Digit2 CALL KB_Scan ;Scan keys for a keystroke MOVF Key,W ;Load Key into W to check for keypress

BTFSC Z ;and check Z flagGOTO :Digit2 ;If Z=0, no key pressed. Scan againCALL Key_Remap ;Convert key stroke to binary nybbleMOVWF Digit ;Save Key code in Digit registerIORWF SEEData ;and save in bottom of SEEDataCALL LCD_Port ;Set Port A and Port B for LCD useMOVLW CursOff ;Send LCD command to turn offCALL LCD_Reg ;blinking cursor

MOVF Digit,W ;Load W with Digit valueCALL Hex_Remap ;and convert to ASCIICALL LCD_Data ;Display key code on LCD

CALL SEE_Port ;Configure Port A for SEEPROMMOVLW SEEEWEN ;Send Erase/Write Enable commandCALL SEE_Command ;to SEEPROM

MOVF Addrl,W ;Copy Addrl byte toMOVWF SEEAddrl ;SEEAddrl

MOVF Addrh,W ;Copy Addrh byte toMOVWF SEEAddrh ;SEEAddrhMOVLW SEEWrite ;Send data write commandCALL SEE_Command ;to SEEPROMMOVLW SEEEWDS ;Send Erase/Write Disable commandCALL SEE_Command ;to SEEPROM

RETURN

Key_Release ;Waits for the key to be released

CALL KB_Scan ;Scan keys for key press MOVF Key,W ;Check Key return code for no key

BTFSS Z ;by checking for 0 (0=no key)GOTO Key_Release ;If key pressed, try againCALL Delay_5ms ;If key released, wait for debouncingRETURN ;and return

Hex_Remap ;Changes binary nybble into ASCII Hex value.

SEETEST.ASM - Chapter 17 Example Program

Page 364: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code94

MOVWF Character ;Store character offset

MOVLW HI Hex_Code ;Move the High Byte of Hex_Code;address location into W

MOVWF PCLATH ;and into PCLATHMOVLW Hex_Code+1 ;Move address + 1 into W

ADDWF Character,W ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Hex_Code ;Jump to the data table

RETURN ;and finish if done

Hex_Code MOVWF PCL ;Use Hex digit to offset PCRETLW �0� ;0000 remapped to �0�RETLW �1� ;0001 remapped to �1�RETLW �2� ;0010 remapped to �2�RETLW �3� ;0011 remapped to �3�RETLW �4� ;0100 remapped to �4�RETLW �5� ;0101 remapped to �5�RETLW �6� ;0110 remapped to �6�RETLW �7� ;0111 remapped to �7�RETLW �8� ;1000 remapped to �8�RETLW �9� ;1001 remapped to �9�RETLW �A� ;1010 remapped to �A�RETLW �B� ;1011 remapped to �B�RETLW �C� ;1100 remapped to �C�RETLW �D� ;1101 remapped to �D�RETLW �E� ;1110 remapped to �E�RETLW �F� ;1111 remapped to �F�

Key_Remap ;Changes key code into binary nybble.

MOVWF Character ;Store character offset

MOVLW HI Key_Code ;Move the High Byte of Hex_Code;address location into W

MOVWF PCLATH ;and into PCLATHMOVLW Key_Code+1 ;Move address + 1 into W

ADDWF Character,W ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Key_Code ;Jump to the data table

RETURN ;and finish if done

Key_Code MOVWF PCL ;Use Key code to offset PCNOP ;No key 0RETLW 01h ;Key 1 remapped to 0001RETLW 02h ;Key 2 remapped to 0010RETLW 03h ;Key 3 remapped to 0011RETLW 0Ah ;Key 4 remapped to 1010RETLW 04h ;Key 5 remapped to 0100RETLW 05h ;Key 6 remapped to 0101RETLW 06h ;Key 7 remapped to 0110RETLW 0Bh ;Key 8 remapped to 1011RETLW 07h ;Key 9 remapped to 0111RETLW 08h ;Key 10 remapped to 1000RETLW 09h ;Key 11 remapped to 1001RETLW 0Ch ;Key 12 remapped to 1100RETLW 0Eh ;Key 13 remapped to 1110RETLW 00h ;Key 14 remapped to 0000RETLW 0Fh ;Key 15 remapped to 1111RETLW 0Dh ;Key 16 remapped to 1101

Disp_Message ;Copies ASCII data from a look-up table to the current cursor

SEETEST.ASM - Chapter 17 Example Program

Page 365: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 95Program Pull-Out

References

;position of the LCD. Character is loaded with the starting;offset of the message before calling this routine.

MOVWF Character ;Save offset in Character counter

:Get_Char MOVLW HI Message ;Move the High Byte of Message3;location into W

MOVWF PCLATH ;and Move it into PCLATHMOVLW Message+1 ;Move message address + 1 into W

ADDWF Character,W ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Message ;Jump to the data table

IORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Character,1 ;Add 1 to CharacterGOTO :Get_Char ;Do it again for the next character

Message MOVWF PCL ;W contains low program counter;byte and points to next location;plus Character offset

RETLW � � ;Menu_Msg StartRETLW �D�RETLW �w�RETLW �n�RETLW � �RETLW �U�RETLW �p�RETLW � �RETLW �S�RETLW �e�RETLW �l�RETLW � �RETLW �C�RETLW �h�RETLW �g�RETLW 0 ;End of message 1

RETLW �A� ;Status_Msg StartRETLW �d�RETLW �d�RETLW �r�RETLW �:�RETLW � �RETLW � �RETLW � �RETLW � �RETLW �D�RETLW �a�RETLW �t�RETLW �a�RETLW �:�RETLW 0 ;End of message 2

RETLW �E� ;Addr_Msg StartRETLW �n�RETLW �t�RETLW �e�RETLW �r�RETLW � �RETLW �A�RETLW �d�RETLW �d�RETLW �r�

SEETEST.ASM - Chapter 17 Example Program

Page 366: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code96

RETLW �e�RETLW �s�RETLW �s�RETLW � �RETLW � �RETLW 0 ;End of message 3

RETLW �E� ;Data_Msg StartRETLW �n�RETLW �t�RETLW �e�RETLW �r�RETLW � �RETLW �D�RETLW �a�RETLW �t�RETLW �a�RETLW � �RETLW � �RETLW � �RETLW � �RETLW � �RETLW 0 ;End of message 4

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

Repeat_Delay ;Long delay loop to for key repeat

CLRF Counter1 ;Wipe Counter1 and:Set MOVLW 40h ;load W with preset

MOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement second counterGOTO :Loop ;256 more timesCALL KB_Scan ;Scan Key codes for release

MOVF Key,W ;Load Key code into W and checkBTFSC Z ;for 0 (0=released)RETURN ;If released, return earlyDECFSZ Delay ;Decrement delay duration counterGOTO :Set ;based on loaded Delay valueRETURN

SEETEST.ASM - Chapter 17 Example Program

Page 367: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 97Program Pull-Out

References

;TIMEOUT.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates how to determine whether a MCLR or Watch Dog; Timer (WDT) reset was responsible for re-starting program executing in; the PICmicro. The LCD displays a message indicating the source of the; reset, either MCLR or WDT. During normal processing the WDT is always; being reset. By pressing and holding a key for 2-3 seconds, the WDT will; time out, resetting the PICmicro. Use the reset button to restart the; program.

; Note that this program also demonstrates a problem that may occur during; the execution of WDT-enabled programs. Although a user typically presses; and releases a key, pressing and holding a key in this program will; cause an unintended reset. Make sure to verify the operation of programs; that receive an unintended WDT reset!

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This program has no special requirements.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_ON,PROTECT_OFF,PWRT_ONID �TOUT�

;Hardware Equates

ORG 0Ch ;Start of File register area

Character DS 1 ;LCD message character offsetCounter1 DS 1 ;LCD delay/keystroke delay counterCounter2 DS 1 ;LCD delay/keystroke delay counter

;Equates required by KEYPAD.LIB

Key DS 1 ;Key return code variable

TIMEOUT.ASM - Chapter 18 Example Program

Page 368: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code98

;Software Equates

Reset_Msg EQU 0 ;Reset source message offsetPwr_Msg EQU 12 ;Power up message offsetWDT_Msg EQU 29 ;Watchdog timer message offset

ORG 00h ;Start program at Reset Vector

CLRF Key ;Clear Key return variableCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �LCD.LIB� ;LCD subroutine libraryInclude �KEYPAD.LIB� ;Keypad scanning subroutine library

Initialize ;Continue by initializing the LCD display.

CALL LCD_Port ;Set up Ports for LCD use

BTFSS TO ;Check WDT Time Out flag andGOTO WDT_Message ;skip WDT and LCD init if reset by WDT

Init_WDT CLRWDT ;Clear Watchdog TimerBSF RP0 ;Select register page 1MOVLW 0FFh ;Set Option register for WDT withMOVWF Option ;1:128 prescaler (maximum prescaler)BCF RP0 ;Return to register page 0

Init_LCD CALL LCD_Init ;Initialize LCD and clear screenMOVLW LCDLine1 ;Send line 1 starting addressCALL LCD_Reg ;to LCDMOVLW Reset_Msg ;Load W with Reset message offsetCALL Disp_Message ;and call display message routineMOVLW LCDLine2 ;Send line 2 starting addressCALL LCD_Reg ;to LCDMOVLW Pwr_Msg ;Load W with power up message offsetCALL Disp_Message ;and display it on line 2 of LCDGOTO Wait_for_Key ;Continue with main program

WDT_Message MOVLW LCDLine2 ;Send line 2 starting addressCALL LCD_Reg ;to LCDMOVLW WDT_Msg ;Load W with WDT message offsetCALL Disp_Message ;and display it on line 2 of LCD

Wait_for_Key ;Checks for a key press. If no keys are pressed, WDT is reset.

CALL KB_Port ;Set up Ports for keypad scanningCALL KB_Scan ;Get Key return codeMOVF Key,W ;Load Key code into W to set flagsBTFSC Z ;and check for 0 (0=no key)GOTO Reset_WDT ;If no key pressed, reset WDT

Key_Release ;Waits for the key to be released. If a key is held for 2-3;seconds, the WDT will time out since there is not CLRWDT;instruction inside this wait loop.

CALL KB_Scan ;Scan keys for key pressMOVF Key,W ;Check Key return code for no keyBTFSS Z ;by checking for 0 (0=no key)GOTO Key_Release ;If key is held, check again

TIMEOUT.ASM - Chapter 18 Example Program

Page 369: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 99Program Pull-Out

References

Reset_WDT ;Resets the WDT, setting the TO flag.

CLRWDT ;If no key pressed, clear WatchdogGOTO Wait_for_Key ;and check for another key press

Disp_Message ;Copies ASCII data from a look-up table to the current cursor;position of the LCD. Character is loaded with the starting;offset of the message before calling this routine.

MOVWF Character ;Save offset in Character counter

:Get_Char MOVLW HI Message ;Move the High Byte of Message3;location into W

MOVWF PCLATH ;and Move it into PCLATHMOVLW Message+1 ;Move message address + 1 into WADDWF Character,0 ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Message ;Jump to the data table

IORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Character,1 ;Add 1 to CharacterGOTO :Get_Char ;Do it again for the next character

Message MOVWF PCL ;W contains low program counter;byte and points to next location;plus Character offset

RETLW �R� ;Reset_Msg StartRETLW �e�RETLW �s�RETLW �e�RETLW �t�RETLW � �RETLW �f�RETLW �r�RETLW �o�RETLW �m�RETLW �:�RETLW 0 ;End of message 1

RETLW �P� ;Pwr_Msg StartRETLW �o�RETLW �w�RETLW �e�RETLW �r�RETLW �-�RETLW �u�RETLW �p�RETLW � �RETLW �o�RETLW �r�RETLW � �RETLW �M�RETLW �C�RETLW �L�RETLW �R�RETLW 0 ;End of message 2

RETLW �W� ;WDT_Msg StartRETLW �a�RETLW �t�RETLW �c�

TIMEOUT.ASM - Chapter 18 Example Program

Page 370: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code100

RETLW �h�RETLW �d�RETLW �o�RETLW �g�RETLW � �RETLW �t�RETLW �i�RETLW �m�RETLW �e�RETLW �r�RETLW �!�RETLW �!�RETLW 0 ;End of message 3

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

TIMEOUT.ASM - Chapter 18 Example Program

Page 371: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 101Program Pull-Out

References

;VMETER.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone:at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates the use of the PIC16C711 A/D converter in a; voltmeter type application. It samples the voltage on potentiometers; RA0 and RA1 and displays the binary result as a decimal number on the; LCD. The RA0 value is then scaled to 5V and displayed as a voltage on; line 2 of the LCD while the RA1 value is converted into a bar-graph; display on the LED Bar.;; Note: If you use a voltmeter to measure the voltage on RA0 and RA1; while this program is running, you will not get the same results as; on the display. The reason for this is that both RA0 and RA1 are; multiplexed between being digital control lines for the LCD and analog; inputs for the PIC. An oscilloscope will show the correct analog; voltage between LCD writes.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 ON; RA1 ON; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; None

Maclib �P71x.INC� ;Library file for PIC16C711 and PM assembler ;Comment this line out for other assemblers

Device PIC16C711, HS_OSC, WDT_OFF, PROTECT_OFF, PWRT_ON ID �VMET�

;Hardware Equates

ORG 0Ch ;Start of register file memory

Counter1 DS 1 ;LCD/A-D update delay counterCounter2 DS 1 ;LCD/A-D update delay counterCounter3 DS 1 ;A-D update delay counterCharacter DS 1 ;LCD message character offsetAnalog0 DS 1 ;Temporary Analog storage for chan. 0Analog1 DS 1 ;Temporary Analog storage for chan. 1Bargraph DS 1 ;Temporary storage for LED bar output

VMETER.ASM - Chapter 16 Example Program

Page 372: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code102

;Equates used by BIN2BCD.LIB

HighByte DS 1 ;High byte of numberLowByte DS 1 ;Low byte of number

TenThous DS 1 ;Ten thousands BCD digitThouHund DS 1 ;Thousands & Hundreds BCD digitTensOnes DS 1 ;Tens and Ones BCD digit

ShiftCounter DS 1 ;Counter for BCD conversion shifts

;Software Equates

Channel0_Msg EQU 0 ;�Ch.0:� message offsetChannel1_Msg EQU 5 ;�Ch.1:� message offsetVoltage_Msg EQU 10 ;�Ch.0 Voltage:� message offsetCh0_Data EQU 4 ;Channel 0 data cursor addressCh1_Data EQU 12 ;Channel 1 data cursor addressCh0_Volts EQU 10 ;Channel 0 voltage cursor address

ORG 00h ;Reset Vector

CLRF Counter1 ;Clear delay counters CLRF Counter2 CLRF Counter3 GOTO Initialize ;Continue with initialization

ORG 05h ;One location past interrupt vector

Include �ATOD.LIB� ;A-D conversion library Include �LCD71.LIB� ;LCD subroutine library Include �BIN2BCD.LIB� ;Binary to BCD conversion library

Initialize ;Sets up the LCD and writes messages to line 1 and line 2.

CALL LCD_Port ;Set up ports for LCD use CALL LCD_Init ;Initialize LCD & clear screen MOVLW LCDLine1 ;Send line 1 starting address to CALL LCD_Reg ;to LCD as a command MOVLW Channel0_Msg ;Load W with channel 0 message offset CALL Disp_Message ;and call display message routine

MOVLW LCDLine1+8 ;Set LCD address to middle of line 1 CALL LCD_Reg ;and pass to LCD as a command MOVLW Channel1_Msg ;Load W with channel 1 message offset CALL Disp_Message ;and call display message routine

MOVLW LCDLine2 ;Send line 2 starting address to CALL LCD_Reg ;to LCD as a command MOVLW Voltage_Msg ;Load W with ch 0 voltage_msg offset CALL Disp_Message ;and call display message routine

Main ;Configures A-D converter by initializing Port A to be ;analogue intsead of digital, setting the clock divider, ;and selecting the A-D channel.

CALL AD_Port ;Initialize A-D converter & Port A MOVLW ADCLK32 ;Get clock divider for high speed CALL AD_Clock ;from ATOD.lib and set A-D MOVLW ADCH0 ;Get channel 0 constant and CALL AD_Channel ;set A-D channel MOVF Bargraph,W ;Display Bargraph value on LEDs while

VMETER.ASM - Chapter 16 Example Program

Page 373: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 103Program Pull-Out

References

MOVWF PORTB ;waiting for next conversion

Call Delay_5ms ;Wait for track & hold to settle CALL AD_Poll ;Start conversion, & wait until done MOVF ADRES,W ;Load conversion result into W and MOVWF Analog0 ;save in Analog0 for voltage display

MOVLW ADCH1 ;Get channel 1 constant and CALL AD_Channel ;set A-D channel MOVF Bargraph,W ;Display Bargraph value on LEDs while MOVWF PORTB ;waiting for next conversion

CALL Delay_5ms ;Wait for track & hold to settle CALL AD_Poll ;Start conversion, & wait until done MOVF ADRES,W ;Load conversion result into W and MOVWF Analog1 ;save in Analog1

CALL LCD_Port ;Reconfigure Ports for LCD use MOVLW LCDLine1+Ch0_Data ;Send channel 0 data starting CALL LCD_Reg ;address to LCD as a command MOVF Bargraph,W ;Display Bargraph value on LEDs while MOVWF PORTB ;waiting for BCD conversion MOVF Analog0,W ;Load channel 0 result into W and MOVWF LowByte ;save into LowByte register CALL Display_Num ;Let Display_Num display BCD digits

MOVLW LCDLine1+Ch1_Data ;Send channel 1 data starting CALL LCD_Reg ;address to LCD as a command MOVF Bargraph,W ;Display Bargraph value on LEDs while MOVWF PORTB ;waiting for bcd conversion MOVF Analog1,W ;Load channel 1 result into W and MOVWF LowByte ;save into LowByte register CALL Display_Num ;Let Display_Num display BCD digits

MOVLW LCDLine2+Ch0_Volts ;Send channel 0 voltage starting CALL LCD_Reg ;address to LCD as a command MOVF Bargraph,W ;Display Bargraph value on LEDs while MOVWF PORTB ;waiting for scaling CALL Scale_Voltage ;Convert Ch.0 result to voltage and CALL Display_Volts ;display the result on the LCD

MOVF Bargraph,W ;Display Bargraph value on LEDs while MOVWF PORTB ;waiting for lookup RRF Analog1 ;Divide channel 1 result by 2 RRF Analog1 ;again = divide by 4 RRF Analog1 ;again = divide by 8 RRF Analog1 ;again = divide by 16 RRF Analog1 ;again = divide by 32 MOVLW 07h ;Clear upper 5 bits of result by ANDWF Analog1,W ;ANDing with zero, leave 3 bit result CALL Bar_Table ;in W to look up 1 of 8 patterns MOVWF PORTB ;Output LED pattern to LED bar MOVWF Bargraph ;and to Bargraph register for update

CALL AD_Delay ;Wait to minimize display flicker GOTO Main ;and do it again

Bar_Table ;Look-up table for bar graph display. Takes a number from ;0 to 7 and determins which LEDs should be on.

CLRF PCLATH ;Clear PCLATH before doing lookup ADDWF PCL ;PCL=PCL+W to generate offset RETLW 10000000b ;Bottom LED on RETLW 11000000b ;Bottom 2 LEDs RETLW 11100000b ;Bottom 3 LEDs RETLW 11110000b ;Bottom 4 LEDs RETLW 11111000b ;Bottom 5 LEDs

VMETER.ASM - Chapter 16 Example Program

Page 374: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code104

RETLW 11111100b ;Bottom 6 LEDs RETLW 11111110b ;Bottom 7 LEDs RETLW 11111111b ;All LEDs on

Scale_Voltage ;Scales the result of the A/D conversion such that there are ;only 250 states instead of 256. This way the result can be ;multiplied by two to give a result from 0 to 500 representing ;a voltage of between 0.00 and 5.00 volts. For display, a ;decimal point is just inserted after the first digit by the ;Display_Volts subroutine.

MOVF Analog0,W ;Load W with the A/D result and SUBLW 225 ;check if it�s greater than 225 by BTFSS C ;testing the Carry flag DECF Analog0 ;If so, subtract one from the result MOVF Analog0,W ;Repeat the above process, comparing SUBLW 175 ;the A/D result with successively BTFSS C ;smaller values DECF Analog0 MOVF Analog0,W SUBLW 125 BTFSS C DECF Analog0 MOVF Analog0,W SUBLW 75 BTFSS C DECF Analog0 MOVF Analog0,W SUBLW 25 BTFSS C DECF Analog0

CLRF HighByte ;Clear HighByte register for multiply MOVF Analog0,W ;Reload W with scaled result and MOVWF LowByte ;save result in LowByte register BCF C ;Clear Carry before multiplying by 2 RLF LowByte ;Shift LowByte left to multiply RLF HighByte ;Shift Carry into HighByte CALL BIN_BCD ;and convert to BCD RETURN ;Return when done

Display_Volts ;Displays the result of the BCD scaled voltage as a decimal ;number at the current LCD cursor address.

MOVF ThouHund,W ;Load thousands & hundreds digits in ANDLW 0Fh ;W and clear thousands nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD MOVLW �.� ;Load W with ASCII code for �.� CALL LCD_Data ;and display on LCD SWAPF TensOnes,W ;Load tens & ones digit in reverse ANDLW 0Fh ;and clear ones nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD MOVF TensOnes,W ;Load tens and ones digits in ANDLW 0Fh ;W and clear tens nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD MOVLW �V� ;Load W with ASCII code for �V� CALL LCD_Data ;and display on LCD RETURN ;Return when done

Display_Num ;Converts the 8-bit A/D result to BCD and displays the ;hundreds, tens and ones digits on the LCD at the current ;LCD cursor address.

VMETER.ASM - Chapter 16 Example Program

Page 375: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 105Program Pull-Out

References

CLRF HighByte ;Clear HighByte before converting CALL BIN_BCD ;result to BCD MOVF ThouHund,W ;Load thousands & hundreds digits in ANDLW 0Fh ;W and clear thousands nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD SWAPF TensOnes,W ;Load tens & ones digit in reverse ANDLW 0Fh ;and clear ones nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD MOVF TensOnes,W ;Load tens and ones digits in ANDLW 0Fh ;W and clear tens nybble ADDLW 30h ;Add ASCII offset to generate number CALL LCD_Data ;and display on LCD RETURN ;Return when done

Disp_Message ;Copies ASCII data from a look-up table to the current cursor ;position of the LCD. Character is loaded with the starting ;offset of the message before calling this routine.

MOVWF Character ;Save offset in Character counter

:Get_Char MOVLW HI Message ;Move the High Byte of Message3 ;location into W MOVWF PCLATH ;and Move it into PCLATH MOVLW Message+1 ;Move message address + 1 into W ADDWF Character,W ;Calculate offset address and BTFSC C ;see if it overflows INCF PCLATH ;If so, increment PCLATH CALL Message ;Jump to the data table

IORLW 00h ;RETLW won�t affect flags so use OR to BTFSC Z ;check for end of message RETURN ;and finish if done CALL LCD_Data ;If not done, send character to LCD INCF Character,1 ;Add 1 to Character GOTO :Get_Char ;Do it again for the next character

Message MOVWF PCL ;W contains low program counter ;byte and points to next location ;plus Character offset

RETLW �C� ;Channel0_Msg Start RETLW �h� RETLW �0� RETLW �:� RETLW 0 ;End of message 1

RETLW �C� ;Channel1_Msg Start RETLW �h� RETLW �1� RETLW �:� RETLW 0 ;End of message 2

RETLW �C� ;Voltage_Msg Start RETLW �h� RETLW �0� RETLW � � RETLW �V� RETLW �o� RETLW �l� RETLW �t� RETLW �s� RETLW �:� RETLW 0 ;End of message 2

VMETER.ASM - Chapter 16 Example Program

Page 376: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code106

AD_Delay ;25ms delay between A-D conversions.

MOVLW 5 ;Load Counter3 with number of times MOVWF Counter3 ;to execute 5ms LCD delay loop

:Loop CALL Delay_5ms ;Wait 5 ms DECFSZ Counter3 ;Decrement counter 3 and check for 0 GOTO :Loop ;If not 0, wait again RETURN ;otherwise, return

Delay_5ms ;Delay loop used to initialize LCD.

CLRF Counter1 ;Wipe first counter MOVLW 1Ah ;Load W with timer Constant MOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counter GOTO :Loop ;256 times DECFSZ Counter2,1 ;Decrement second counter GOTO :Loop ;from constant, above RETURN

VMETER.ASM - Chapter 16 Example Program

Page 377: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 107Program Pull-Out

References

;WDTIMER.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates the use of the Watch Dog Timer (WDT) to wake; the PICmicro from Sleep in order to continue processing. This is useful; in reducing power consumption while periodically resuming processing; without using interrupts. By putting the PICmicro to Sleep, the WDT does; not reset the microcontroller. This is demonstrated by clearing the; Wake_Upx counters during a reset, but not during the WDT wake up (See; the data sheets for more information).;; The program displays a 16-bit count indicating the number of times that; the PICmicro has been awakened since the last reset. The display also; indicates whether the PICmicro is Sleeping or Processing.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select N/A

;Requirements

; This program has no special requirements.

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_ON,PROTECT_OFF,PWRT_ONID �WDTM�

;Hardware Equates

ORG 0Ch ;Start of File register area

Character DS 1 ;LCD message character offsetCounter1 DS 1 ;LCD delay/keystroke delay counterCounter2 DS 1 ;LCD delay/keystroke delay counterWake_UpH DS 1 ;Wake-up event counter high byteWake_UpL DS 1 ;Wake-up event counter low byte

;Equates required by BIN2BCD.LIB

TenThous DS 1 ;Ten thousands register

WDTIMER.ASM - Chapter 18 Example Program

Page 378: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code108

ThouHund DS 1 ;Thousands and hundreds registerTensOnes DS 1 ;Tens and ones registerHighByte DS 1 ;High byte of binary numberLowByte DS 1 ;Low byte of binary numberShiftCounter DS 1 ;BCD shift counter

;Software Equates

Wake_Up_Msg EQU 0 ;Wake-up message offsetSleep_Msg EQU 11 ;Sleeping message offsetProc_Msg EQU 22 ;Processing message offset

Wake_Ups EQU 8Bh ;Wake-up counter position on LCD

ORG 00h ;Start program at Reset Vector

CLRF ShiftCounter ;Clear BCD shift counterCLRF Counter1 ;and delay countersCLRF Counter2GOTO Initialize ;Continue with initialize routine

ORG 05h ;One location past Interrupt Vector

Include �LCD.LIB� ;LCD subroutine libraryInclude �BIN2BCD.LIB� ;Binary to BCD conversion library

Initialize ;Continue by initializing the LCD display.

CLRF Wake_UpH ;Continue clearing registersCLRF Wake_UpLCALL LCD_Port ;Set up Ports for LCD use

Init_WDT CLRWDT ;Clear Watchdog TimerBSF RP0 ;Select register page 1MOVLW 0FEh ;Set Option register for WDT withMOVWF Option ;1:64 prescalerBCF RP0 ;Return to register page 0

Init_LCD CALL LCD_Init ;Initialize LCD and clear screenMOVLW LCDLine1 ;Send line 1 starting addressCALL LCD_Reg ;to LCDMOVLW Wake_Up_Msg ;Load W with Wake-up message offsetCALL Disp_Message ;and call display message routine

Main MOVLW LCDLine2 ;Send line 2 starting addressCALL LCD_Reg ;to LCDMOVLW Proc_Msg ;Load W with Processing message offsetCALL Disp_Message ;and display it on line 2 of LCD

MOVLW 1 ;Increment Wake-Up counter low byteADDWF Wake_UpL ;using Add instructionBTFSC C ;Check Carry for roll-overINCF Wake_UpH ;and increment high byte if set

MOVF Wake_UpL,W ;Copy Wake-Up counters to LowByte andMOVWF LowByte ;HighByte for BCD conversionMOVF Wake_UpH,WMOVWF HighByte

CALL Bin_BCD ;Convert to BCD

MOVLW Wake_Ups ;Send starting address of wake-upCALL LCD_Reg ;counter to LCDMOVF TenThous,W ;Load W with lower nybble ofANDLW 0Fh ;Ten thousands digit

WDTIMER.ASM - Chapter 18 Example Program

Page 379: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 109Program Pull-Out

References

ADDLW 30h ;Convert it to ASCII andCALL LCD_Data ;display it on the LCD

SWAPF ThouHund,W ;Load W with upper nybble ofANDLW 0Fh ;thousands and hundreds digitsADDLW 30h ;Convert it to ASCII andCALL LCD_Data ;display it on the LCD

MOVF ThouHund,W ;Load W with lower nybble ofANDLW 0Fh ;thousands and hundreds digitADDLW 30h ;Convert it to ASCII andCALL LCD_Data ;display it on the LCD

SWAPF TensOnes,W ;Load W with upper nybble ofANDLW 0Fh ;tens and ones digitADDLW 30h ;Convert it to ASCII andCALL LCD_Data ;display it on the LCD

MOVF TensOnes,W ;Load W with lower nybble ofANDLW 0Fh ;tends and ones digitADDLW 30h ;Convert it to ASCII andCALL LCD_Data ;display it on the LCD

MOVLW LCDLine2 ;Send line 2 starting addressCALL LCD_Reg ;to LCDCALL Delay_5ms ;Add a 20ms pause to see Processing mesgCALL Delay_5msCALL Delay_5msCALL Delay_5ms

MOVLW Sleep_Msg ;Load W with Sleeping message offsetCALL Disp_Message ;and display it on line 2 of LCD

SLEEP ;Sleep until WDT expiresNOP ;GOTO Main ;On WDT wake-up, display next count

Disp_Message ;Copies ASCII data from a look-up table to the current cursor;position of the LCD. Character is loaded with the starting;offset of the message before calling this routine.

MOVWF Character ;Save offset in Character counter

:Get_Char MOVLW HI Message ;Move the High Byte of Message3;location into W

MOVWF PCLATH ;and Move it into PCLATHMOVLW Message+1 ;Move message address + 1 into WADDWF Character,0 ;Calculate offset address andBTFSC C ;see if it overflowsINCF PCLATH ;If so, increment PCLATHCALL Message ;Jump to the data table

IORLW 00h ;RETLW won�t affect flags so use OR toBTFSC Z ;check for end of messageRETURN ;and finish if doneCALL LCD_Data ;If not done, send character to LCDINCF Character,1 ;Add 1 to CharacterGOTO :Get_Char ;Do it again for the next character

Message MOVWF PCL ;W contains low program counter;byte and points to next location;plus Character offset

RETLW �W� ;Wake-up_Msg StartRETLW �a�RETLW �k�RETLW �e�

WDTIMER.ASM - Chapter 18 Example Program

Page 380: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code110

RETLW �-�RETLW �u�RETLW �p�RETLW � �RETLW �#�RETLW �:�RETLW 0 ;End of message 1

RETLW �S� ;Sleep_Msg StartRETLW �l�RETLW �e�RETLW �e�RETLW �p�RETLW �i�RETLW �n�RETLW �g�RETLW � �RETLW � �RETLW 0 ;End of message 2

RETLW �P� ;WDT_Msg StartRETLW �r�RETLW �o�RETLW �c�RETLW �e�RETLW �s�RETLW �s�RETLW �i�RETLW �n�RETLW �g�RETLW 0 ;End of message 3

Delay_5ms ;Delay loop used to initialize LCD

CLRF Counter1 ;Wipe first counterMOVLW 1Ah ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

WDTIMER.ASM - Chapter 18 Example Program

Page 381: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 111Program Pull-Out

References

;XMIT232.ASM v1.2 Last modified on August 31, 1998

;These program subroutines were written for the Sirius microSystems PICmicro;development system. For more information contact Sirius microSystems by phone;at 519-886-4462, or on the Internet at http://www.siriusmicro.com .

;Sirius microSystems provides this software on an �as is� basis, without any;warranty, either expressed or implied. All Sirius microSystems software is;provided for educational use only, and Sirius microSystems does not assume;any liability for damages, either incidental or consequential, arising out of;the application, use, or misuse of any of its software or hardware products.;Sirius microSystems reserves the right, without further notice, to make;changes to any of its software or hardware referred to in this program or;library program in order to improve its function, design or reliability.

;Description

; This program demonstrates software timed RS-232 signal transmission.; The keypad is scanned and whenever a key is pressed, the key return; code along with some text is transmitted through H3, the serial; header. The MAX232 translates the signal on RA.4 to RS-232 levels; after it passes through the serial Transmit/Receive select jumper; (JU5).;; To ensure accurate serial bit timing, use a crystal oscillator and; not a ceramic resonator to generate the processor clock.

;Jumper Settings

; JU2 5VDC internal/external select REG; JU1 Variable DC internal/external select REG; JU3 Processor power select jumper RUN; JU4 EEPROM X8/X16 organization select N/A; JU6 Port A LED output and analog input RA0 OFF; RA1 OFF; RA2 ON; RA3 OFF; RA4 OFF; JU5 RS-232 receive/transmit select TX

;Requirements

; An external RS-232 serial terminal or a computer with an appropriate; connection to the PIC-MDS serial input header (H3). For testing we; used a cable wired as follows:;; Computer DB-25 PIC-MDS; Transmit pin 2 �> H3.3 - Rx; Receive pin 3 �> H3.1 - Tx; Ground pin 7 �> H3.2 - Gnd

Maclib �PF8x.INC� ;Library file for PIC16F84 and PM assembler;Comment this line out for other assemblers

Device PIC16F84,HS_OSC,WDT_OFF,PROTECT_OFF,PWRT_ONID �232T�

;Hardware Equates

ORG 0Ch ;Start of File register area

;Equates required by BIN2DEC.LIB:Hundreds DS 1 ;Hundreds digitTens DS 1 ;Tens digitOnes DS 1 ;Ones digit

;Equates required by KEYPAD.LIB:

XMIT232.ASM - Chapter 15 Example Program

Page 382: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code112

Key DS 1 ;Key return code register

;Equates required by RS232TX.LIB:Counter DS 1 ;Serial bit delay counterBitCounter DS 1 ;RS232 bit counter registerTransmit DS 1 ;Transmit byte storage register

;Other equates:CharCounter DS 1 ;Message character counterCounter1 DS 1 ;Delay counter variableCounter2 DS 1 ;Delay counter variable

ORG 00h ;Start program at Reset Vector

CALL Transmit_Port ;Configure PortA.4 as serial outputCALL KB_Port ;Configure Port B for keypad scanningGOTO Get_Key ;Jump over interrupt vector

ORG 05h ;Program starts after interrupt vector

Include �BIN2DEC.LIB� ;Binary to decimal conversion libraryInclude �KEYPAD.LIB� ;Keypad scanning subroutine libraryInclude �RS232TX.LIB� ;RS232 serial transmission library

Get_Key ;Wait for a key stroke, debounce it and convert it to three;decimal digits.

CALL KB_Scan ;Get Key return codeMOVF Key,0 ;Check Key return codeBTFSC Z ;for no key press (0=no key)GOTO Get_Key ;If no key pressed, try again

CALL Delay ;Wait for key to settleCALL KB_Scan ;Read Key code after settlingMOVF Key,0 ;Read Key code into WCALL Bin_Dec ;and convert to decimal

Convert_ASCII ;Add 30h to offset the BCD numbers into ASCII.

MOVLW 30h ;Load ASCII offset into W andADDWF Tens ;add to Tens andADDWF Ones ;Ones registers to make ASCII numbers

Transmit_Key ;Transmit the word �Key �

MOVLW �K� ;Load W with ASCII code for �K� andCALL Transmit_Data ;send out of serial portMOVLW �e� ;Load W with ASCII code for �K� andCALL Transmit_Data ;send out of serial portMOVLW �y� ;Load W with ASCII code for �K� andCALL Transmit_Data ;send out of serial portMOVLW � � ;Load W with ASCII code for �K� andCALL Transmit_Data ;send out of serial port

Transmit_Num ;Transmit the two key return code ASCII digits.

MOVF Tens,0 ;Load W with ASCII Tens digit andCALL Transmit_Data ;send out of serial portMOVF Ones,0 ;Load W with ASCII Ones digit andCALL Transmit_Data ;send out of serial port

Transmit_Mesg ;Transmit the word � Pressed�, followed by the character;codes for carriage return (13) and line feed (10).

CLRF CharCounter ;Clear message character counterGet_Char MOVF CharCounter,0 ;Get current character count in W

CALL Message ;and retrieve message character

XMIT232.ASM - Chapter 15 Example Program

Page 383: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystems Microchip Code 113Program Pull-Out

References

MOVWF Transmit ;Store returned character in TransmitMOVF Transmit,1 ;and check transmit for end ofBTFSC Z ;message marker by checking ZGOTO Wait ;If message done, wait for key releaseCALL Transmit_Data ;If not, send current characterINCF CharCounter ;Increment the character counterGOTO Get_Char ;and get the next character

Wait ;Wait until the user releases the pressed key.

CALL KB_Scan ;Scan keypadMOVF Key,0 ;Check key for 0BTFSS Z ;And if Z=1 key has been releasedGOTO Wait ;Otherwise, wait for releaseCALL Delay ;Wait for key to settleGOTO Get_Key ;Wait for next key

Message ADDWF PCL ;Offset program counter by WRETLW � � ;to Return Message charactersRETLW �P�RETLW �r�RETLW �e�RETLW �s�RETLW �s�RETLW �e�RETLW �d�RETLW 13 ;Carriage Return characterRETLW 10 ;Line Feed characterRETLW 0 ;End of Message marker

Delay ;Provides a debounce delay for the keypad.

CLRF Counter1 ;Wipe first counterMOVLW 80h ;Load W with timer ConstantMOVWF Counter2 ;for Counter2

:Loop DECFSZ Counter1,1 ;Decrement first counterGOTO :Loop ;256 timesDECFSZ Counter2,1 ;Decrement, second counterGOTO :Loop ;from constant, aboveRETURN

XMIT232.ASM - Chapter 15 Example Program

Page 384: PIC-MDS Training Manual - Carleton Universitynagui/Appnotes/Microchip/PIC/PIC-MDS... ISBN 0-9681220-0-0 (Training Manual) ISBN 0-9681220-1-9 (Teacher’s Reference) Disclaimer of Liability

©1998 Sirius microSystemsMicrochip Code114