a practical course on pic micro-controller operation and applications - volume ii(all)

260
 A Practical Course on PlC Micro Controller Operation and Applications Volume Based on the PIC16F84 Written and Compiled by: DN de Beer - ..

Upload: geovalidus

Post on 17-Jul-2015

389 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 1/260

 

A Practical Course on

PlC Micro-Controller

Operation and Applications

Volume 11

(Based on the PIC16F84)

Written and Compiled by:

DN de Beer

- ..

Page 2: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 2/260

 

First Published: Aug 1995

Second Edition: Jan 1996

Third Edition: Feb 1997

Fourth Edition: Jun 2002

Fith Editiqn: Jul2002

Published at the Cape Technikon, Tennant street, Zonnebloem, Cape Town, RSA.

All copyright and distributing rights are reserved by the author. No part of this book may be

reproduced, in any form or by any means, without the permission in writing ITom the author.

Disclaimer: Much care and effort have been taken in the preparation of this book. These efforts

include the development and evaluation of problem solving methods and listed micro-controller

programs. The author makes no warranty of any kind, expressed or implied, with regard to the

methods or programs on this book. The author shall not be liable in any event of incidental or

consequential damages in connection with, or arising out ot: the furnishing, performance, or the

use of these methods and listed programs.

Page 3: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 3/260

 

Synopsis

These notes form the second and more advanced practical and hands-on

course in PlC micro-controller operation and applications. It follows directly

on Volmne I and covers some of the more complex features and applications

of the micro-controller, such as interrupts, binary mathematics, parallel and

serial port expansion, access to serial memories, programming in C, and alsosome of the special features of the rest of the PlC family.

The course sets off at a relatively high level where the introductory course

ended off. New concepts are introduced and applied in practical tutorials

and exercises. Special programming techniques are introduced and appliedto the section on binary mathematics, where routines are written to pass

parameters to and from sub-routines. This also doubles as an introduction

to the section on programming in C, where parameter passing is common

practice.

An Operating Manual for the PS 16F84 Simulater Program, and also Sample

Batch Files to emulate Intergrated Design Environments for DOS and

WINDOWS operating systems, are included in the last chapter of this book.

xxv

Page 4: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 4/260

 

xxvi

Page 5: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 5/260

 

Table of Contents

Page

Course Description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix

9. Power Conservation, the Watch Dog Timer and Interrupts 297

10. BinaryMathematics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 319

11. Port Expansion and External Memory Devices. . . . . . . . . 357

12. PIC16C84 Micro-Controller Programming in C . . . . . . . .. 387

13. Introduction to the Rest of the PlC Family. . . . . . . . . . . . . . . . .. 495

14. Operating Manual for the PICSIM Simulator Porgram . . . . . . . . . . . . 543

LookupTables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . .. 637

Appendix P: IDE (Integrated Development Environment) Batch Files 627

Rev.S 6/02

DndB

Table a/Contents xxvii

Page 6: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 6/260

 

Notes:

xxviii PlC Micro-Control/er Operation and Applications - Vol. 11

Page 7: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 7/260

 

Course Description

This course intends to be the more advanced instructional and hands-on

training experience in the operation and application of the PlC micro-

controllers. It followsdirectlyon the introductorycourse in Volume I of thisseries. The range covered is trom the concepts of power conservation, the

Watch Dog Timer, the SLEEP mode, interrupts, binary mathematics and

. specialprogrammingtechniques, such as parameter passing to and trom sub-

routines. This also included indirect addressing and the use of pointers in

preparationto a later section on programming in C. Parallel and serial port

expansion is covered with practical examples. Protocols for access to

external serial memory devices for the 3/4-wire and PC 2-wire systems are

introducedand explained. The chapter on programming in C for PlC micro-

controllerswas designedto be used as a reference handbook. It also includesnotes, examplesand exercises based on the Assembler exercises of Volume

I. The other members of the PlC familyare introduced, compared and some

of the special features explained and sutnmarised.

The exercisesand practical assignments in this course are also selected to be

applied directly on the PIC84 Basic Board, Serial Programmer and the

Keyboard and Display Module. A simplified PlC Skeleton Development

Systemis introduced and described in the final chapter. It can, with a little

more effort'trom the user, do almost everythingthat the Basic Board systemcan do.

Course Description xxix

Page 8: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 8/260

 

Prerequisites to the Course

It is assumed that a prospective micro-controller student for this course

should have completed the introductory course successfully, and be well

rehearsed in the writing and application of assembler programs. Manyreferences are made to the exercises and procedures used in that course. It

is also expected fromthe student to apply more imagination and confidencein the cl}oiceof an individual class project.

The Class Tests

Class tests will be conducted in the following format: A relatively simple

problem and a guide to some solution will be given in a story book form.The student must successfully translate the solution into an assembler

program, run it through the Simulator, program the Basic Board, anddemonstrate the fmal result to the invigilator.

The Individual Course Project

As an exercise in the solution of problems using a micro-controller, it is

expected from each student to design and build an individualproject. Thisproject may either be an extension to the Basic Board, or a complete new

design. The complexity of the project should be at a much higher standard

than what was expected from the introductory course. Itmust demonstrate

the student's ability to use the micro-controller to solve a typical industrial

problem. .

xxx PlC Micro-Controller Operation and Applications - Vol. 11

Page 9: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 9/260

 

Formal Course Time Allocations

A fonnal course onVolume II of these noteswill stretch over 16weeks, and

will include and be limited to the following sections of instructional and

practical activities:

Week 1 and 2:

Power saving techniques; the Watch Dog Timer operation and settings; reset

sources of the PIC16C84; the Power Down or SLEEP mode and wake-up

from SLEEP procedures; interrupts and the interrupt sub-routine; interrupt

sources. Revision of Program 11 from Volume I: The Frequency Meter.

Notes: Chapter 9. (p-297 to p-318)

Week3:

Binary addition; byte and multi-byte addition routines; local and global

variables and the SET directive. Practical exercise on A Security Lock on

Standby batteries.-

Notes: Chapter 10. (p-319 to p-330, p-315)

Week 4:

Special programming techniques and indjrect addressing; the use of Pointers

for parameter passing to and from sub-routines; binary multiplication;

multiple-add method of multiplication. Practical exercise on The Hour-Minute Alarm Clock.

Notes: Chapter 10. (p-33 I to p-338)

Course Description xxxi

Page 10: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 10/260

 

Week 5:

Shift-and-Add method of multiplication; negative numbers and binary

subtraction; 2's compliment binary numbers; the SUBLWand SUBWF

instructions;multi~bytesubtraction. Practical exerciseon An Interval Timer.

Notes: Chapter 10. (p-339 to p-347, p-316)

Week 6:

Realising bigger than, equal to and smaller than conditions; multi-byte

comparisons; binary fractions and integer division; the multiple subtract

method for division. Practical exercise onA CashRegister.

Notes: Chapter 11. (p-348 to p-356) .

Week 7:

Parallel output port expansion; parallel outputs; parallel inputs; driving an

externalparallelmemorydevice. Practical exercise onAdding Auto-ranging

to the Frequency Meter.

Notes: Chapter 11. (p-359 to p-367, p-352)

Week 8:

Discussion of individual class project; serial port expansion; accessing serial

inputs and outputs on 3 wires only; serial memory devices;3/4-wirecommunication to serial EEPROM memory devices. Practical assignment on

3-wire Serial Driving of Serial-In Parallel-Out and Parallel-In Serial-Out

Shift Registers.

Notes: Chapter 11. (p-348 to p-378)

xxxii PlC Micro-Controller Operation and Applications - Vol.II

Page 11: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 11/260

 

Week 9:

Practical Test 1; preparation for individual class projects; PC 2-wire

protocol and serial memories. Practical assignment on Serial MemoryAccess.

Notes: Chapter 11. (p-378 to p-386)

Week 10:

Programming in C for PlC micro-controllers; building blocks of a C

program; key words, identifiers, data types, operators, etc. Practical C

programming on exercises I and 2.

Notes: Chapter 12. (p-391 to p-416, p-459 to p-467)

Week 11:

Conditional test and loops in the C language. Practical programmingexercises 3 to 6.

Notes: Chapter 12. (p-416 to p-423, p-468 to p-483)

Week 12:

Arrays, strings, pointers, structures and unions; the look-up table. Practical

programming exercises 7 and 8.

Notes: Chapter 12. (p-423 to p-450, p-485 to p-493)

Week 13:

Preparation for project; introductionto the other members of the PlC family;

comparisons of code memory and RAM size, ports, configuration bits,instruction sets and the Power Control Register.

Notes: Chapter 13. (p-497 to p-520, MicroChip Data Books)

Course Description xxxiii

Page 12: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 12/260

 

Week 14:

.Completion of projects. Special features of the other members of the PlC

family; Timer I and 2; the Capture, Compare and Pulse Width Modulationmodules.

Notes: Chapter 13. (p-521 to p-530)

Week 15:

Practical Test 2. The Analogue-to-Digital Conversion modules; parallel

slave, serial port, Voltage Comparators and LCD Drive modules; thePIC14000.

Notes: Chapter 13. (p-531 to p-541)

Week16:

Demonstration and Evaluation of projects.

xxxiv PIC Micro-Controller Operation and Applications - Vol. 11

Page 13: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 13/260

 

Notes:

Course Description xxxv

Page 14: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 14/260

 

xxxvi

Notes:

PlC Micro-Controller Operation and Applications - Vol.Il

Page 15: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 15/260

 

9. Power Conservation, the Watch DogTimer and Interrupts

Table ofContents

PagePowerConservation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 301

The Watch Dog Timer (WDT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 302

The Three Reset Sources of the PIC16F84 Processor. . . . . . . . . . . .. 303

The Power Down or Sleep Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . .. 304

InterruptsandInterruptSub-Routines. . . . . . . . . . . . . . . . . . . . . . . .. 305

TheINTCONRegister. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 306

The Conditions and Settings of the Interrupt Sources. . . . . . . . . . . .. 30}~

TheExternalInterruptonPinRBO ......................The Timer/Counter Interrupt. . . . . . . . . . . . . . . . . . . . . . . . . . .

The EEPROM Done Writing Interrupt. . . . . . . . . . . . . . . . . . . .

TheInterruptOnChangeofpinsRB4 toRB7 .............

300'63~ "t

310311

TheCompositionof anInterruptSub-Routine. . . . . . . . . . . . . . . . . .. 3)Z!/

Using Interrupts to Wake out of the SLEEPMode. . . . . . . . . . . . . .. 313

Program 12: Updated Security Lock on Standby Batteries. . . . . . . .. 3)6/4

Program13:AnHour-MinuteAlarmClock 315

Program 14: An Interval Timer. . . . . .. . .. . . . . . . . . . . . . . .. . . . .. 31-61 S"

ExternalnterruptGeneratingDevices.. . .. . ... ... 317

Co n c l u s i o n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 17

Rev.5 6/02DNdB

297

Page 16: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 16/260

 

298

Notes:

PlC Micro-Controller Operation and Applications - Vol. II

Page 17: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 17/260

 

Power Conservation, the Watch Dog Timer and Interrupts

Chapter Summary

This chapter deals with some circuit design considerations and options toconserve power, especially when the circuit operates on batteries. Clock

speed and supplyvoltage influences, and also some basic design choices are

.discussed to specifically reduce the power consumption of a system.

The operation, control and the application of the Watch Dog Timer are

discussedto get a program out of an unintentional endless loop or controllerfreeze situation. .

The various reset sources of a PlC processor are covered. A power savingSLEEP or Power Down mode, and how to wake the system up out of the

Sleep Mode are discussed.

The Interrupt sources, the application of interrupts, and also the conditions

and settings to enable these interrupt sources are discussed. The special

behaviourof the processorwhen wakingup out of the Sleep Mode by means

of an interrupt, is also covered.

Special projects included in this chapter are:

* An Updated Security Lock on Standby Batteries

* A Programmable Hour-Minute Alarm Clock

* An Interval Timer

----------------

Ch. 9. Power Conservation. the Watch Dog Timer and Interrupts 299

Page 18: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 18/260

 

300

Notes:

PlC Micro-Control/er Operation and Applications - Vol. 11

Page 19: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 19/260

 

Power Conservation

A micro-controllermayoften operate at a remote location. It may be used in

a situation that cannot be dependant on a normal mains supply, such as a

burglar alarm or a gate access control lock. Here the power will probably be

supplied by a battery. Batteries are expensive, and even re-chargeable

batteriesneed to be recharged andmaintained on a regular basis. One would

therefore try to designa circuit thatwould dissipate the least amountof power

without interfering with its function or efficiency.

The first power conservation factor to investigate is the system clock

frequency. If there are no critical minimum timing prerequisites, the clock

speed can be brought down as low aspossible. The PlC 16F84can work from

and upper limit of 4 or 10MHz, down to almostDC. Iffor example, a cheap

RC oscillator is used to run at 10 kHz (R = 100 kQ, C = 330 pF), then the

quiescent current of the processor will drop by a factor of approximately

10times that of the consumptionat 4 MHz. The lowest frequency that can be

used, will depend on the execution time of the program and how often aspecificmeasurement or hardware interaction need to take place.

The RC oscillator is not very stable for power supply and temperature

variations. If the internal time-keeping is important, then a freely available

standard 32768 kHz crystal can be used as a low frequency source.

The next power conservation factor is the circuit supply voltage. The

PIC16LF84 can operate on any supply voltage between 2 and 6 volt. The

same circuit running on 2 volt would obviously consume much less powerthan one running on the standard 5 volt supply. A limit may be imposed by

the specifichardware used in the circuit. Many standard CMOS devices are

designed for lower voltages, and new low voltage devices are produced

continuously. Lithium batteries are often used to supply these low voltages.

They are relatively expensive, but even if a standard voltage regulator (e.g.

the LM317L), or a series Zener diode is used with a standard battery, the

lower supply across the circuit will still use much less current.

Ch. 9. Power Conservation. the Watch Dog Timer and Interrupts 301

Page 20: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 20/260

 

The design of the circuit can also contribute a great deal to power

conservation. Considerable power can be saved by simple design options:The pull-up or pull-down resistors can be made large. The circuit can be

designed so that the logic levels required to drive the hardware, are at the

levels that require the least current for most of the time. An example is atransistor that should rather be kept OFF formost of the time, and will switch

ON onlywhen it is used for a brief period. Most CMOS devicesuse virtually

no currentwhenthey are in a static state, and only consumepower while they

are switched. It may evenbeworth the extra initial expense to iIicludea few

invertor circuits on the board if it can reduce the power consumption.

If there are some parts of the circuit that need not be used ;tor specific

operations, the power to these circuitsmay be suppliedby anunw::edport pin.

The port pins can supply up to 25 mA each without too much voltage drop.Larger currents can be controlled by a transistor, switched off or on by oneof the port pins.

The Watch Dog Timer (WDT)

Each PIC16F84 processor is provided with an internal Watch Dog Timer.

When enabled, this circuit is designed to give the controller a regular reset.The period is adjustable IToma few milli-seconds up to a few seconds. The

WatchDog Timerreset is used to regain control whena systemmay be stuck

in an endless loop, or a supply voltage glitch has upset the normal operation

of a program. The Watch Dog Timer can be enabled or disabled by the

programming of one of the Configuration fuses. For a specific application,

the Watch Dog Timer must either always operate, or it will always be

disabled. Once a program is running, the Watch Dog Timer cannot be

switched in or out to operate by normal software commands.

The Watch Dog Timer consists of an 8-bit counter. It is driven by its ownon-board RC oscillator. The standard overflow time ITomthis timer is

approximately 18mini-seconds. When this happensduringnormalexecution,

the system will reset and start to execute the program ITomcode address

OOOOh.To prevent a reset during the normal program flow, the Watch Dog

Timer must be reset before the overflow occurs by the Clear Watch DogTimer instruction: CLRWDT. When the system is in the SLEEPmode, the

program will continue executingthe instructions after the SLEEP instruction

when woken up by the Watch Dog Timer.

302 PlC Micro-Colltroller Operation and Applications - Vol.II

Page 21: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 21/260

 

The overflowperiod can be extended by allocating the prescaler to the Watch

Dog Timer in place of the nonnal Timer. This is done by setting the PSA bit

in the OPTION register. It will place the prescaler between the RC oscillator

and the counter. The prescaling factor can be selected by the three least

significant bits of the OPTION register, from a I: 1 ratio up to a 1:128 ratio:

OPTION Bits :1 1 0

000

001

010

o 1 1100

101

1 1 0

1 1 1

Watch Dog Timer1: 1

1: 2

1: 4

1: 8

1: 16

1:32

1:.64

1:128

Normal Timer

1: 2

1: 4

1: 8

1: 16

1:32

1: 64

1:128

1:256

When the prescaler is set for the maximum 1:128 ratio, the roll-over only

occurs at approximatelyevery 2.3 seconds. The prescaler will also be cleared

whenever the Watch Dog Timer is cleared. The timing of the Watch Dog

Timer is controlled by an internal RC oscillator and is unfortunately very

temperature and supply voltage dependant. It cannot be used for accurate

timing applications. (Theprescaler is actually connected as a postscaler, but

that does not make any difference to the operation of the WDT system.)

The Three Reset Sources ofthe PIC16F84 Processor

Three sources of reset can be identified for a PlC 16F84 processor:

* A Power Up Reset

* A Reset from the MCLR pin

* A Reset from a Watch Dog Timer Overflow

The last two reset types can eitherbe given while the processor is in the nonnal

running mode, or while it is in the SLEEP mode. Some bits in the STATUS

register can be used by the software to identify what source created the reset,

and whether the processor was in the sleep mode or if the power was down

before the reset. In all events, after a SystemReset, the Program Counter will

be set to OOOOh,nd the special function registers to their nonnal reset values.

Ch.9. Power Conservation, the Watch Dog Timer and Interrupts 303

Page 22: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 22/260

 

The Power Down or Sleep Mode

As a power conservation feature, the PlC processors can be placed in a Power

Down or Sleep Mode. This mode is initialised by the SLEEP instruction. Then

all the normal activities of the processor, including the system clock, will stop.The current file register and the port output pin values will be maintained.

Various methods may be use~ to wake the processor up out of the Sleep Mode:

* A MCLR pin System Reset

* An Overflow from the Watch Dog Timer

* An Interrupt on one ofthe Interrupt Sources

Two negative active bits in the STATUS register, the Timer Overflow, TO, and

the Power Down bits, PD, can be used to indicate whether the system was

woken up from the sleep mode, or if a normal Power Up reset has occurred.

The transition between the various modes, and the setting of the TO and PD bits

can best be demonstrated by the following sketch:

PO-!I

PD-!

TO»O TO-!

PO»!

TO»!

MCLR

po»oTO-!

PC - OOOOh(Reset)

WDTOverflow

. CLRWDT[TO»! POll!]

tIIbit change

- bit unaltered

SLEEP [TO II ! PO"O]

Next Instruction

Reset Sources for tile PlC

304 PlC Micro-Controller Operation and Applications - Vol. 11

Page 23: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 23/260

 

Interrupts and Interrupt Sub-Routines

In the previous exercises,whenever the p~ogramhad to wait for a condition to

change, a loop was used to repeatedly test the condition until it happens.

Exampleswerea key being pressed, or the timer roll-over flag checked. Only

then will another path be taken, or a specific sub-routine executed. This type

of repeated testing is calledpolling. The processor must operate continuouslyto catch the condition when it is met.

In some programs, where the processor may follow anyone of a number of

paths, these conditional test and branching instructionswill have to be included

in every path. Only this can ensure that the test is done all the time while the

program is running. One may wait until the paths come together again for a

single test, but that may be too late. The SLEEP mode cannot be use, becausethe processor will stop working and can only test the condition after it has

woken up either by the Watch Dog Timer, or a MCLR pin reset. By then the

test condition may have been met a few times, and some missed.

Take the exampleof theminute-second clock exercise. Here the time must be

updated every second. Say one were to include routines to be able to change

the time or set an alarm by means of push-buttons. Then some of the

increments for seconds may be missed while the time or alarm adjustments are

being done. What is required is some way of breaking out of any current pathevery time, precisely at, for example, the end of every second. The time will

then be updated, roll-overs checked, and the higher digits changed accordingly.

When this is completed, the program must return back to the program section

it was busy with before the break.

In such cases, the use of interrupts is essential. They act as if they are normal

sub-routine calls, but activated by a hardware event the moment when it

happens. For a normal sub-routine, a CALL instruction must be placed at a

specific locationin a program. The CALL must also be included every time itis required. Interrupt sub-routines does not need a CALL instruction and can

happen anywhere in the program.

There are 4 interrupt sources for the PICI6F84, listed on the next page:

Ch.9. Power Conservation, the Watch Dog Timer and Interrupts 305

Page 24: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 24/260

 

Interrupt Sources for the PIC16F84:

* A positive or a negative transition on RBO(External Interrupt)

* A Roll-over from the Timer

* A Change of any level on pins RB4 to RB7

* A Done Programming from the EEPROM data memory

Each of the four sources may be enabled or disabled by the setting of one of

four individual interrupt ENABLE bits in the INTCON register. Each source

also has an INTERRUPT flag bit. This bit is set every time the interrupt

condition occurs, whether the interruptwas enabled or not. These bits are alsoin the INTCONregister, except the EEPROM interrupt flag. This flag is in the

EECONl register on Page I.

The INTCON register also contains a Global Interrupt Enable bit, GIE. This

bit can be used to blanket out all interrupts, without changing the

currentsettingsofthe Enable bits.

The INTCON Regjster. (Address OBPage 0)

o

Global Interrupt

RB4-7 Intenupt on Change Flag:

RBO Edge Interrupt Flag:

2 Timer 0 Rollover Intenupt Flag:

3 RB4-7 Change Interrupt:

4 RBO Edge Interrupt:

5 Timer 0 Rollover Intenupt:

6 EEPROM Intenupt Boable:

7

Reset Value: OOOOOOOx

0= NO Intenupt

I = Interrupt

o = NO Interrupt

I=Intenupt

0= NO Interrupt

1 = Intenupt

0=DisabledI =Enabled

0- Disabled

I =Enabled

0= DisabledI =Enabled

0= DisabledI - Enabled

0- DisabledI - Enabled

306 PlC Micro-Controller Operation and Applications - Vol. 11

RBIF

INTF

TOIF

RBIE

INTE

TOIE

EEIF

GIB

Page 25: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 25/260

 

When any intel11lptoccurs and it is enabled, the processor will store the current

Program Counter in the stack, and jump to the intel11lptroutine starting address

at 0004h. The process and timing are the same as for a normal sub-routine call.

In the intel11lptsub-routine the software must test the intel11lpt flags of each of

the possible sources, and give each activated interrupt the attention it requires.

The intel11lptflag must then be cleared by the software. When the sub-routine

is finished, the original program counter is recovered from the stack, and the

~ormal program can continue.

It might happen that the Work Register or some of the other registers contain

some important data when the intel11lptoccurs. When the intel11lpt sub-routine

is executed, this information can be cOl11lpted. Care must therefore be taken at

the beginning of the intel11lpt sub-routine to temporary store the information in

all the registers that may be corrupted. These values must also be restoredbefore the execution returns to the original program. See the data book for

examples to store and retrieve the W and gTATUS registers, using the SWAPF

instruction, that does not alter the STATUS flags.

In programsectionswhere the normal execution timing is critical, or if it is not

so easy to take care of all the possible bytes that may be corrupted. The

interrupts may have to be disabled temporarily. This can be done by either

clearing the specific interrupt enable flags, or a blanket disabling of all the

intel11lptscan be accomplished by clearing the global GIB bit.

The priority of which interrupt to serve first when two or more interrupts

happen at the same time, will depend on how the intel11lpt sub-routine is written

and what flag is tested first. Each intel11lpt flag must therefore be tested in turn.

When set and enabled, a service sub-routine must be executed.

That bringsone to the problem of whatwill happen if another intel11lpthappens

while the processor is busy servicingone intel11lpt,or the same intel11lptsource

gives another interrupt before the current sub-routine is done. It will requirecareful and complex testing not to corrupt any important data in these second

level intel11lpts.What the controller does in stead, is that the GIE bit is cleared

automatically by the hardware when the interrupt sub-routine is activated the

first time. Thiswillprevent any other sources from creating an interrupt, even

when their intel11lptflags are enabled and triggered. When the sub-routine is

finished,the program must return to normal execution with the special Return

from anInterrupt instruction,RETFIE. This will automaticallyset the GIB bit,

and allow other interrupts to occur and be serviced.

Ch. 9. Power Conservation. the Watch Dog Timer and Interrupts 307

Page 26: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 26/260

 

To prevent the same interrupt to be activated again when the GlE bit is set by

the RETFIE instruction,it is important to clear the individual interrupt flagby

software every time the specific interrupt is being serviced. If the same

interrupt occurswhile the interrupt routine is being executed, then the interrupt

flag will be set again. The :;econd interrupt will then occur and be servicedafter the RETFIE instruction has set the GIE bit.

Take an,exampleof a complex timer that keeps track of 1/1OOOthsof a second,

up to hours, days, months and years. The timer gives an interrupt every1/ IOOOthof a second to update the clock. If the date and time were

23:59:59.999 on the 28th of February of a leap year, a rather complex set of

instructionswill have to be done to take care of all the roll-overs, and to test if

the current year is a leap year or not. The next date can either be the 29th of

February, or the 1st of March. Such a set of instructionsmay take more than1/1000ths of a second to execute, so the next interrupt from the same source

may happen before the current interruptsub-routineis finished. ID,hiscase, the

interruptbit mustbe cleared soonafter entering the interrupt sub-routine. The

second interruptmay then set this bit before the end of the interruptsub-routine.

When returning to the main routine, another interrupt CALL' will happen

immediately. The updating of the clock will happen a little later, but no timewill be lost.

If the set of roll-over tests in the previous example takes more than two

1/1000thsof a second, the second interruptwill be lost. It such cases, one may

even consider to enable the GIE bit inside the interrupt sub-routine, and allow

the second interrupt to occur as soon as the seconds part of the timer has been

updated. The second interrupt service will be short. It only has to increment

the 1/1000digit by one withHOroll-overs. Whenthe program returns from the

second interrupt, it can continue to update the other digits in its own time. A

second and a third interrupt can take place, without losing any time whileupdating the rest of the digit values.

The Conditions and Settings of the Interrupt Soul-ces

The External Interrupt on Pin RBO

Apart from the normal I/O functions of the RBOpin, this pin can also be used

as an external interrupt source. The INTEDG bit in the OPTION register is

used to select if the interrupt must be generated on the falling edge of the pin

level when INTEDG = 0, oron the risingedge,whenINTEDG= 1. Foran

308 PIC Micro-Controller Operation and Applications - Vol. 11

Page 27: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 27/260

 

interrupt to be activated on the falling or rising edge of an external signal on

port pin RBO,the pin must be set to be an input, the GIE and the INTE bits in

the INTCONregistermust be set. The INTF flag in the INTCON registermustbe cleared as well.

A servicesub-routineto test if the INTF flagwas set must be placed at address

0004h. This service sub-routine must either clear the interrupt flag to allow a

similar interruptagain, or the enable flagmust be cleared to prevent any further

interrupts from this source. The interrupt sub-routine must return to nonnal

execution by using the RETFIE instruction in place of the nonnal RETURN.

It will set the GIE flag and allow interrupts from the same or other sources to

happen.

The interrupt sub-routine may also be forced by a software instruction, bysetting the INTF flagwhile the interrupt is enabled.

The following sequence of instructions should be executed to allow an external

interrupt:

a) Set the RBOpin to be an input.

b) Selectthe level directionInterruptEdge bit, INTEDG, in the OPTION register.

c) Clear the INTF flag in the INTCON Register to prepare for the interrupt.

d) Set the INTE bit in the INTCON Register to enable the interrupt.

e) Set the GIE flag in the INTCON Registe~ to enable any interrupt.

The Timer/Counter Interrupt

The Timer/Counter will generate an interrupt when the count rolls over from

FFh to DOh. The timer source may either be the internal system clock or an

external source. The GIE bit and the TOIEbits in the INTCON register must

be set, and the TOIFflag must be cleared.

A similar test and service routine, such as used for the external interrupt on pin

RBO, must be included. It must also clear the TOIF flag if a subsequent

interrupt must be detected.

Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts 309

Page 28: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 28/260

 

The following sequence of instructions should be executed to set a timer or

counter interrupt:

a) Clear or set the Timer (and Prescaler) to prevent an immediate roll-over.

b) Clear the TOIFflag in the INTCON Register to prepare for an interrupt.

d) Set the TOIEbit in the INTCON Register to enable the interrupt.

e) Set the GIE flag in the INTCON Register to enable any interrupt.

The EEPROM Done Writing Interrupt

When data iswritten to the EEPROMdatamemory, it will take approximately

10 milli-seconds before another instruction involving the EEPROM can be

executed. If timing is not critical, then the program can use a delay to wait for

10 to 12milli-seconds before continuing. Another option is to test the EEIF

flag continuouslyuntil it is set. That will indicate the EEPROMwrite cycle is

complete. The third option is to let the program continue with other routines

and only return with an interrupt when the write cycle is complete and the

interrupt flag is set. To activate an interrupt ITomthe EEPROM, the GIE andEEIE flags in the INTCON register must be set, and the EEIF flag in theEECONI register must be cleared.

A Similar test and service routine, such as used for the other inteJTUptsources

must be included. The EEIF flagmust also be cleared if another interrupt mustbe detected later.

The following sequence of instructions should be executed to set a Done

WritingInterrupt for the EEPROM data:

a) Clear the EEIF flag in the EECONl Register to prepare for the interrupt.

b) Set the EEIE bit in the INTCON Register to enable the interrupt.

c) Set the GIE flag in the INTCON Register to enable any interrupt.

----------------310 PlC Micro-Controller Operation andApplications - Vol.Il

Page 29: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 29/260

 

The Inte""pt On Change of pins RB4 to RB7

Pins RB4 to RB7 each has an additional data latch connected to the input pins.

Every time the port is read, the current values are stored in these latches. As

soon as anyone of the pin values changes to be different from the previous

latchedvalue, the TBIF flag will be set. An interrupt trom this source will be

"generatedif the GIE and RBIE bits inthe INTCONregister are set. Before the

RBIF flag is cleared, the pin values must first be read to make the latched

values the same as theport pin values. Only pins set to be input can generate

this interrupt.

The following sequence of instructions should be executed to set an Interrupt

on change of any of the RB4 to RB7 pins:

a) Set the appropriate RB4 to RB7 pins to be inputs.

b) Read Port B to latch the current pin values into the input compare registers.

c) Clear the RBIF flag in the INTCON Register to prepare for the interrupt.

d) Set the RBIE bit in the INTCON Register to enable the interrupt.

e) Set the GIE flag in the INTCON Register to enable any interrupt.

The Compositionofan Interrupt Sub-Routine

In a system with multiple interrupt sources, of which the service timing of some

of the sources are critical, the interrupt sub-routine must be put together with

great care. It must cater for all possibilities, so that all interrupts are servicedin time, and no interrupts are lost.

First, the priorities of the interrupts must be decided. The most important or

critical interruptmustbe serviced first. One must also look at the time between

interrupts trom the same source, and also the shortest and the longest time the

servicingof an interrupt in the sub-routinemay take. Some important factors to

keep inmindwhen composing an interrupt service sub-routine, are emphasised

onthe next page:

Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts 31/

Page 30: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 30/260

 

* The inten-upt servicing routine must start at address 0004h in the code memory

with a suitable jump-over instruction from the reset address at OOOOhn the main

program.

* If the inten-upt can happen from anywhere in the main program, the WorkRegister value at the moment of inten-upt can be important. It must be saved in

some temporary storage, and be retrieved just before returning from the inten-uptservice routine.

* If the exact timing of an external inten-upt is important, the timer value must be

read and stored as soon"as possible after entering the inten-uptservicesub-routine.

* In some cases, where a second inten-upt can happen before the specific inten-uptis serviced, Le. the second inten-upt is requested while the inten-upt flag is still

set, the entire INTCON register must be stored at the beginning of the inten-upt

sub-routine. The appropriate inten-upt flags in the INTCON register is then

cleared. The individual inten-upts can now be serviced according to the stored

INTCON values, while the INTCON is ready to latch in and register any second

inten-upts. After the RETFIE instruction, the inten-upt flags set, will create a

second inten-upt.

* The inten-upt flag of the highest priority inten-upt must be tested fir~t. If it is set,

the service routine of that inten-upt must be executed as soon as possible.

* All the inten-uptsusedmay not alwaysbe enabled duringthe entire execution of

the main program. Some of the inten-uptsmay be disabledduring someparts of

the program. Then the Enable flag of an inten-uptmust also be tested in the

inten-upt sub-routine, before a specific inten-upt is serviced. From within theinterrupt sub-routine, one would not know from where in the main routine the

inten-upthappened. Here the Enable flag will show if a specific inten-uptmustbe serviced at that stage of the program, or not.

* Once inside a specific inten-upt service routine, the inten-upt flag must be cleared

as soon as possible. It can then capture a second inten-upt from the same source

if it happens while servicing this, or any of the other interrupts. Once the entire

interrupt sub-routine is done, and one returns to the main prOlI"am with the

RETFIE instruction, the GIE bit will be set. If a second inten-upt has happened,

the program will inunediately jump into the inten-upt sub-routine again and

service the new interrupt.".

312 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 31: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 31/260

 

* The time taken to complete an interrupt sub-routine can be quite long. An

example is the time-date roll-over tests right up to leap years, discussed before.

Here one may consider enabling the GIE bit from within the interrupt

sub-routine. Onewould in effect allow an interrupt sub-routine call from within

itself. Hopefully,the second interrupt sub-routine executionwill be a short one,

else one could have another interrupt before the second interrupt is fmished.

This would soon run into stack overflow problems.

* Before returning to the main program, all the interrupts that were enabled and

triggered, must first be serviced. The appropriate interrupt flags must also be

cleared. If not, the program will continuouslycall the same interrupt sub-routine

directly after it returns with the RETFIE instruction that clears the GIE bit.

Using Interrupts to Wake out of the SLEEP Mode

Interrupts can also be used to wake the processor out of the sleep mode. Say the

processor is used as a battery powered security lock at a door. A specific code

must be entered through the keypad to allow access. While waiting for hours or

days before someone may want to open the door, the processor can be placed in

the sleep mode to conserve batteries. The other option is to continuously test the

keyboard at a break-neck speed of Mega Hertz for days on end, waiting forsomeone to (please!!) press some button.

To wake the processor out of sleep though an interrupt, the appropriate interrupts

must be enabled and the interrupt flags triggered in the normal way. The setting

of the GIE flag before the SLEEP instruction will determine what the processor

will do when it wakes up. This is also illustrated on the sketch below:

* If the GIE flag was cleared (Interrupts Disabled) before the processor went into

the SLEEP mode, the program will continue with the instruction just after the

SLEEP instruction. It can therefore be used as a point where the program will

stop and wait until the interrupt is triggered. The specific interrupt enable bit

must be set and the interrupt flag cleared beforehand. If not, the processor will

not stay in the SLEEP mode.

Ch. 9. Power Conservation. the Watch Dog Timer and Interrupts 313

Page 32: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 32/260

 

*If the GIE flag was set (Interrupts Enabled) before the processor went into the

sleep mode, the processor will execute only the one instruction directly after the

SLEEP instruction(it canbe a NOP), before it willjump to do a normal interrupt

sub-routine. There it will test which source or sources generated the interrupt

and service the interruptsasusual. After the interrupt sub-routine, the programwill continue with the second instruction after the SLEEP instruction.

PC - OOOOh(Reset)

PC = 0004h (Interrupt)

j

RETFIE

Execute

SLEEP[TO» I'PO»OjI st Instruction

Onlv if GIE=I

2nd Instruction

!

2nd Instruction after

RETFIE or if GIE =O.

Wake upfrom Sleep by alllllterrupt

The timer or counter cannot be used as a SLEEP mode wake-up source. The

internal clock and synchronising circuits are all disabled during the SLEEP

mode. The PIC16F877 for example, has an additional timer that can be driven

from an independent external source. This timer can wake a system up from

sleep when a roll-over occurs.

Program 12: Updated Security Lock on Standby Batteries

Alter Program 10, the Programmable Security Lock, so that after a system resetor after access was granted for 4 seconds, the processor must go to sleep. This

must happen only after setting up the correct logic levels on to the keyboard to

allow for any RB4 to RB7 interrupt on change. As soon as any key is pressed,

the processor must wake up. It must then read and display the key value as the

first number of the secret code to be entered. The rest of the keys can be

entered. If a next key is not pressed within 10 seconds, the system must go backinto the SLEEP Mode.

314 PlC Micro-Control/er Operation and Applications - Vol.II

Page 33: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 33/260

 

Program 13: An Hour-Minute Alarm Clock

Design an Hour-Minute Alann Clock that will make use of the timer and

prescaler to time out a full count (65536) before an interrupt is given. In the

interruptsub-routine,another two-byte counter must be decremented to time outI minute, together with the required delays to compensate for accuracy. This

may include a specific preset value loaded into the timer for the final round

~efore the minute digit is updated. The time must be updated internally even

while one of the following adjustment settings are in progress:

If one of the non-numericalkeys, say 'C' is pressed, the system must go into the

Set Clock mode, and the most significant timing digit must flash. A numerical

key can then be pressed to change the digit. If the Set Clock key is pressed

again, then next digit must flash, etc., in a circular fashion.

When another non-numerical key, say 'A' is pressed, the Set Alarm mode must

be selectedand updated in the same fashion as the timing digits. Another key,

say D', will return the system back to the normal Display Clock Mode.

If the alann and the time settings are equal, the alarm must be switched on for

1 minute. This can be indicated by the least significant decimal dot in the

display, and pin RA4 must also be taken low to be able to drive an external

alarm.

Another non-numeric key, say 'F, can be used to cancel the alann before theminute is over.

Program 14: An Interval Timer

Based on Program 11, the Simple Frequency Meter, include the features of an

interval timer in the hardware and software. The main difference between aFrequencyMeter and an Interval Timer, is that the Frequency Meter counts the

externalpulses between afIXed period, while an Interval Timer time the periodbetween two external events.

The timing resolution of the Timer at 4 MHz is 1 micro-second. Only three

display units need to be used, so the smallest range available will be 1 to

999 micro-seconds. The other digit and the decimal dots can be used to indicatethe units.

Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts 315

Page 34: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 34/260

 

To indicate that the Interval1;imer, Lp.o. the FrequencyMeter is in operation,

the left hand side digit can be used for the units. Six ranges, from .100msec upto 99 seconds canbe included,with a seventhrange as an externalevent counter.

The ranges, display digits and unit symbols can be as follows:

Range

o1.23456

Period Symbol, Dot & Display

u 999

m 9.99

m 99.9

m 999

t 9.9 9

t 9 9.9

1 Ils - 999 Ils

lOllS - 9.99 ms

100 Ils - 99.9 ms

1ms- 999ms10 ms - 9.99 sec

100 ms - 99.9 sec

o - 999counts c c c c

The hold timemust be adjustable from 0.5 to 5 seconds, and the range selection

must either be Manual- or Auto-Ranging, selectable by the push buttons.

Another input variable is the level of the external source to start-and end the

timing period. They are shown below:

These selectionsmust bemade by some other combinationsof the push-buttons.

One may, for example, use one button to select a Mode, in circular fashion,while two buttons do the UP or Down selections for each mode. The fourth

button can select betweenFrequencyMeterMode or Interval TimerMode. The

PD bit in the status register allows one to toggle between the Frequency andTimer modes on every MCLR reset. The PD bit stays the same after a MCLR

reset. The bit is toggled and tested. On power up, (pD = 1), the instrumentwill

be aFrequency Meter when PD becomes O. After a MCLR reset, PD will still

be O. After toggling PD, the the circuit will become an Interval Timer. After

another MCLR reset the circuit will become a FrequencyMeter again.

An external Phase Lock Loop can be used to dynamically multiply a low

incoming frequency to get itbigger count value for a shorter gate period.

316 PlC Micro-Control/er Operation and Applications - Vol.II

Start End Measuring

Intput: t Input: t Period

Intput: t Input: Interval

Intput: Input:. Inverse Interval

Intput: Input: Inverse Period

Page 35: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 35/260

 

External Interrupt Generating Devices

An external timing device, such as the Watch Dog Timer from Dallas, can be

used to generate pulses at regular intervals to wake up the PlC to do whatever

ithas to do. The device dissipates very little power. It can be set to give regular

pulses every second, every minute or every hour, or once a day or once a week

at a specifictime. To drive the IC, one need 8 data lines, six address lines, andalso as somecontrol lines. Similar serial access external timer devices are also

available that require less data and control lines.

Conclusion

To drive external hardware, such as one of the multi-control pin devices in theprevious paragraph, the 13port pins ofthe PIC16F84 fall a little short. A later

chapter will deal with the expansion of the output ports to drive multi-pin

external hardware in the parallel mode. It also covers user RAM memory

expansion in both the parallel and serial modes.

The next chapter will cover binary mathematics and the use of indirect

addressingand addresspointers to be able jo write flexiblegeneral purpose sub-

routineswithparameter passing to and from these sub-routines. Somemethods

to conservememory and re-use variable addresses will be discussed.

Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts 317

-.

Page 36: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 36/260

 

318

Notes:

PlC Micro-Control/er Operation and Applications - Vol. 1/

Page 37: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 37/260

 

10. Binary Mathematics

Table of Contents

Page

Chapter Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 321

BinaryAddition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 323

ByteAddition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 324

ATwo-ByteAdditionRoutine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 325

Multi-Byte Addition using Local and Global Variables. . . . . . . . . . .. 328

TheSETDirective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 329

The Use of Pointers for Multiple Indirect Addressing. . . . . . . . . . . .. 331

Bina ryMu l t i p l i c a t i on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

The Multiple Add Method of Multiplication """""""""" 338

The Shift-and-AddMultiplication Algorithm. . . . . . . . . . . . . . . . . . .. 339

Binary Subtraction and Negative Binary Numbers. . . . . . . . . . . . . . .. 344

Subtracting 2's Complement Binary Numbers. . . . . . . . . . . . . . . . . .. 346

Subtract W from Register or Literal Values, SUBWF and SUBLW .. 347

AddingandSubtractingofPositiveandNegativeNumbers. . . . . . .. 347

Multi-ByteSubtraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 347

(Continued )

Rev.5 6/02

DNdB

319

Page 38: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 38/260

 

Table of Contents (Continued..)Page

Realising Bigger Than, Equal To and Smaller ThanConditions. . .. 348

Multi-ByteComparisons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 350

Program 15: A Cash Register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 351

Program16: AddingAuto-Rangingo theFrequencyMeter. . . . ... 352

Binary Fractions and Integer Division. . . . . . . . . . . . . . . . . . . . . . . .. 353

Micro-Processor Division Algorithms. . . . . . . . . . . . . . . . . . . . . . . .. 353

The Multiple Subtract Method for Division. . . . . . . . . . . . . . . . . . . .. 354

Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 355

-------------------

320

Page 39: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 39/260

 

10. Binary Mathematics

Chapter Summary

The basic procedures to add, subtract, multiply and divide in the binarysystemare similar to the procedures used for the decimal system. The maindifference is that there are only two count symbols in the binary system, as

.opposed to the lOin the decimal system.

In amicro-controllerthesemathematicaloperationsare done in byte units, Le.

a numberingsystemwith a base of256. A very close correlationbetween the

binary system and this byte system exist~. The binary system uses I bit at a

time, whilethe byte systemoperates on 8 bits simultaneously. To be able to

predict the answersto themathematicaloperations of the micro-controller,themethods used for binary calculations by hand, will first be revised.

Various methods or algorithms for the mathematical operations will be

covered. Single and multi-byte addition, multiplication and subtraction will

be covered using various methods. Division will be limited to integer

division and themultiple subtraction method only. Integer division is where

the answer will result in an integer answer and an integer remainder.

The use of Local and Global variables and the SET directive will be used toeconomiseon the number of RAMbits required for a program. Pointers will

be explained and used to transferparameters to and trom sub-routines. These

pointers are used to increase the flexibility of standard sub-routines.

Useful methods for the comparison of multi-byte Bigger Than, Equal To and

Smaller Than equations will also be discussed.

Specific projects covered in this chapter are:

* A Cash Register

* Adding Auto-Ranging to the Frequency Meter.

-------------------

Ch.10 BinaryMathematics 321

Page 40: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 40/260

 

322

Notes:

PlC Micro-C011troller Operation and Applications - Vol. 11

Page 41: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 41/260

 

Binary Addition

To do decimalsystemadditionby hand, the two numbers to be added will be

placed on top of one another. One will start the addition at the least

.significantdigits. If the sum is equal or bigger than 10d, 10will be subtracted

fromthe answerto leave the rest as the least significant answer. One unit of

tens will be carried over to be added to the next significant digit.

Binary addition is done in a similar way. Here the roll-over limit is 2. The

possible answers for the sum of two binary bits, can be only 0, 1 or 2. When

the sum is 2, 2 is subtracted to leave 0, and one unit of 2's must be carriedover to the next significant digit. For the addition of the next digit, that

consists of the two bits plus a carry, the answer can be 3 as well. Then onemust subtract2 from 3 to leave 1, and take a carry over to the next significant

digit.

A very important aspect to always keep in mind when doing mathematical

operations in micro-controllers, is the byte space required by the numbers.On paper there will normally be sufficient space to extend to the left-hand

side if the answer gets bigger. In micro-controller systems, however, one

must alwaysbe prepared for the biggest possible answer, and allow sufficient

space in the form of open bytes.

For binary addition, the biggest possible answer one can get from the sum of

two binary numbers, is one bit bigger than the biggest original number.

Ch.IO Binary Mathematics 323

Example:

Number I: 1 1 0 1 1 0 0

Number2: 0 1 1 1 0 1 0

Halfsum:

°j IjOjljljOarries: 11 11 0 0 0 0

Total: 1 0 1 0 0 1 1 0

Page 42: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 42/260

 

Byte Addition

The instructions for addition used inmicro-controller systems add 8 bits of

two bytes together simultaneously. It takes care of all the intermediate bit

carries automatically. When a carry is generated by the addition of the twomost significant bits, it will set the Carry flag of the Status register to 1. Ifthere is no carry, the C bit will be cleared.

If the size of the original two numbers canbe any value that can fit into 8 bits,

then size of the biggest possible answer is one bit longer that one byte.

Therefore, the space required for the answer must be at least two bytes long.

Only when one is sure of the limits of the length of all the possible answers

that no carry will be generated, one byte of space may be sufficient.

This brings one to the situation of what will then happen if the original

numberswere two ormore bytes long. The maximum space required for the

answer will still be one bit more than the biggest of the two bytes. The

micro-controlleruses bytes only. The byte sizes of the numbersmustbemade

equal, filling the higher byte!;with zero's, and the answer byte sizemust be

one byte more than the size ofthe numbers. .

The procedure or algorithm to add two 2-bytes numbers together, is the sameas in the decimal or the binary systems: First add the two least significant

bytes and store the answer. A carry may be generated and provision must be

made in the algorithm that it can be carried over and added to the sum of the

next two bytes. The next two bytes, together with a possible carry, are then

added, and the answer stored. If another carry is generated, it must be placed

in the third byte of the answer section.

A program to do this additionmustbewrittenso that the size ofthe two initial

numbers may be any value ftom the smallest, up to the biggest possiblevalues. It must also take care of any possible carries. rtere are twoinstructions that can be used to do mathematical additions in the PlC

instruction set:

The Add a File Register Byte or a Literal to W, ADDWF and ADDLW: The

first instruction also requires a destination operand. It can either be the Work

Register or the File Register. The other register stays unaltered. For the

second instruction, the literal value is specified in the code, and the answer to

the addition will always be stored in the Work Register.

324 PlC Micro-Controller Operation and Applications - Vol. 11

Page 43: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 43/260

 

Examples are:

ADDWF PORTB,f

ADDFW PORTB,wADDLW 23

;Add Port B to w and store back to Port B.

;Add Port B to w and store in w;Add 23 to w and store in w

.If the sum is bigger that 255, the Carry flag will be set. If the sum is not

bigger than 255, the Carry flagwillbe cleared. If the sum of the values in the

two least significantnibbles is bigger than D'15', the DC or Digit Carry bit in

the StatusRegisterwill be set. The bit will be cleared if not. The Z flag will

be set if the result of the operation is a zero byte, or cleared ifnot.

A Two-Byte Addition Routine

To add any two byte number to another two byte number, and get a maximum

possible answer of a three-byte number, the same recipe or algorithm is used

as for adding two decimal digits. The only difference is that the roll-over for

each decimal digit is D'10', while for byte addition it is 256.

Say the one byte is saved in the variable NUMA (LSByte) and NUMA+ 1.

The other number is saved inNUMB and NUMB+1, and the answer must bestored in SUM,SUM+1 and SUM+2. The two-byte addition algorithm willbe as shown below:

Two-Byte Addition Algorithm:

1. Clear the answer bytes of any previous answers.

2. Move the lower byte of the one register, NUMA, into w.

3. ADD the other byte, NUMB, to w, with the destination ofw.

4. Store the answer in the lower answer byte, SUM.

5. If the carry was NOT set, skip to 7.

6. Increment answer byte two, SUM+1, Le. form cleared to 01h.

Ch.lO BinaryMathematics 325

Page 44: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 44/260

 

7. Move the higher byte of the first number, NUMA+l, to w.

8. ADD the higher byte ofthe sum, SUM+!, with the destination f.

9. If the carry was NOT set, skip to 11.

10. Increment answer byte num~er three, SUM+2.

11. Get the other byte, NUMB:+-l,into w.

12. ADD the higher byte of the sum, SUM+1,with the destination t

13. If the carry was NOT set, skip to 15.

14. Increment answer byte number 3, SUM+2

15.Exit.

Note there are two possible places where a carry may be generated by the

second byte addition at steps 9 and 13. Only one of the two will happen: If

the one value was FFh, then the addition of a previous carry will result in

1DOh,hat will generatea carry. The subsequent addition of even the largest

other byte value cannot generate another carry (00 + FF= FF).

The other possibility for a carry is when the sum of the two bytes is bigger

than 255, then a normal carrywill be generated (FF + FF = IFE). A previous

carry cannot cause another roll-over (FE + I = FF).

Only the address of the lea~t significant byte of each number need to be

defmed. Any higher bytes can be referred to as the base address plus an

offset, e.g: NUM+ I. The assembler will do the offset calculation duringassemblytime and place the correct address in the instructions. 'Thenormal

convention for placing multi-byte numbers inmemory, is to place the least

significant byte first, followed by the rest of bytes in order of ascendingsignificance and address values.

Assume the base addresses, the bytes containing the original numbers, andalso the base address of the answer bytes has been defined beforehand. The

conversion into assembler instructions ofthe above algorithmwill generate

a sub-routine shown on the next page:

326 PlC Micro-Control/er Operation and Applications. Vol. Il

Page 45: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 45/260

 

;TwoByte Addition Sub-Routine (ADD.ASM)

ADD CLRF SUM

CLRF SUM+I

CLRF SUM+2

MOVF NUMA,w

ADDWF NUMB,wMOVWF SUM

BTFSC STATUS,C

INCF SUM+I,f

MOVF NUMA+l,w

ADDWF SUM+I,f

BTFSC STATUS,C

INCF ANSW+2,f

MOVF NUMB+I,w

ADDWF SUM+I,f

BTFSC STATUS,C

INCF ANSW+2,f

RETURN

;Clear the answer bytes

;Get the lower byte of A

;Add the lower byte ofB to w;Store the answer

;Skip if no cany was generated

; else add I to the next higher answer

;Get the higher byte of A in w

;Add the sun and store.

;Skip if no cany was generated

; else add I to the next higher answer

;Get the higher byte B in w

;Add the sum and store.

;Skip ifno cany was generated

; else add I to the next higher answer

;End

Identification of Instruction Sub-Sets to Create a Loop

Note that the instruction sets for adding the two higher bytes to the sum are

exactlythe same. The only difference is the bytes being used. The addition

of the sum to thehigherbyte ofNUMA will capture a possible carry from the

previous addition, and could generate a cany itself. This part was not

required for the low bytes, because there was no previous cany.

The same set of instructions could be used and the same results obtained for

the low bytes, provided the sum was cleared initially. Adding a cleared SUM

byte will give the same answer and no cany will be generated. The aim is to

make the instruction sets for the higher and lower bytes similar. Then one can

use the same set of instructions for adding all the bytes in a loop. Only theaddress references of the instructions are different. These address references

must be incremented by one for every next significant byte addition.

Ch.IO Binary Mathematics 327

Page 46: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 46/260

 

Eventually, the same routine may be used to add any number of bytes to any

other equal number of bytes. All that need to be specified are the least

significant byte addresses of the two numbers and the answer. Also required

is the number of bytes that need to be added. The increme}!tingof byte

addresses can be achieved by indirect addressing in the FSR register.

Multi-~yte Addition using Local and Global Variables

The change in the instruction set required for the addition of the least

significant bytes have been discussed already. What must still be done to

achieve a multi-byte addition sub-routine, is to make the addressing modes

indirect. Then the addresses can be incremented by one for every loop. A

loop counterwill also be needed. It will be used to initiallyclear all the answerbytes, and then to countout the number of bytes that must be added in a loop.

Only one register, the FSR, is'availablefor indirectaddressing. One will need

at least three indirectaddress registers, two for the initialnumbers,and one for

the answerbytes. To solve the problem, the address referencesmust be stored

temporarily in RAM. They are only moved into the FSR when required. All

moving must be done through the Work Register. The value in the Work

Register may be significant before the move, so it may also have to be stored

temporary and recovered after the move.

All these additional variables that must be defmed and used,may sound a bit

complex, but in this way the routine can be made flexible to add any two

numbers of any lengthand stored at anyplace inmemory. The answercan also

be stored at any place in the memory. As a summary, the following variables

must be defmed before the multi-byte addition sub-routine is entered:

Start Address of the first number, NUMA

Start Address of the second number, NUMB

Start Address of the answer, SUM

The count value for the number bytes to be added (stored in W)

Inside the sub-routine, one also requires the following variables:

Loop counter, COUNT

Temporary storage fo~W, TEMPW

328 PlC Micro-Controller Operation andApplications - Vol. 11

Page 47: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 47/260

 

It appears that a great deal of a memory is being used up just to store

references and counters. When the routine is completed, these memory

locations can be freed to be used by other routines. All the variables are

therefore local variables and only used in the add sub-routine and the calling

routine. Globalvariables, on the otherhand, are variables that will be used intwo or more routines, and the values must be kept when the routines are

fmished. By defining some variables as local, and other as global, more

.effective use can be made of the limited RAM bytes available for the

PlC 16F84. That will prevent the danger of over-writing significant data in a

variable by another routine.

Before continuingwith this section, another directive, the SET directive, must

first be explained. It will be helpful in the declarations and the effective use

of memory space for local and global variables.

The SET Directive

The SET directive has the same function as the EQU directive, except that the

SET variable values may be changed in the program. EQU directives must

stay the same throughout a program. Global variables must therefore be

defined at the top of the program with the EQU directive, while local variables

can be defined by the SET directive at the beginning of each the programming

module. Their values can be discarded or corrupted when the section is done.

Other local variables may then re-use that memory location. That will save on

the total space required by variables.

Variables must be defined to be between file addresses OCand 4F (68 RAM

bytes availablefor the PlCI6F84), The global variables can be defmed by the

EQU directive, form OChupwards, as was done before. Local variables can

be placed from 4Fh downwards. To make the allocation of local variableseven more simple, a sufficient number of unused RAM locations can be

defmed by the EQU directive as LOCALI, LOCAL2, LOCAL3, from 4Fh

upwards.

At the beginningof each sub-routine, the local variables are then allocated to

the local variable space using the SET directive to tie the name of the firstlocal variable to LOCALl, the second to LOCAL2, etc. The same locations

canthen be used by redefining the new local variables with the SET directive

at the beginning ofthe other modules or'sections.

Ch.lO BinaryMathematics 329

Page 48: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 48/260

 

Any address may have more than one Symbol. The Symbolswill be replaced

by the address valuesduring assembling time. A Symbol, however,may only

refer to one address at a tim~.

At the beginning of the program the local variable space is defined by the EQUdirective as follows:

LOCALI EQU

LOCAL2 EQULOCAL3 ...

4F

4E

In a sub-routine, local variables are defmed using meaningful names that are

applicable to this routine only by the SET directive:

COUNT

TEMPW

SET

SET

LOCALI

LOCAL2

One may define the local variable addresses directly in the SET directive as

4Fh, 4Eh, etc. but the method above will make the allocation ~f space forvariables flexibleto move the globaland local variables aroundin the available

memory space to suit specific requirements. It needs only to be done once at

the top of the program, without having to go through the whole:program to

correct each SET directive for local variables for every sub-routine or section.

If the FSR, EEADR and EEDATA registers are not specifically used in a

routine, they may also be used as temporary storage of local variables.

330 PlC Micro-Controller Operation andApplications. Vol. JJ

Global and Local Variables:

Global OC Local 4D

Global VAR2 OD Local 4E

Global VAR3 OE Local 4F

Page 49: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 49/260

 

The Use of Pointers for Multiple Indirect Addressing

To continue with the discussion on the multi-byte add sub-routine, one may

definethe singlebyte address reference storage or pointer variables as PTRA,

PTRB and PTRS. The actual numbers are stored elsewhere in the RAM, andonly the addresses of the least significant bytes of each number, NUMA,

NUMB and SUM are stored in the pointer variables, for example:

PTRA

PTRB

NUMA

NUMB

10

11

NUMA 18(e.g)

PTRS SUM 12

A+O

A+1

A+2

etc.

NUMB B+O

B+1

B+2

etc.

S+O

S+1

S+2

etc.

20 (e.g) SUM 28 (e.g)

In this type of arrangement, the addresses of a variable are stored in another

variable, and the addresses can be manipulated as if they are normal numbers.

The pointers and numbers must be set up previously, and the only other

parameter that must be taken into the sub-routine, is the number of bytes that

must be added. It can either be stored in another pointer, or taken over in theWork Register when the sub-routine is called. The multi-byte addition

algorithmmay be as shown on the next page:

Ch.10 Binary Mathematics 331

Page 50: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 50/260

 

Multi-Byte Addition Algorithm:

Clearing the Answer Bytes:

1. Place the number of bytes in W into a local variable counter.

2. Get the address of the sum bytes into the FSR through W.

3. Recover the counter value into W for later use.

4. Increment the counter to clear one extra byte of the sum.

5. Clear the sum byte indirectly by addressing INDF (the byte FSR is pointing to).

6. Increment the FSR.

7. Decrement the counter and skip if not zero.

8. Go back to step 5.

Adding a Byte of the First Number to the Sum:

9. Load the original number of bytes into the counter fromW.

10. Place the address pointer of number A in the FSR through W.

11. Read the Number A byte indirectly through the FSR to w, and store in a

temporary storage, TEMPW.

12. Place the address pointer of the sum byte in the FSR through W.

13. Get the Number A byte back in W from the temporary storage.

14. Add the sum byte to W and store back into the sum through INDF.

15. Increment the FSR to point to the higher sum byte.

16.Test the Carry and skip if cleared (no roU-overduring ADD)

17. Increment the sum byte indirectly, Le. increment INDF.

332 PlC Micro-Controller Operation and Applications - Vol. II

Page 51: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 51/260

 

Adding a Byte of the Second Number to the Sum:

18. Place the address pointer of Number B in the FSR through W.

19.Read the Number B byte indirectly through the FSR to w, and store in a

temporary storage, TEMPW.

20. ,Placethe address pointer of the sum byte in the FSR through W

21. Get the Number B byte back in W from the temporary storage.

22. Add the sumbyte to W and store back into the sum through INDF.

23. Increment the FSR to point to the higher sum byte.

24. Test the Carry and skip if cleared (no roll-over during ADD)

25. Increment the sum byte indirectly, Le. increment INDF.

26. Increment the number A pointer.

27. Increment the number B pointer.

28. Increment the sum pointer.

29. Decrement the counter and skip if not zero.

30. Go back to step 10.

31.Exit.

Note that steps 11 to 17 is exactly the same as steps 19 to 25, so these steps

maybe placed in a sub-sub-routine. Examples of the assembler calling routineand the two sub-routines can therefore be as shown on the next pages:

Ch.i 0 BinaryMathematics 333

Page 52: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 52/260

 

;Multi-Byte Addition Calling Routine: (MULADD.ASM)

; Variables:

PTRA

PTRB .PTRS

NUMANUMBSUM

LOCAL2LOCAL1

; Constants:

VALAVALB

N

INCLUDE <\PIC\REG84.H>

EQU OC

EQU OD

EQU OE

EQU 10

EQU 18

EQU 20

EQU 4E

EQU 4F

EQU 0x218C7

EQU Ox681EEsum = Ox89AB5

EQU 3

; Load the initial numbers in.RAM

START

334

MOVLW low VALA

MOVWF NUMA

MOVLW lowVALAlOxl00

MOVWF NUMA+I

MOVLW high VALAlOxlOOMOVWF NUMA+2

MOVLW 10wVALB

MOVWF NUMB

MOVLW low VALB/Oxl00

MOVWF NUMB+l

MOVLW high VALB/Oxl00MOVWF NUMB+2

;F:Address reference to NUMA

;F:Address reference to NUMB

;F:Address reference to SUM

;F:LSByte of VALUEA

;F:LSByte of VALUEB

;F:LSByte of SUM

;F:Space for Local Variables

;F:

;C:Defined the actual numbers here

;C: for easy change while testing.

Will be the answer for checking

;C:Three bytes long

;Store LOW byte of A

; into RAM (C7h)

;Store MIDDLE byte of A

; into RAM (I8h)

;StoreHIGH byte C'fA; into RAM (02h)

;Store LOW byte ofB

; into RAM (EEh)

;StoreMIDDLE byte ofB

; into RAM (81h)

;StoreHIGH byte ofB

; into RAM (06h)

PlC Micro-Controller Operation and Applications - Vol. 11

Page 53: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 53/260

 

; Set up the Address References:

MOVLW NUMA

MOVWF PTRA

MOVLW NUMB

MOVWF PTRBMOVLW SUM

MOVWF PTRS

;These are addresses used as

; numbers, and stored in

; pointer or address variables.

; Set up the loop counter in Wand call the sub-routine:

MOVLW N

CALL MULADD

SLEEP

;Multi-ByteAddition Sub-Routine:

; Enter: Address References to the lowest bytes in PTRA, PTRB and

; the answer bytes in PTRS. The byte counter must be in W.

; Local Variables: COUNT

; Exit: Answer in answer bytes.

; Corrupt: (W, FSR, C, DC, Z). Stack: 2 levels.

COUNT SET LOCAL1

; Clear the answer bytes:

MULADD MOVWF COUNT

MOVF PTRS,wMOVWF FSR

MOVF COUNT,w

INCF COUNT,f .CLRLOOP CLRF INDF

INCF FSR,f

DECFSZ COUNT,fGOTO CLRLOOP

Ch.10 BinaryMathematics

;F:

;Set up counter to clear bytes

;Answer reference to W

;Recover counter for re-use

;Clear N+1 sum bytes

;The data referred to by FSR

;Set FSR up for next round

;Skip at end of count.

; else repeat loop.

335

- I

Page 54: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 54/260

 

; Multi-byte add loop.

MOVWF COUNT

ADDLOOP MOVF PTRA,w

CALL AD2SUM

MOVF PTRB,wCALL AD2SUM

INCF PTRA,f

INCF PTRB,f

INCF P1'RS,f

DECFSZ COUNT,fGOTO ADDLOOP

RETURN

;Set up counter for add loop

;Get the 1st byte reference add

;Call Add 1 byte to sum sub.

;Get the 2nd byte reference add

;Call Add 1 byte to sum sub.

;Set up for next round

;Set up for next round

;Set up for next round

;Skip at end of count.

; Else, repeat loop.

;Add 1Byte to Sum byte and increment Sum+1 for Carries.

;Exit sub-routine

;Enter: Address pointer of byte in W.

;Local Variables: TEMPW;Corrupt: W, FSR, C, DC, Z. Stack: 1 level.

TEMP SET LOCAL2

AD2SUM MOVWF FSR

MOVF INDF,wMOVWF TEMPW

MOVF PTRS,w

MOVWF FSRMOVF TEMPW,w

ADDWF INDF,f

INCF . FSR,f

BTFSC STATUS,C

INCF INDF,fRETURN

END

336

;F:

;Place byte pointer in FSR

;Read byte indirectly

;Store byte in temporary store

;Get sum byte pointer

;Place in FSR

;Recover byte from storage

;Add and store back in sum byte

;Point to higher sum byte

;Skip if no carry was generated

;Increment higher sum byte

;Exit

PlC Micro-Controller Operation and Applications - Vol. II

Page 55: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 55/260

 

The assembler high and low operators are very useful on any two byte

numbers. They have the same result as a divide by 100h ( / ) and the modulus

( % ) or the remainder of a division by 100h. Any byte of a multi-bytenumber

in the hexadecimal system, or a digit value in the decimal system can be

isolatedbythe use these operators. These operators are usedby the assemblerprogram and not by the PlC. They will calculate a value during assembly time

and place the result in the user program.

"Toisolate the second byte out of a three-byte number, use:

346DE4 / 100

346DE4 % 10000

(346DE4 % 10000) /100

to chop off the lower byte, and

to chop off the higher byte, orto do both.

For this example one can easily spot the answer 6D without using the

operators. The original number may also be a symbol that can change or be

unknown when the program iswritten.

To let the assembler convert and isolate the 3rd hexadecimal byte out of the

decimal numberD'7654321', use:

D'765432I' % OxlOOOOOO to chop off the higher byte, then

(D'765432I ' % Oxl000000) / 10000 to chop off the lower 2 bytes.

Note againthat these calculationswill be done by the assembler, and can only

be used to calculated specific values that must be placed into instructions.

Division and conversion of numbers by the PlC itself, is a bit more complex.----------------

Binary Multiplication

Multiplicationis nothingmore thanmultiple addition. The binary equivalent

for the decimalmultiplicationof the numbers: 4 x 5 = 4 + 4 + 4 + 4 + 4 = 20,

or inbinary: (100x 101)= 100 + 100 + 100 + 100 + 100= 10100.

Specific names are given to the two initial numbers and the answer. The

names are used to identifYwhich iswhich: The number to be multiplied is the

multiplicand. The number that indicates how many times the multiplicand

must be multiplied, is the multiplier. The answer is theproduct.

Ch.iO Binary Mathematics 337

Page 56: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 56/260

 

.The maximumbyte space required for the product of two numbers is the sum

of the number of bytes of each of the two numbers, e.g:

1byte x 1byte = 2 bytes

2 bytes x 3 bytes = 5 bytes

There are two basic methods or algoritIuns to do binary multiplication, the

Multiple.Add method, and the Shift-and-Add method:

The Multiple Add Method of Multiplication

Here the Multiplier is used as a down-counter. It counts the number of times

the multiplicand is added to the answer. The answer must be cleared initiallyof any possible previous values. An example of a I-byte by I-byte multiple

add multiplication problem, is as follows:

; Multiple Add: I-Byte by I-Byte Multiplication

; The Calling Routine:

INCLUDE <\PIC\REG84.H>

;Variables

NUMA

NUMB

ANSW

EQU

EQU

EQU

OC

OD

OE

;F: (I byte long)

;F: (l byte)

;F: (2 bytes)

;Load the initial numbers

INIT MOVLW B'OlOIIOII'

MOVWF NUMA

MOVLW B'OOOIOIOO'

MOVWF NUMB

CALL MULADD

SLEEP

;=D'91'

;=D'20'

338 PIC Micro-Control/er Operation and Applications - Vol. II

Page 57: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 57/260

 

; I Byte x I Byte Multiplication Sub-routine

MULADD CLRF ANSW

CLRF ANSW+I

MOVF NUMA,w

CycleTiming123

LOOPM ADDWF ANSW,f

BTFSC STATUS,C

INCF ANSW+I,f

DECFSZ NUMB,fGOTO LOOPM

;Add NUMA to answer 4 10

;Skip for no carry 5 11

;Add carry to high answ. 6 12

7[&8] 13&148&9.

,

RETURN [9&10] 15&16

The nwnbers on the right-hand side can be used to derive a fonnula for the

nwnber of cycles required to do the multiplication for a multiplier value of 1and 2. The resultant fonnula is:

Cycles =4 + (NUMB x 6) = 4 + (20 x 6) = 124cycles

If NUMB was 255, the maximwn nwnber of cycles will be 1534.

A two-byte by two-byte multiplication will require a two-byte add, with

possible cames taken care of right up to the most significant product byte. A

two-byte decrement of the multiplier, that is similar to the double inner and

outer loops done for the delay routines, will also be required. This two-byte

by two-byte routine can be done by the student as an exercise.

The Shift-and-Add Multiplication Algorithm.The decimalequivalent for this method is found in the way one would do the

multiplicationof large decimalnwnbers on paper. Each digit of the multiplier

is multiplied individuallywith the multiplicand and the answers added. The

higher digit answersare shifted before they are added to the answer. Say one

need to multiply257 by 312, the procedure will be as shown on the next page:

Ch.lO Binary Mathematics 339

Page 58: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 58/260

 

257 Multiplicandx 312 Multiplier

TotalO 000

+(2x257) 514 LSD of Multiplier x Multiplicand

Total 1 514

+(1.x257xl0) 2570 (Sub-answer Shifted 1 digit left)

Total2 3084

+(3x257x100) 77100 (Sub-answer Shifted 2 digits left)

Total 80184

Follow the same procedure in binary to multiply 110lO1 by 1011:

x110lO1 Multiplicand

1011 Multiplier---------------TotalO 0000000000

+(lxl10lO1) 110101 LSB of Multiplier x Multiplicand

---------------Totall 0000110101

+(1x110101xlO) 0001101010 (Sub-answer is shifted 1digit left)---------------Total2 0010011111

+(Oxl10101x100) 0000000000 (Sub-answer shifted 2 digits ieft)---------------Total 3 0010011111

+(1x110101x1000) 0110101000 (Sub-answer shifted 3 digits left)---------------Total 1001000111

For micro-controllers, all operations are done on byte units. The shifting of the

multiplicand to the left can be done by the RLF instruction. The highest bit is

shifted into the Carry, and then shifted into the other byte. The higher byte of

the multiplicand and the carry must be cleared before the instruction.

340 PIC Micro-Control/er Operation and Applications - Vol. II

Page 59: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 59/260

 

The Roll Right Instructions: (Move MSB of NUMB to LSB ofNUMB+ I)

Themultiplicationof one digit of the multipliercan onlyresult in one times the

multiplicandor in zero. One must therefore either add the shiftedmultiplicand

to the answer if the multiplierdigit is one, or skip over the adding sequence if

it is zero. The whole routine can be written in a loop that repeats itself for -

everybit of themultiplier. To test the multiplier digit at the same bit position

for every loop, the multipliercan be shiftedRIGHT and the Carry bit tested to

decide whether to add or to skip.

NUMA (Tested In C)

~

The SequenceofEvents and assembler program for a shift-and-add I-byte by

I-byte multiplication problem, may therefore be as shown below:

A I-Byte x I-Byte Multiplication Sequence of Events:

1. Cle~ the ANSW, ANSW+l and NUMB+ I bytes.

2. Set a counter to 8 for the 8 bits of the multiplier.

3. Roll right the multiplier to get the LSB into the carry.

4. Test carry and skip to 6 ifset, Le.LSB was a 1 before the RRF.

5. Else, ifLSB was 0,jump over the addition to step 10.

Ch 10 BinaryMathematics 341

CfJ-i

NUMB RLF NUMB,f

.NUMB+l RLF NUMB+l,f

.

Page 60: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 60/260

 

6. Add the multiplicand lower byte to the answer.

7. Skip to step 9 if no carry was generated, i.e. C = O.

8. Increment ANSW+ 1 to record the carry.

9. Add the higher multiplicand byte, NUMB+ 1 to ANSW+ 1.

10. Clear the Carry byte.

11.Roll the multiplicand low byte one bit left into the carry.

12.Roll the carry one bit to the left into the higher multiplicand byte.

13. Decrement the counter and skip if zero.

14. Goto step 3 to repeat loop.

15. Exit.

(Note: The carry does not hav.e to be cleared before the roll into the multiplier

at step 3, because that bit will not be used again.)

Software Listing: I-Byte x I-Byte Shift-and-AddMultiplication

; The Calling RoutineINCLUDE <\PIC\REG84.H>

;Variables

COUNT EQU OC ;F:

NUMA EQU OD ;F: (1 byte)

NUMB EQU OE ;F: (2 bytes)ANSW EQU 10 ;F: (2 bytes)

;Load the initial numbers

INIT MOVLW B'OIOllOll' ; = D'9I'MOVWF NUMA

MOVLW B'OOOIOlOO' ; = D'20'MOVWF NUMB

CALL SHFADD

SLEEP

342 PlC Micro-Controller Operation and Applications - Vol. 11

Page 61: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 61/260

 

; General Purpose I-Byte x I-Byte Multiplication Sub-RoutineCycle count

1

2

3

4

5

SHFADD

'LOOPM

CLRC

CLRF ANSW

CLRF ANSW+1

CLRF NUMB+ 1

MOVLW 8

MOVWF COUNT

RRF NUMA,f

BTFSS STATUS,CGOTO CLRC

MOVF NUMB,w

ADDWF ANSW,f

BTFSC STATUS,CINCF ANSW+l,f

MOVF NUMB+l,w

ADDWF ANSW+l,f

BCF STATUS,C

RLF NUMB,f

RLF NUMB+l,f

DECFSZ COUNT,fGOTO LOOPM

RETURN

6 21

7 22

8 23

9 24

\Adtllower Multiplicand 10 2511 26

12 27

13 28

\Add higher Multiplicand 14 29

;Prepare for byte shift 15 30

;Shift bit from lower byte 16 31

; into the higher byte 17 32

18[&19] 33&3419&20

[20&21] 35&36

;Multiplier

;Skip if carry SET

; else jump over adding

;Adjust for carry

The loop timing formula for the worst case (no jumping over the adding

section) will be: 6 + (count x 15) cycles, and for 8 bits, the maximum

execution time will be 126 cycles.

For multi-byte by multi-byte multiplication, the same process is followed. The

total number of bytes required for the answer will be the total sum of the

number of bytes of the multiplier and the number of bytes for the multiplicand.

The multiplicand must be shifted right through multiple byte shifts, Le. into the

carry and into the next byte. The number of empty bytes allowed for the

multiplicand to shift left, must be the same as the number of bytes allowed for

the answer. Every time the higher byte is incremented to record the carry, it

must be tested if another carry was not generated. If so, it must be added to the

next higher answer byte. This test must be done up to the second most

significant byte only. The multi-byte addition sub-routine of the previous

section may be used.

Ch.i 0 Binary Mathematics 343

Page 62: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 62/260

 

Binary Subtraction and Negative Binary Numbers

When two numbers are added or multiplied, the position of the two numbers

can be swappedwithout any change in the answer. For subtraction, however,

which number is subtracted ITomwhich, is important. It will have a defmiteinfluence on the answer. Consider the following examples:

5 + 4 = 9 and 1+ 5 =9 (No change to answer)

but 5 -4 = I and 4 -5 = -I (The same value, but negative)

It is obvious that when the smaller number is subtracted ITomthe bigger one,

the answerwill be positive. If the numbersare equal, the answerwill be zero.

A zero answer will also be considered positive.

To indicate negative numbers in the binary system, the most significant bit is

sacrificed to indicate the sign. An 8-bit byte will then consist of 1 sign bit and

7 bits for the value. A two-byte number, which may contain negative numbers

as well, will consist of 1 sign bit, and 15 bits to indicate the value.

When the sign bit is 0, the number is positive, and the rest of the number will

be the nonnal binary value used so far. When the sign bit is 1, the number is

considered a negative value. The value of a negative number is presented in

the so-called 2's complement fonnat. The 2's complement fonnat will give a

simple roll-over ITompositive into negative numbers when crossing the zero

point. The nonnal addition sub-routines will add positive and negativenumbers correctly, and reflect the correct sign for the answers, if sufficient

space has been provided for the answer.

If one counts down (decrement) ITomthe binary number 3, or 000000II past

the zero point, the result will be as follows:

00000011= 300000010= 200000001 = 100000000= 011111111=-111111110=-211111101=-3

. 11111100=-4

(Negative, in the 2's complement fonn)

( do. )

( do. )

( do. )

344 PIC Micro-Controller Operation andApplications - Vol. II

Page 63: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 63/260

 

It is difficult to convert a 2's complement number to decimal directly by

inspection and mental arithmetic. First the number must be converted into a

signed binary value, and then directly fo decimal. The inverse conversion

from a negative decimal number to the 2's complement, is similar.

Two convert a 2's complement number into a signed binary number, the entire

number must be complemented, i.e. all the lIs must be changed to O's, and the

D's to I's first. That will result in what is called a I's complement number.

Then add a normal! to make it a 2's complement number.

As an example, the -3, or 11111101 from the count table above, will beconverted to decimal as follows:

OriginalComplement:Add 1

Signed binary:Decimal

11111101 (2's complement and negative)-(00000010) ( l's complement)

1

-(00000011) (Binary value with negative sign)

-( 3) (Direct conversion to decimal)

Original

To convert a decimal-4 to the 2's complement format:

Complement:Add I

2's Complement:

-( 4)-(00000100), (Signed Binary format)

-(11111011) (l's complement)1

11111011

The 2's complementformat for binarynumbers must be considered a different

numbering system than the normal positive binary system. The user mustdecide beforehand which numbering systemwill be used for his application.

If there is a possibility that there are going to be negative binary numbers, the

2's complement format must be used. When working in this format, positive

numbers are alsocalled2's complementnumbers. They may look the same as

the normal binary numbers, because the MSB is zero, but are treateddifferently.

Ch.IO Binary Mathematics 345

Page 64: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 64/260

 

The maximwn nwnber that can be represented by an 8-bit 2's complement

nwnber is +127, or 01111111, and the minimum ormost negative number, is

-128, or 10000000, in total, also 256 different nwnbers, including the zero.

Subtracting 2's Complement Binary Numbers

Subtraction in binary is essentially the same as for decimal. If the top nwnber

is too small, one would borrow or subtract one unit ITomthe more significantunits to enable the subtraction:

Subtract: 24253 (Decimal) 010101011 (Top nwnber -Binary)-12432 - 001010010(Bottomnwnber)

11821 001011001

Subtraction in binary can also be achieved by adding the 2's complement of

the bottom nwnber to the top nwnber. The 2' complement of 00 1(I100 10 is for

example: 1101011 10.

01010101 I

+ 110101I 10 (Add the 2's complement of 001010010)

1 001011001 (The 1 or carry on the left side is discarded)

By using the 2's complement format, the sign will automatically be set to

indicate a positive or negative result. This will happen only if the original

nwnbers were represented cOlTectlyn the available bits. The numbers and the

answer must also be able to fit into the available bits. Any caITiesfrom the

sign bit must be discarded. An example of normal subtraction ofD'20' ITom

D'30' in the 2's complement numbering system, is shown below:

30 = 00011110-20 = - 00010100

20 = 00010100

-30 = -00011110

10 00001010 - 10 11110110

-(00001001)+ 1

-(00001010) = -D'lO'

346 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 65: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 65/260

 

For PlC micro-controllers that operate in byte units, there are two ByteOriented Subtract Instructions:

Subtract Wfrom Register or Literal Values, SUBWF and SUBLW: The first

instruction will do an 8-bit binat)' subtraction of the Work Register value trom

a File Register value and place the answer in the specified destination byte.

The second instruction will subtract the Work Register trom the Literal value

contained in the instruction, and place the answer in the Work Register. The

numbers may be in the normal binat)' format or in the 2's complement format.

If there is a borrow trom the most significant bit, Le. the Work Register value

was bigger than the other value, the Carry bit will be cleared. If there was no

borrow, the Carry bit will be set. The setting of the Carry can be remembered

by assuming a borrow bit (the Carry) was set and available for use before one

subtracts. If it is needed, it is taken out of the Carry bit to leave it cleared. If

it is not used, the carry bit will stay set. .

Adding and Subtracting of Positive and Negative Numbers

In decimalmathematics,any of the initial two numbers may be either positive

or negative. These numbers can be added together, or subtracted from one

another to give either a positive or a negative result. Examples are:

(+4) + (-3) =(+1)

(-2) + (-3) =(-5)

(-2) - (-3)=(+1)

(+2) - (+4) = (-2)

The same operations can be done to positive and negative numbers in the 2's

complement format. The sign will automatically be set of cleared to give a

positive or negative answer. This will happen only if the conditions of space

allowed are followed, and carries or borrows from of the sign bit are discarded.

Multi-Byte Subtraction

The algorithmsfor multi-bytesubtraction.arethe sameas for addition. The top

number (from which the other number must be subtracted) is placed in a few

bytes. It must be in the 2's complement format, Le. the MSB is the sign.

Ch.l0 Binary Mathematics 347

Page 66: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 66/260

 

The bottom number must be placed in an equal number of bytes, also in the 2's

complement format. The answer or difference should be placed into one more

byte than the two original numbers, to provide for the widest possible answer.

The operation must start by clearing the answer bytes. The two leastsignificantbytes are subtracte,dand the answerstoredin (or added to ) the least

significant answerbyte, If a borrowwas generated,Le.the Carry was cleared,

this borrpwmustbe taken from the more significant bytes. If the next answer

byte is decremented from zero to FF by the borrow, it must generate another

borrow to the higher bytes, etc. This must be continued up to past the most

significant byte and the sign bit, where a borrowwill be discarded.

The next two bytes are then subtracted. Any possible borrow must again be

subtracted fromthe higher bytes. Some of these bytesmay already be FF, andanother decrement will not generate a borrow. The result of the subtraction

must be ADDED to the answer byte. This byte may contain the (-1) of a

previous borrow. If a roll over from the addition occurs, the carry must be

ADDED to the higher bytes.

The process seems to be quite complex, but by using a proper flow diagram

that covers all the possible paths, the solution can be simplified.

Realising Bigger Titan, Equal To and Smaller Titan Conditions

In choosingbetween different paths in a program, one often has to choose on

the basis of one number being bigger than, equal to or smaller than another.For these choices, the subtract instruction can be used. Here one must

remember that the Work Register value is always subtracted from the othervalue.

* Subtracting equal numbers will set the Z flag.

* If the Work Register value was bigger the subtraction result will be negative

and the Carry bit will be cleared.

* If the Work Register value was smaller the result will be positive and the Carrybit will be set.

348 PIC Micro-Control/er Operation and Applications - Vol. II

Page 67: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 67/260

 

When BCD numbers were incremented, the BCD roll-over was required when

the value of 1010 was reached. It was tested for being equal to 1010 by the

XOR instruction to set the Zero flag. If one were to add two BCD numbers,

the answer may be equal to or bigger than 1010. To detect this, 10I0 is placed

into the Work Register and subtracted from the answer. The destination must

be the Work Register. Then the BCD number in the File Register will stay

unaltered after the instruction. There are two possible outcomes:

..Ifthe value was bigger than or equal to 1010, i.e. the answer is positive or

zero. The carrywill be set. Thenl010 must be subtracted from the sum value.

This operationwas done already and the answer is in the WorkRegister. Only

the carry to the next digit must be taken care of.

* If the tested number was smaller than 10I0, i.e. the subtract answer wasnegative, then the carry will be cleared (C = 0). Here the value must stay as it

was (still unaltered in the File Register) and there is no carry.

As an example, two BCD digits, occupying only the lower nibbles of two

bytes, will be added to two other BCD digits, also in two separate bytes:

A BCD Two-Byte by Two-Byte Addition Sequence of Events:

1. Clear at least 3 SUM bytes for the answer.

2. Add the LSDigits together and store in a SUM byte.

3. Load 1010 in the Work Register.

4. Subtract W from the SUM to set or clear the Carry. Store in W.

5. Skip if the carry was set, Le. W was smaller than SUM.

6. Jump over to step 9.

7. Store W to SUM.

8. Increment the more significant SUM byte.

9. Add the second significant digits together and add to SUM+1.

Ch.10 Binary Mathematics 349

Page 68: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 68/260

 

10. Load 1010 in the Work Register.

] 1. Subtract W ITomthe SUM+1 to set or clear Carry. Store in W.

12. Skip ifthe caIT)' was set, Le. W was smaller than SUM.

13. Jump over to step 16.

14. Store W to SUM+ 1. The subtraction has already been done for the test.

15. Increment the SUM+2 byte.

16. Exit.

To add packed BCD numbers, Le. two BCD numbers per byte, the bytes

shouldbe separated first. Aft'erthe addition, the answer can be packed again.

There are methods using the DC or Digit CaIT)'bit as an indication of

roll-overs above a sum of 15 to correct the BCD numbers, but tbey are a bit

complicated and too time consuming to included here. .

Multi-Byte Comparisons

To find if a multi-byte number is bigger than, equal to or smaller than another

number of an equal number of bytes, one would start with the most significant

bytes. If the most significant byte of one number is bigger or smaller than the

other most significant byte, no further comparisons need to be done. Only if

the most significant bytes are equal, the corresponding lesser significant bytes

need to be compared with the other bytes. When one is bigger or smaller thanthe other, no further comparisons need to be done. The least significant bytes

will only be compared if all the higher bytes of the two numbers are equal.

350 PIC Micro-Controller Operation and Applications - Vol. II

Page 69: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 69/260

 

Program 15: A Cash Register

Use the Basic Board and the Keyboard and 7-Segment Display to design a

CashRegister to operate as follows:

* OnReset,the displaysmustbe blank and only the decimal dot of the third digit

from the leftmust be on. The devicemust be placed in the SLEEP mode with

~e keyboard interrupts enabled.

* When a number key is pressed, the device must wake up and the key value

must appear on the least significant display digit. The decimal dot can staywhere it is.

* Subsequent number keys must shift the first digit on the display to the left, and

the new key value must appear on the least significant display digit.

* More keys must be able to shift the current display values to the left and out,

so that faulty entries can be corrected this way.

* After a correct number up to 99.99 has been entered, the F key may be pressed

as an Enter and Add key. It will add the current number to a total, and the total

must be displayed on the four digits. It must show Rand and Cents, togetherwith the decimal dot.

* Once the Grand Total has been reached, the pressing of the B key will

calculate and show a 14%V.A.T. value ("BTW"), rounded off to the closestcent.

* Pressing the F key again, this VAT will also be added to the Grand Total.

* After this, the number entered into the display must be a rounded Rand value

bigger than the total, as the amount tendered or handed over to the cashier.When the C key ispressed, it must calculate and display the change that must

be handed back to the customer. If the number entered is less than the grand

total when C is pressed, the display must flash at a I-second interval. The

display must be restored when a new number is entered as the tenderedamount.

Ch.10 Binary Mathematics 351

Page 70: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 70/260

 

Notes:

The nwnbers entered and the total maybe stored in the BCD format using one

byte per digit. When two digits have been added together, the swn must betested if it is more or equal to 10. If it is, a 10must be subtracted and I unit

added to the more significant digit.

The 14% VAT is 0.14 times the total. It can be treated as an integer 14,

(0.14 x 100), and multiplied as a normal integer. That will result in a value

100 times (or two decimal BCD-digits) bigger than the correct value. To

round this nwnber off to the closest rounded cent, 50 must be added to the

total. Then the two least significantdigitsmust be discardedto dividethe total

by 100 again.

-------------Program16: AddingAuto-Rangingto the FrequencyMeter

Modify the program of the Frequency Meter to have an auto-ranging facility.

It must have two modes, the Auto-Ranging mode, and a Manual Ranging

mode. On Reset, the system must automatically go into the Auto-Ranging

mode. When the pulse count is more than 999, i.e. and Overflow has been

reached, the range selectingmust be decremented by one. If the count is less

than 099, the range must be incremented automatically.

When one of the Range selec(buttons are pressed, the system must go into the

Manual Ranging mode. Then the buttons may be used to increment or

decrement the range manually as before, If both buttons are pressed

simultaneously, the system must go back into the Auto-Ranging mode.

-------------

352 PIC Micro-Controller Operation and Applications - Vol. 11

Page 71: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 71/260

 

Binary Fractions and Integer Division

Fractions can also be represented in the binary system, and are similar to

decimal ftactions. In decimal ftactions, the fIrst digit to the right of the

decimalpoint indicates 1/10thsof a unit, then 1/100ths,etc. In binary, the firstdigit to the right of the point indicates 1/2, then 1/4, then 1/8, etc. It expands

to a whole field of the so-called FloatiYIgPoint Arithmetic, that will not be

.covered in this course. These calculations normally consume a great deal of

RAM and code bytes, of which the PIC16F84 has not too many!

There are some ways to bypass multiplication of binary ftactions. The two

numbers are first shifted leftpast the decimal point (multipliedby 2) until they

are both integers. The combined total of the number of shifts must be stored.

Then the numbers are multiplied as integers. Finally, the answer is shiftedright past the decimal point (divided by 2) by the total number of shifts used

tomake the two numbers integers.

Normal division will result in an answer containing ftactions for most cases.

One way to steer clear of these ftactions, is to make use ofInteger Division.

Integer Division will result in an integer Answer, and an integer Remainder.

To indicate the difference in operation between normal division and integer

division, the % symbol is used, in place of the / symbol:

13 / 4 = 3.33333 (Normal division)

13 % 4 = 3 remaining 1 (Integer division)

Micro-Processor Division Algorithms

For micro-controllers working in byte units, there are two methods of doing

division: The Multiple Subtract method, and the Shift and Subtract method.The Shift and Subtractmethod ismuch faster in cycle time than the Multiple

Subtractmethod. It is alsomuchmore complex to understand, even for single

byte division. This method will also result in a ftactional answer. Only the

Multiple Subtract method will be covered. This method will result in an

integer division answer, and an integer remainder:

Ch.10 Binary Mathematics 353

Page 72: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 72/260

 

The Multiple Subtract Method for Division

The multiple subtractmethod is the inverse of the MultipleAdd niethod used

for multiplication: One must count (in the answer byte) the number of

subtractions of the divider from the dividend, until the value left over (theremainder) is smaller than the dividend.

Micro-controllers operate in bytes, and the same calculations can be made,

using bytes. Provisionmust alsobemade for both the divider and the dividend

to be any value from 1 to the maximum. Division by zero cannot be done.

The space required for the answers will again be an issue. If the dividend is

1 byte long and the divider is also 1 byte long, the answer must be at least

1 byte long and the remainder also 1byte long.

If the dividend is three bytes long, and the divider to two bytes long, the

answermaybe up to three bytes long (for divisionby 1). The remainder must

be at least two bytes long. The same size as the divider. (The maximum

remainder value can be the divider value minus I.)

For a single byte divider and a single byte dividend, the Integer Divisionalgorithm can be as follows:

I. Clear the answer byte.

2. Subtract the divider from the dividend and store in W.

3. Skip to step 5 ifno borrow was generated, Le. the divider can be subtracted

without going negative, C = I.

4. Else jump to exit.

5. Copy W into dividend. The subtraction has already been made for the test.

6. Increment the answer byte by one.

7. Jump back to step 2.

8. Exit with answer in answer byte, and the remainder left in the dividend byte.

354 PlC Micro-Con/roller Operation and Applications - Vol. II

Page 73: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 73/260

 

Multi-byte integer division is done in a similar fashion. Care must be taken

with borrows between the higher and lower bytes. The test if another

subtractioncan be done before the remainder goes negative, can be done with

the Smaller Than comparison tests between the divider and the remainder ofthe dividend.

Conclusion

Due to the limited RAM and Code memory of some of the PlC controllers, it

will be better to try to avoid too complex mathematical calculations. This can

be doneby ratherbuilding in scale factors, offsets, etc. in the input hardware.

This should then result in values that can be useddirectly as is by the software.

Another option is to write the program in C for PlC Controllers. Here,

algorithms for calculations up to two bytes long for Addition, Subtraction,

Multiplication and Division are stored in existing libraries. When required,

these algorithms will be included automatically by the C Compiler.

Programming in C is covered in a later chapter.

The next chapter will deal with parallel and serial port expansion to control

mor~ complex hardware systems. The addition of parallel and serial access

external memory will also be done.

Ch. ID Binary Mathematics 355

Page 74: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 74/260

 

Notes:

356

-

PIC Micro-Controller Operation andApplications - Vol. 11

Page 75: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 75/260

 

11. Pod Expansion and External Memory Devices

Table of Contents

Page

ChapterSummary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 359

.Parallel Output Port Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 361

Expanding to more Sets of Parallel Output Data Lines. . . . . . . . . . .. 362

Parallel Input Port Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 363

Multiple Inputs and Outputs on the Same System. . . . . . . . . . . . . . .. 364

ASmall8 x 8-BitExternalMemoryBlo~k 366

Driving of an External Parallel Memory Device from the PIC16F84 . 366

SerialInputExpansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 368

SerialOutputExpansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 369

Accessing Serial Inputs and Outputs on 3 Pins Only. . . . . . . . . . . . .. 371

Practical Assignment 4: Driving SIPO and PISO Shift Registers. .. 372

,

Serial Memory Devices. . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . .. 372

Basic 3/4-Wire Communication to EEPROM Memories. . . . . . . . . .. 372

Practical Assignment 5: Serial Memory Access. . . . . . . . . . . . . . .. 378

The 16-BitOrganisation and Other 3/4-WireEEPROMSerialMemories.. ... ... .. .. 378

(Continued )Rev.5 6/02DNdB

357

Page 76: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 76/260

 

Table of Contents. (Continued..)

Page

The 2-Wire PC Protocol and Serial Memories. . . . . . . . . . . . . . . . .. 378

The 85C82EEPROMSerialMemoryDevice , 380

Other 2-yv'ireSerial EEPROM Memory Devices. . . . . . . . .. . . . . . .. 385

Communication with a PC through the Parallel Printer Port. . . . . . .. 385

Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 386

---------------------

358 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 77: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 77/260

 

11. Port Expansion and External Memory Devices

Chapter Summary

This chapter deals with the expansion of the number of output and input portsfor PlC devices. For parallel expansion, a parallel data bus and device

selection decoders are used to supply up to 64 inputs and 64 outputs on the

same system. The circuit to drive a 32K x 8-bit parallel RAM memory deviceis also included.

Serial port expansion using 3 wires only, can be used to extend the number

of inputs and outputs to as many as may be required. The operation is

explained and incorporated into a practical circuit.

The use of external serial memory devices, and specifically the EEPROM

based 3/4-wire serial memories, are explained in detail. Timing and

sequential diagrams are also included.

The industrystandardPC protocol, and the application to drive 2-wire serial

EEPROM memory devices, such as the 85C82, are covered in detail.

Finally, the requirements to enable a PlC device to communicate

bi-directionally with a PC through the parallel printer port, are given.

Appendices to this chapter include the 2-wire and 3/4-wire EEPROM

Memory Device Data sheets and Selection Guides.

----------------

Ch. I I Port Expansion and External Memory Devices 359

Page 78: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 78/260

 

Notes:

360 PIC Micro-Control/er Operation and Applications - Vol. 11

Page 79: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 79/260

 

Parallel Output Port Expansion

The Port B pins can be used to drive two or more devices in turn, while the

Port A pins are used as control pins. Initially, only one extemallatch will be

added to demonstrate the principle. Then it will be expanded to includemore

output devices.

Either the 74HC573 (Octal Latch) or the 74HC574 (Octal D-Flip-Flop) maybe used. The essential data sheets for these two devices can be found in the

CMOSData Book fromNational Semiconductor or other suppliers.

These 20-pin devices have 8 parallel latches or D-flip-flops, each with a

separateinput and output. A commonLatch Enable or Clock input, and also

a commonHigh Output Impedance control exist for each device. The main

difference between the two devices is the logic levels required on the Latch

and Clock controls to capture the input data.

For the Octal Latch, a HIGH on the Utch control will make the outputs

transparent, Le. continuously show the same value as the inputs. When the

Latch control is taken LOW, it will capture the input values in the output

latches. These values will then be kept stable.

For ~heD-Flip-flop, the outputs will be steady for the Clock control either

HIGH or LOW. The inputs will only be captured and shown on the output

when the clock changes from LOW-to-HIGH.

The Output Tri-state control (OC) for both devices will make the outputs high

impedance when the control is kept HIGH. If this feature is not used, these

output control pins must be tied to ground.

Outputs

Inputs Inputs

Octal D-Flip-Flops and Octal Transparent Latc/les

Ch.ll Port Expansion and External MemoryDevices 361

Page 80: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 80/260

 

Timing Diagrams:

Input:~Latch: r

Input:

LClock:

Out: ~InPut datal~ Out: Previous~New Data

The 8 inputs of each device can be connected directly to the Port B pins, and

the Latch or Clock controls to one of the Port A pins. The sequence to

capture data on to the outputs is shown on the timing diagrams i1bove. The

high impedance Output Controls can also be connected to one of the Port A

pins to place all the outputs in a high impedance state simultaneously. This

can for example, disable all the LEDs driven by the outputs, without changing

the values in the output buffer.

Expanding to more Sets of Parallel Output Data Lines

Once the data has been captured in the buffers and the latching control pins

disabled, the port pin values can change without changing the buffer values.

The same port pins can therefore be used to latch other data on to similarbuffers. Each buffer must then be controlled individually by one of the other

Port A pins.

Using this method, up to 5 latches, or (5 x 8) = 40 independentl()utputpins

can be available. Theyhave a commonData Bus and only the 5 C'ontrollines

are separate to select one of the 5 latches. Only one latch will be enabled at

any time. That means the control lines need not each occupy one pin ofPort A. A decoder can be used instead. It will select one of the five or more

buffers through a unique binary code from Port A. In this waymore latchescan be added and controlled.

The 74HC138 3-to-8 line decoder, and the 74HC154 4-to-16 line decoder

will be discussed. These decodersuse three or four input Selectpins tomake

only one of the outputs low at a time. All the other pins stay high. Each

device also has two ormore control pins that will deselect all the output pinssimultaneously. Then none will be selected.

362 PlC Micro-Controller Operation and Applications - Vol.l/

Page 81: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 81/260

 

The input Select lines and the Enable control of the decoder can be connected

to Port A. All the data input pins of the latches are connected in parallel sets

of 8 lines each to Port B. In addition, each of the decoder output pins must

be connected to a clock pin of each octal D-flip-flop.

Outputs (1 or none LOW) Outputs (1 or none LOW)

74RCUS 74RCl54

o 0

Selcct(MSD-LSD)

Enableo 0 1

Selcct(MSD-LSD)

Enableo 0

3-to-8 and 4-to-16 Line Decoders

Care must be taken with the choice of IC that will be controlled by these

decoders. When the decoder select one output, that output will go LOW.

Whennot selected or not Enabled, the output will go HIGH again. The data

mustbe captured in the output latches onthe LOW-to-HIGH transition. The

D-Flip-floptypemusttherefore be used. The Enable inputs into the decoderscan be used to deselect all the outputs. Then the Port B pins may be used for

somethingelse. ThisEnable pin canbe defined as a general WRITE Control.A total of up to 8 x 8 = 64 or 16 x 8 = 128output pins can be made available

to a system.

To write 8 bits of data to any of the outputs ofa latch, the operating sequence

should be as follows: A specific latch is selected by the binary code to the

Select inputs of the decoder from Port A. The output data is placed on the

Port B pins. Then the Enable (WRITE) line is taken LOW and HIGH again

to write the data to the selected latch. The whole operation will take only a

fewmachine cycles per output latch.

Parallel Input Port Expansion

On externaloutputpins, the datawould normally be stableuntil another write

is done to the latches. Inputs, on the other hand, need only be stable on the

Port B pins at the moment of the Read instruction.

Ch.]] Port Expansion and External Memory De~ices363

Page 82: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 82/260

 

A single input pin expansion devicewill be used to explainthe principle. One

of the 74HC541 high impedance buffers, such as used for the Key and

Display Board, will be employed. Here the high-impedance control pins ofthe bufferswill be implemented. The 74HC540bufferwillworkequallywell,

except that the bufferswill invertthe data levels. This canbe correctedby thesoftware.

Inputs Inputs

High Impedance Input Buffers

The external device pins that must be read are connected to the inputs if the

buffer. The outputs of the buffer are connected in parallel to the Port B pins.

The high-impedance control is connected to one of the Port A pins to enable

or disable the flow of the data through the high impedance buffers. Both

control inputs must be LOW to enable the data. When the buffer outputs are

at high impedance, Port B may be used as outputs, or to read another set of

input data through a similar buffer, controlled by another Port A pin. Two or

more buffers must not be enabled simultaneously. Again the controls for such

a system can be fed from a decoder to expand the number of inputs to the PlC

device to 8 x 8 = 64, or 16 x 8 = 128.

The logic of two Output Control pins of the buffer is connected in a negative

logic AND configuration, i.e. both must be LOW to enable the buffer. One

of the Output Controls from each buffer may therefore be tied together to one

Port A pin. This will facilitate a general READ control pin. It has the sameaction as the WRITE pin used before, to deselect all outputs simultaneously.

Multiple Inputs and Ou~puts on the Same System

By using 8 latches, 8 buffers and two 3-to-8 line decoders, 64 individual

inputsand 64 individualoutputsmay be controlledby the 13port lines of thePICI6F84. The three select lines of the decoders are connected inparallel to

Port A, and an output control of each decoder to the two other Port A pins.

364 PIC Micro-Control/er Operation and Applications - Vol. 11

Page 83: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 83/260

 

(To Other Buffers and Flip-Flops)

Multiple Inputs and Outputs

Ch.ii Port Expansion and External Memory Devices365

Page 84: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 84/260

 

A Small 8 x 8-Bit External Memory Block

By connecting the outputs of the Output Latches back to the inputs of the

Input Buffers, and external storing device can be realised. In place of using

the 8 separate input buffers in the circuit on the previous page, thehigh-impedanceoutput controls of the latches canbe used instead. Theyhaveexactly the same function as the buffers. The outputs of the latches can

therefor~ be connected directly back to the Port B data pins. Eight bits of

data can then be stored externallyin each latch. The data isread back through

their high-impedance output controls, when required. A typical external

memory system.

The connections to the data and control lines to such an external memory

system, are exactly the same as one would fmd for a normal static RAMmemory chip. There are 8 data pins, used for bi-directional data. The three

Select Linesare the Address Lines. Theywill selectthe address of one of the

eight 8-bit latches. The WRITE and the READcontrolsto the decoders,have

the same functionas the WR (Write) and OE (Output Enable) functions of a

memory chip. A memory chip also has a general CS (Chip Select) line. This

can be emulated by the additional Enable inputs on the decoders. Whenneither the WRITE or READcontrols are selected, it has the same effect that

everything is disabled. A normal memory device would have considerably

more address lines than the three used in the previous example. Up to 15 or16 address lines to select between 32K or 64K byte addresses of8 data bits

each, is now the norm.

Driving of an External Parallel Memory Device by the PIC16F84

The pinouts from a typical 32K x 8-bit static RAM device are shown below:

32Kx 8-Bit

StaticRAM

HM65256

366 PIC Micro-Controller Operation and Applications - Vol. 11

Page 85: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 85/260

 

To store or WRITE 8 data bits in parallel to the RAM, the address must be

selectedby placing the correct binary code on the address lines. This address

must be kept stable during the entire storing operation. The 8-bits of data

must be placed on the data bus and also kept stable. The Chip Select line CS

must be taken or kept LOW, and the Write Control, WR, taken LOW and

then mGH again. The input data will be stored inthe specified address until

new data iswrittento that address, or the power is removed from the device.

When the control lines are deselected, the data pins of the device are at high

'impedance.

To READ 8 data bits in parallel out of the RAM, the address must again be

selected and the CS pin taken or kept LOW. When the Output Enable (OE)

line is taken LOW, the stored data will appear on the data pins and can be

read by the controlling device.

The multipleof connectionlines required for the externalRAM seems far too

many for the mere 13 lines of the PICI6F84. By using just two external

latches to latch the 15 address lines (no decoder required), the RAM can be

accessed. It is shown in the sketch below. The data lines of the memory are

connecteddirectly to the Port B pins. Four control lines, two from the RAM

(WR and OE) and one from each of the output latches to Port A, can realise

a complete external memory system with 1port pin spare! The Chip Select

pin, CS, of the RAMcan be enabled permanently.

RAO

~WR

RA! OE

PICl6F84 .. - ...D7RB7 .RBO -~ t .

.

)0

. :, DOA!4

cs

32 K x 8-blt Static RAM -

RAJ RA2

AO

32K x 8-Bit Memory Expansion

Additional output latches and a decoder to control the WR, OE and latch

controls, can expand external memory into Mega-bytes!

Ch.ii Port Expansion and External Memory Devices 367

Page 86: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 86/260

 

Serial Input Expansion

The parallel method of input and output expansion may give a reasonable

access time to the input and output devices. It will also place a large amount

of signal tracks on the circuit board. If the speed is not that critical, serialexpansioncan be used instead. It will reduce the number of signal tracks ona circuit board considerably.

The next IC building block that need to be introduced, is the 74HC165

Parallel-lnlSerial-Out (PISO) 8-Bit Shift Register. These devices have

8 internal D-flip-flops. They can either be loaded directly ITom8 external

inputs, or the data to each flip-flop can be shifted in ITomthe adjacent

flip-flop. Only two control lines are required. A LOW on the Shift/Load

controlwill load the data on the input pins asynchronously,i.e. not dependenton a clock signal. When this control is HIGH, the data will shift out at the

Serial-Out pin on every positive going edge of the Clock input. When the

chip is in the Shift Mode, data can also be shifted into the register through aSERIAL-INpin:

Serial In 74HC16S

Parallel In/Serial OutShift Register

Serial Out

Shift/Load

Clock

A B C D E F G H

Only three port pins are required to connect the chip to a PlC processor to

read the data: The Shift/Loadcontrol, the Clock, and the Serial-Outpin ITom

the device. To read the 8 input bits of the chip into the PlC processor, one

must start in the Load mode, Le. Shift/Load is LOW. The data on input pin

H is then continuouslyavailable on the Serial-Outpin. It canbe read directly

and may also be used to generate an interrupt to start the reading process.

The timing diagram is shown on the next page:

368 PlC Micro-Controller Operation and Applications - Vol. 11

Page 87: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 87/260

 

ShiftILoaeJ:JClock:

. .. ..

SerialOutput: H: G : F j E : D j C : B : A : SI.:. .:4 .:. .:. .:. .:. .:. .:.

The parallel input data will be latched-into the internal latches when the

Shift/Loadcontrol ismade HIGH. Input H will still be on the Serial Output

pin, but now it will be a latched value. After each positive transition of the

Clock signa~ the data of the next input pin can be read on the Serial-Out pin

of the shiftregister. After the 8th clock signal, the data that was on the Serial-

Inpin before the clock signalwentpositive the first time, will be available onthe output to give a 9th input data bit.

Once this serial input system is operational, it can be expanded by adding

another 8 input bits fToma similar shift register. The Serial-Out pin of the

next shift register must be connected to the Serial-In pin of the first shift

register. The ShiWLoadandClock controls of the shift registers are common.

Still only three pins fTom the PlC controller are needed to do all the

interfacing. By using this method, as many additional shift registers as may

be required can be added. The access speed depends on how fast theprocessor can clock the data out of the shift register train. Another factor is

how fast the input data can be processed and stored - thinkin termsoftheRRF instruction and loops.

Serial Output Expansion

A similar expansion for outputs can be achieved by using one of the following

Serial-In/Parallel-Out (SIPO) Shift Registers: The 74HC164 or the 74HC595.

(parallel Outputs) (parallel Outputs)

SerialOut

Clock74HCl64

ABCDEFGHSerialIn SerialOut

Clock 74HCS9S

RiDDle Clock

Ch.]] Port Expansion and External Memory Devices 369

Page 88: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 88/260

 

Themain difference between.the two devices is in the reaction of the output

pins on the shifted data. For the '164 device, the shifted data will

continuouslyappear on the outputpins, i.e. l's and O'swill flicker through on

the output pins while shifting the data. A serial output can be taken directly

trom output pin H. For the '595 device,the shifted datawill be hidden insidethe chip. It will only appear on the outputs when a Ripple Clock control is

activated bymaking it HIGH. Thatwill latch the shifted data into the outputlatches where it will be stable. A Serial-Out pin is also available trom the

internal shift register.

The outputs trom a systemmust usually be kept stable until it is replaced by

other data. In an application where the flicker of the shifting data will not

matter, such as driving LEDs, the '164 device will be sufficient. For LEDs,

the moving of the data past a pin is so fast that it will not be detected. Thisdevice will require only two pins trom the PlC to be driven, one Clock and

one Data pin. The Serial-Out trom the chip is taken fromthe H output. It can

be used to feed additional shift registers.

When the flicker of passing data is not desirable, the '595 device must be

used. Once all the data havebeen shifted to their correct positions,the Ripple

Clock will transfer the shifted data over to the output latches when taken

HIGH. For this device, three driver pins from the PlC will be required:Data,

Clock and the Ripple Clock ~LATCH).

Timing Diagrams:

Clock:

x A

Scr.In: ~'165:

(pinA)

RippleClock:

'595: PrcviousData E

370 PIC Micro-Control/er Operation and Applications - Vol. 11

Page 89: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 89/260

 

AccessingSerial Inputs and Outputs on 3 Pins Only

Combinationsof the '165 PISO and the '595 SIPO can be used for inputs and

outputs on the same three pins of the PlC. Just before the clock goes high,

data mustbe placed on the serial input of the SIPO. At that point, the port pin

must be configuredas an output. For the serial input circuits, the data on the

serial output of the PISO was valid just after the clock went high. At that

moment the port pin must be configured as an input and the data can be read

bythePlC.

The circuit below will enable the PlC to read the input data when the clock

signal is HIGH, and to write output data when the clock is LOW.

ABCDEFGH

DataInIOut

PlC

ClockSIL&RCLK

SI ABCDEFGH

3-Wire Serial Inputs and Outputs

When the PlC data pin is configured as an Output, the output voltage level

will overpower the serial output from the PISO through the resistor. When

configured as a high impedance input, the output data from the PISO can be

read through the 2.2 kQ resistor. The timing diagrams to serially read and

write data to and from the shift registers, are shown below:

.ofTiming Diagrams:

~~lJ . ~CIK:LnJl.J n

11 loll loll loll loll loll loll loll 10I. . . . . . . . . . . . . . . . .

IBD IWRI BD IWRI BD IWRI BD IWRIBD IWRIBD IWRIBD IWRI BD iwRl. . . . . . . . . . . . . . . .

D8!aln: IDO1 IDJI 1021 IDJI 1D41 IDSI 1061 1071 I-_._-_.__._.D8!a0ut:IDOl IDJI ID21 IDJI 1D41 IDSI 1061 1071--------

PortTRlS:PortRDIWR:

Ch.ll Port Expansion and External Memory Devices 371

Page 90: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 90/260

 

PracticalAssignment 4: Driving of SIPO and PISO Shift Registers.Construct the circuit on the previous page. Add a LED to .theF output and apush-button to the H input. Place the PlC in the SLEEP mode. When the

button is pressed, the PlC mustwake up and flash the LED. Whenthe button

is released, the LEDmust go ?FF and the PlC must go into the SLEEPmode.-----------------------Serial ,Memory Devices

MicroChip and various other companies manufacture a vast range of serial

memory devices. Some are factory-programmed, some are One-Time-Programmable, some are flashmemories and some are EEPROMbased. For

experimental and prototype work, the EEPROM based devices are the most

appropriate. Two types of communication exist between serial EEPROMmemories and the processor: The 3/4-wire method and the 2-wire PC

protocol. The PC protocol is an industry standard method of serial

communication between various systems and devices.

Basic 3/4-Wire Communication to EEPROM Memories

Initially, only the 93C56 2K-Bit Serial EEPROM will be cover:~din detail.

Data sheets are included in the appendix. Then other members of the 93Cxx

family will be introduced and compared. These memory chips haveessentially four pins for communication:

Clock -ControlledbytheProcessoras theMaster,ChipSelect -to enable the specific chip,Data-In - forconb-ol-anddatabitsto thememory,Data-Out - for the databitsfromthechip.

The Data-In and Data-Out pins can be connected through a resistor to makethe system a true 3-wire system. A system, similar to the bi-directional shift

register system on the previous page, can be used. The standard pinouts of

the 8 pin DIP memory devices are as follows:

1

2

3

4

CS

CLK

DI

DO

Vee

NC

ORG

Gnd

8

7

6 (Organisation)

5

372 PlC Micro-Controller Operation andApplications - Vol.II

Page 91: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 91/260

 

The functions of the other pins of the chip, are:

vcc SupplyGround

ORG Input

-Power to the chip- the common ground connection to the system-hardware connection to select the internal

Organisation of the bits in the chip

-Not Used, and connected to Vcc or Ground.est (NC) pin

The 2K storagebits inside the chip can either be selected to have an 8-bit or

a 16-bit organisation. The selection is made by the hardware connection of

the ORG pin:

256:1t 1-II1II (ORG - 0) 128x 16-II1II (ORG - 1)

BIts:76S43210

Add00

01

02

03

bbbbbbbb

b b b b b b b b

b b b b b b b b

bbbbbbbb

Bits: FED C B A 9 8 7 6 S 4 3 2 1 0

Add00 b b b b b b b b b b b b b b b b

m b b b b b b b b b b b b b b b b

~ b b b b b b b b b b b b b b b b

. . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . 7E

7F

b b b b b b b b b b b b b b b b

b b b b b b b b b b b b b b b bE

FP

bbbbbbbb

b b b b b b b bb-Oorl

The Basic Operation

* The basic operations between the processor and the memory chip starts with

the Chip Select (CS) pin taken mGH by the processor or Master device.

* Then bits are clocked in trom the processor by the positive going edge of the

clock signal. The first bit is a START bit, and it must always be a 1.

* Afterthat a two bit instructions code is sent to the chip. Instructions include

operations such as Write, Read, Erase All, etc. These will be covered indetail.

* Then follows an Address to select one byte of 8-bits, or a word of 16-bits,

depending on the selected organisation.

* The 8 or 16 data bits are either sent trom the processor to be stored, or read

trom thememory chip by the processor. If the instruction does not required

data, e.g. Erase All, the data bit section will be left out.

Ch.]] Port Expansion and External Memory Devices 373

Page 92: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 92/260

 

* The process ends with the Chip Select line going LOW. This will start a write

cycle in the chip, or the chip will go into standby mode. The Data Output pin

from the chip will act as the BUSY indicator, and will stay LOW until the

write cycle is completed.

The Instruction Set

There are 7 possible instructions that can be sent from the processor to the

memory chip. Only three of these will require a data train to either be sent to

the memory, or read back to the processor. The other will only contain the

start bit, the instructioncode and the address bits. The 8-bitorganisationwill

be done in detail first. Then the difference for a 16-bit organisation will be

pointed out.

The Read Instruction

This instructionwill read 8 bits from the addressbyte specifiedin theinstruction. The Random Access Read Cycle sequence is as follows:

Random Access Read Cycle:

ChipSel:J LJ<EnCEYcle)

Notes:

The don't care address bit before A7, shown as x, allows the samehardware

and software sequences to be used for the 93C66 device (4K bits). Here the

additional address bit will be significant.

In a 3-wire system, where the Data-Out and Data-In pins are connected

together, conflictmay exit between the last address bit to the device, and the

dummy 0 bit from the Data-Out pin. A 2.2 kQ resistor should be placed

between the two pins and the Data-In pin taken directly to the processor's

Data I/O pin. A typical connection is shown on the next page:

374 PIC Micro-Control/er Operation and Applications - Vol. 11

Page 93: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 93/260

 

PlC

RBS

RB6

RB7

-

3-Wire Connection Diagram

Sequential Access Reading

It ispossibleto continuereading the data nom the next address directly after

a normal random access cycle. Here the Chip Select control must NOT betaken low. The next data byte train can then be clocked out immediately. It

will follow directlywith the Most Significant Bit first.

Erase/Write Enable and Disable Instructions

As a protection against accidental writing, the memory chip will automatically

be placed in the Erase/Write Disabled mode after power up. Before any

writing can be done to the chip, an Erase/Write Enable instruction must firstbe given. After a sequence of writing cycles, the chip should again be placed

in the Erase/Write Disabled mode by the appropriate instruction to prevent

accidental over-writing. The Vcc taken low and high again will also place the

device in the protected mode.

These two instructions do not require any address or data bits. Some of the

addressbits are used for additional instruction decoding. The data trains forthese instructions are:

Erase/Write Enable: 1 0 0 1 1x x x xx x x (CSgoesLOW)Start Inst. (CodeinAddressbits)

Erase/WriteDisable: 1 0 0 0 0x x x x xx x (CSgoesLOW)Start Inst. (CodeinAddressbits)

Each instruction only requires 12 clock cycles.

Ch.11 Port Expansion and External MemoryDevices 375

Page 94: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 94/260

 

The Write Instruction

The write cycle is similar to the read cycle, except that the d3.ta must be

supplied by the driving or Master device. It must follow the address bits from

the processor on the Data-In pin. After the data has been clocked in, the ChipSelect pin must be brought low to start the internal Erase and Program 1 byte

cycle of approximately 1 milli-second. The Data-Out pin will indicate that

the chip' is still Busy by a 0 appearing on the pin. When the Data-Out pin

goes high, the next write cycle can begin. A Sequential access writing feature

is not available. Only one byte can be stored per write cycle.

The Write Cycle Timing Diagram:

U(EndCycle)

Notes:

If more than the prescribed number of data bits are clocked in before the Chip

Select is brought low, the extra bits will be ignored.

When the Chip Select in brought low before the prescribed number of bits

have been clocked in, no action will take place and the chip will go into the

standby mode.

Data written to the device while it is in the Busy Mode, will be ignored.

The Erase 1 Byte Instruction

A single specified byte can.be erased and l's will be written to all the bits

positions. This instructiondoes not require databits, but the address must be

specified.

376 PlC Micro-Controller Operation and Applications - Vol.II

Page 95: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 95/260

 

Tile Erase 1 Byte Sequential Diagram:

Start I Inst I Address I..Write..Data-In: I I I x A7 A6ASA4A3A2Al AO(CSgoesLOW)Data-Out: (HighImpedance) 0 (Busy)

The'Erase I Byte Instruction will take approximately I milli-second.

The Erase All Instruction

The entire memory can be erased and l's will be written to all the bits

positions. This instruction does not require address or data bits. Some

address bits are used as part of the instruction.

The Erase All Sequential Diagram:

Start I Instl...Code inAddressbits I..Write...Data-In: lOO 1 0 x x x x x x x (CSgoesLOW)Data-Out: (HighImpedance) 0 (Busy)

The Erase All Instruction will take approximately 15milli-seconds.

The Write All Instruction

The Write All instructionwill write the data byte in the instruction train into

all the bytes of the memory.

The Write All Sequential Diagram:

StartIInst Code also in Add 1 Data I..Write ...

Data-In: 1 00 01 x x x x x x x D7 D6 D5 D4 D3 D2 Dl DO (20cycles)

Data-Out: (HighImpedance) 0 (Busy)

The Write All Instruction will take approximately 15milli-seconds.

Ch.II Port Expansion and External MemoryDevices 377

Page 96: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 96/260

 

Practical Assignment 5: Serial Memory Access. Connect a serialEEPROM memory device as shown in the previous section and write routines

to read ftom and write to the device. Switch the power OFF and ON again to

prove that the data was stored in the device.

The 16-Bit Organisation and Other 3/4-Wire EEPROM Serial Memories

The memory device can be configured to be in the 16-bit organisation by

connection the ORG pin to Vcc. The only basic difference is that the chipwill use 1 less significantbit in the address field,and 16bits in the data field.

A summary of the instructions for the 8-bit and 16-bit organisaJions of the93C56 (2K bits) and the 93C66 (4K bits) serial EEPROMmemory chips areincluded in the appendix. A selection guide for other 3/4-wiw EEPROM

serial memory chips is also included. It is recommended that the specifieddata setup and hold times be studied carefully, before a device is used.---------------The 2-Wire PC Protocol and Serial Memories

The PC system for serial communications between various devices is an

industry standard. Each device type has a specific 4-bit code allocated for

selection and identification. The general code for Serial Memories is 1010.

Various other types of devices can alsomonitor the common serial link andonly react when their specific type codes are transmitted.

The protocol of thememory train for 2-wire systems is different ftom that of

the 3/4-wire systems, in toat provision must also be made for the chip

selection in the data bit train. The following general conditionsmust be met

by devices using the I2Cprotocol: (See the circuit and timingdiagrams on the

next page.)

* A Master device will control the clock signal.

* The data pins of the devices have Open Drain outputs and the data linemust

be pulled high by a pull-up resistor (lOkQ). When a device is receiving, ~tsoutput must be set to a 1. Then any other device can pull the line low. The

open drain operation is the same as the RA4 port pin of the PIC16F84. This

pin can operate as a bi-directional port when configured as an output.

* When the bus is not busy, both the Clock and Data lines must be kept HIGH.

378 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 97: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 97/260

 

* Normal Data codes and addresses will only be valid if the data line stays

STABLEwhile the Clock goes HIGH and LOW again, Data may therefore

only changewhile the Clock signal is LOW.

* A START bit, 0, must precede every operation and is identified by the master

pulling the data line LOW, while the Clock is still HIGH.

* Every operation must be ended off by a STOP bit, 1, from the master. It is

identified by the master making the data line HIGH, while the Clock signalis still HIGH.

* The receiver of data, that can either be the master or the slave device, must

generate an Acknowledge bit, 0, after every 8 bits that have been received.

A Typical Connection Diagram:

PlC Vcc::r:a~~

Note: All Data pins arc Open Drain.

RA3

RA4

n. Clock

n - Data

MASTER

PC Timing Protocol

Clock

Data:

BusAvailable! Startbit :: AddorDatabit:, ,

IS b

' I

! top It!

Ch.JJ Port Expansion and External Memory Devices 379

Page 98: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 98/260

 

The 85C82 EEPROM Serial Memory Device (2Kbits)

A typical 2-wire EEPROM memory device, the 85C82, will be used to

explain the basic operation. Then the small variations to use other similar

chips will be explained. Data sheetsfor the 85C82 device are included in theappendix. The pinouts and connections of the chip are shownbelow:

The 85~82 Serial EEPROM Pinouts and Connections:

(A8 to Vcc or Gnd)

(A9 to Vcc or Gnd)

(AIO to Vcc or Gnd)

System Ground

1

2

3

4

8 Supply

7 Not ConnectedInternally6 Serial Clock

5 Data I/O (OpenDrain)

The Chip Select linesAO,Al and A2, are connected by hardware to select a

specific three bit Chip Select Code that would represent lof 8 possibledevices.

The internal storage bits are arranged in 256 bytes of 8-bits each. The byteaddresses are :lTomOOhto FFh:

Bits: 7 6 5

Add

00

01

02

03

4 3 2 I 0

Write Buffer

b b b b b b b b

b b b b b b b b

b b b b b b b b

b b b b b b b b

I

I

b b b b b b b b

2 b b b b b b b b

FE

FF

b b b b b b b b

b b b b b b b b

The Device-, Chip- and Read/Write Selection Code

After a START bit, any operation must start with a Select byte, transmitted

by the master. This byte will select the Device, the Chip and the Read or

Write tofollow selection bit:

* The Device Selection Code is a four bit code. It would select serial memory

devices if the code is 1010.

380 PlC Micro-Controller Operation and Applications - Vol. II

Page 99: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 99/260

 

* The Chip Select Code consists of 3 bits. Only the chip with the matching

hardware connections on its AO,Al and A2 pins, will be activated.

* The 8th bit is a 1 for Read, or a 0 for a Write operation tofollow. It will

inform the selected device to transmit data to be read by the master, or toreceive an address or data written by the master for storage.

* After receivinga byte, a device must give an Acknowledge bit, a 0, until theclock goes HIGH and LOW again.

The following timing diagrams will separate the master and slave data pin

OUTPUT logic levels to indicate what device is transmitting. The common

data linecanbe pulledLOW byany of the devices connected in a wired-AND

configuration.

The Select Byte Timing Diagram:

Clock:

Master Out: I0

SlaveOut:

I I I I I

Start :-<--- PCCode-- -~ ChipCode-~ RJWiAck.:I I I I I

WhentheRead/Write byte is 0, itwill inform the slave device that it must be

ready to receive the address byte. If the RJWbit is 1, the slave must transmitthe data at its current address.

The Address Select Byte

After a Select Byte, ending with the RJW bit cleared, the master must transmit

an address byte to set the internal address counter of the chip. The chip must

again return an Acknowledge on the 9th clock pulse.

For a sequential reading operation, the select byte will end on a 1 for Read.

Then the address byte is not required, and the data from the current addressof the device will be read.

Ch.//. Port Expansion and External Memory Devices 38/

Page 100: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 100/260

 

Tlte Address Byte Timing Diagram:

Clock:

~--

Master Out:

SlaveOut:8I I I I

jACk.1 AddressByte 1 Ack. j

Random and Sequential Reading Operations

Random reading is defmed as a situation where any specific address may beread. Sequential reading is where data bytes are read one after the other from

ascending byte addresses. For read operations, the following sequence mustbe followed:

* The master device must give a START bit, followed by a Select byte. The

Selectbyte must end with a Writetofollow bit, O. On the 9th clock pulse themaster must receive the Acknowledge from the device.

* Then follows a byte to set the current address in the slave device. Again itmust receive the Acknowledge from the device.

* Then the master must give a START bit again, followed by the Select byte

with the R/W bit set for reading.

* The slave will then transmit the data at the current address to the master.

After the byte was sent, the internal address counter will increment.

* The master must then send a STOP bit to terminate the operation.

* In place of the Stop bit, the mastermay also send anAcknowledgeto indicate

the reading must continue. The slave device will then continue to send the

next data bytes in the sequential mode, until a STOP bit is received.

* If themaster knows the current address of the memory device, then it is onlyrequired to send the select byte with the R/W bit set. The data can then be

read immediately. The data train timing diagram is shown on the next page:

382 PlC Micro-Controller Operation and Applications - Vol. II

Page 101: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 101/260

 

One Data Byte Read Timing Diagram:

rI rI rI rI r-Clock:

Slave Out:

I I I ,

iRead iAck.~ Data Byte ~Stop

The Complete Random Read One Byte Sequence: (r = read)

Master: St I 0 I 0 AlOA9A8 0 r A7 A6AS A4A3A2Al AO r

Slave: . r r r r r r r r 0 r r r r r r r r O...

StartI Code IChip Add IW IAckI< Address > lAck.

(Continued... )

Master: ..St I 0 I 0 AIOA2Al I r r r r r r r r r StopSlave: .. r r r r r r r r A D7D6DSD4 D3D2DI DO r

StartI Code IChip Add IRIAckI< Data > I

To read 2 bytes, the master will give an Acknowledge in place of a Stop bitin the second line above.

To read directly without an address given, only the second line has to be

sent where a Read bit ends the Select byte.

The Write Operation

The write operation is in principle the same as the Random Read operation.

The main difference is that another START bit will not be given after the

addiess byte. The master will generate the data, while the slave will receivethe data. The slave must generate an Acknowledge after every byte.

The 85C82has a two-bytewrite buffer. That means it can receive two write

bytes before itmust be released by a STOP byte and left to do the internal

write cycle. It is possible to write only one byte to the memory, then the chip

mustbe releasedby a STOPbit after the first data byteAcknowledge ITomtheslave.

Ch.}} Port Expansion and External MemoryDevices 383

Page 102: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 102/260

 

While the device is busy with the internal write cycle, the slave will not

respond togive anAclmowledgeafter a selectbyte. This can bemed as a test

to fmd out if the internal write is still busy. Only the select byte need to be

sent. If the Aclmowledgeis not received, the device can be tested again after

a short delay. When an Aclmowledge is received, the next byte can be sent.

The write time for 1byte is approximately 1milli-second. If two bytes were

loaded, it will take approximately 2 milli-seconds.

If more than two bytes are written to the device, the existing bytes in the writebuffer will be overwritten.

The Write One Byte Sequence:

Master: St 1 0 1 0 AIOA9 AS 0 r A7 A6 A5 A4 A3 A2 Al AO r...

Slave: . r r r r r r r r 0 r r r r r r r r O...

StartI Code IChip A,ddIW IAckI< Address > lAck..

(Continued.. .)

Master: .. D7D6 D5D4D3D2DI DO r StopSlave: .. r r r r r r r r 0 r

I< Datam > IAI(Write)

To write two bytes, the second data byte must follow directly after the

Aclmowledge from the slave, in place of the Stop command. The Stopcommand is then given after the Aclmowledge from the slave, when the fIrst8 data bits have been received.

While the memory chip is busy with the internalwrite cycle, the master can

address anotherchip on the same line. It need only to transmit another Chip

Select byte. When the fIrst chip is done with its internal write cycle, it willnot generate anAclmowledgeand interferewith other communication on the

line. The Aclmowledge will only be issued if the master transmits a select

byte addressed to that specifIc chip.

384 PIC Micro-Controller Operation and Applications - Vol. 11

Page 103: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 103/260

 

Other 2-Wire Serial EEPROM Memory Devices

The 85C82 device described above, is a 2K bit device, with a memory

organisationof256 x 8 bits. Eight address bits are required to address all the

internal bytes. A smaller device, such as the 85C72 (lK bits) requires

7 address bits only. Then the 8th address can be a don't care value. Bigger

devices, such as the 85C92 (4K bits), have an organisation of two banks of

256 x 8 bits each. One of the 2K banks is selected by the least significant

'Chip Selectbit in the select byte. The AOline of such a chip has no function.

Only four of these devices may be connected in a system to give a totalavailable bit count of 16Kbits. This device also has 8 write buffers.

As the bit size of the memory chips increases, more blocks and less address

pins are used. Data sheets for the 83C82 serialEEPROMmemory device areincluded in the appendix. It also contains a selection guide for 2-wire PC

memory devices.

Communication with a PC through the Parallel Printer Port

With suitable software the Programmer can be used for bi-directional

communicationwith a PC. The combination setting between the MCLR and

the Voltage Control pins must release the micro-controller to run while theprogramming board is still plugged into the board. A simplified interfacing

circuit,using two diodes and pull-up resistors, are shown for the PlC Skeleton

circuit in the last chapter.

The PC must act as master to control the .clock line to RB6 of the PlC. Data

can be sent ftom the PC to pin RB7, configured as an input. Data can also be

returned from pin RB7 of the PlC to the SELECT handshaking line of the

parallel port of the PC. A similar protocol as used for the programmer can be

used to establish the data direction. The first byte or word sent, can define thenumber of bytes to follow.

Ch.ii Port Expansion and ExternalMemory Devices 385

Page 104: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 104/260

 

Conclusion

Most of the properties and direct applications of the PlC l6F84 have now

been covered to a greater or lesser extend. Onemore tool program to enable

the programming of the PIC16F84 in the high level computer language C isleft to do. For many applications, programming in C can drastically reduce

the development time required to write a program. The application of C for

the PlC 16F84micro-controller is covered in the next chapter.

-------

Notes:

386 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 105: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 105/260

 

12. PIC16F84 Micro-Controller Programming in C

Table of Contents

Page

1.Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 393

2: The Basic Building Blocks ofa C-Program . . . . . . . . . . . . . . . . . . . .. 395

3. Key Words in the C-Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 396

4 . I d e n t i f i e r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397

5. The Use of Capital and Small Letters, Spaces and New Lines. . . . . .. 397

6. The use of Comments in a program. . . . . . . . . . . . . . . . . . . . . . . . . .. 397

7. The General use of Procedures and Functions. . . . . . . . . . . . . . . . . .. 398

8. Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 399

9. Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 399

10. The Structure of a C-Program 400

11.DataTypes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 403

12. The Declaration of Variables 406

13. Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 409

14.Operators..... . . . . . ... . .. . . .. . . .. .. . ... . ... . .. . . .. 412

15. The If-Else Conditional Statement Format and Usage. . . . . . . . . . . .. 417

(Continued... )

Rev.5 6/02DNdB

387

Page 106: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 106/260

 

Table of Contents (Continued...)

Page

16. The Switch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . .. 418

17. The While Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 420

18. The Do-While Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 421

19. The For Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 422

20. Program Labels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 422

21. Nested Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 423

22. The GOTO Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 423

23. The Use of Pointers 424

24. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 425

25. Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 426

26. Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 426

27. Unions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 428

28. The typedef Function. . . . : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 429

29. Enumeration Declarations and Use. . . . . . . . . . . . . . . . . . . . . . . . . .. 430

30. The Declaratic;m and Use of Procedures and Functions. . . . . . . . . . .. 431

31. The Use of Pointers to Pass Parameters to a Function. . . . . . . . . . . .. 435

388

Page 107: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 107/260

 

Table of Contents (Continued...) Page

32. Pre-Processor Directives. . . . . . . . . . .'. . . . . . . . . . . . . . . . . . . . . . .. 437

The #asm and #endasmDirectives... . . . . . . . . . . . . . . . . .. 437

The #define and #undef Pre-processor Directives. . . . . . . . .. 438The #if, #else, #error and #endif Directives. . . . . . . . . . . .. 440The #ifdef and #ifndef Directives. . . . . . . . . . . . . . . . . . . .. 441

The #pragmaDirective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 441

The#includeDirective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 442

33. Listing of the 16C84A.h Include File. . . . . . . . . . . . . . . . . . . . . . . .. 442

34. Assembler Instruction Equivalents in C 445

35. The Use of an Interrupt Sub-Routine in C 446

36.The'StartupRoutine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 446

37. Standard Existing Header Files and Library Functions. . . . . . . . . . .. 447

CMATH.H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 447

CTYPE.H. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 447MATH.H 449

DELAY14.H 450

EEI4.H... . :.. . . ... .. 450

38. The MPLABC14.LIB and Other Libraries. . . . . . . . . . . . . . . . . . . . .. 450

39. Exercises, Tutorials and Examples. . . . . . . . . . . . . . . . . . . . . . . . . . .. 453

Exercise 1: Setting the LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . .Exercise 2: A 10milli-second Delay Routine. . . . . . . . . . . . . .

Exercise 3: A 4-Bit Binary Counter. . . . . . . . . . . . . . . . . . . . .

Exercise 4: An 8-Bit Binary Stopwatch. . . . . . . . . . . . . . . . . . .

. Exercise 5: An 8-Bit BCD Up/Down Counter. . . . . . . . . . . . . .

Exercise 6: BCD Up/Down Counter using the Internal Timer.

Exercise 7: Disco Light Chaser. . . . . . . . . . . . . . . . . . . . . . . .

Exercise 8: Potting the Ducks. . . . . . . . . . . . . . . . . . . . . . . . . .

459465

4(jg'f{v'

47iP..

47;fb

48111

485

493--------------------389

Page 108: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 108/260

 

390

Notes:

PlC Micro-Controller Operation and Applications - Vol.Il

Page 109: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 109/260

 

Chapter Summary

This chapter describes the structure and application of the MPLABC C-

compiler for the PICl6F84 micro-controller specifically. Some of the

advantagesand limitationsof using C inplace of the Assembler language arepointed out in the introduction. The fmer detail of some functions in the C-

language are quite complex and it may take considerable time, practice and

~ffortto becomefully acquaintedwith. A general strategyto study and applythe C-Ianguage is suggested. To make things simpler, specific sections to

study first are suggested before each new problem in the exercises is

attempted. The exercises are at the end of the chapter.

The examples,tutorials and exercises are discussed for application in a DOS

environment, and also for using the MPLAB Integrated DevelopmentEnvironment, to make it available to m9re users. MPLAB contains a Text

Editor, anAssembler,a C-compilerand a Simulator interface. A student can

also run the DOS environment system in Windows, by using the samemethod and batch files as described at the end of Volume I. The pp

programmer can be linked to the MPLAB system by opening a Shortcut to the

PP.EXE program in a DOS window. It is started without any input

parameters and left open behind the MPLAB Window. When required, thepp Window can be made active, the new Hex file loaded, and be used to

program theBasic Board. After programming, the Board can be tested withthe Execute menu option and without quitting, the pp Window can be

minimised and placed in the background again.

The notes were set in a format that should lend itself to be used as a reference

with relative ease. All the critical information, such as the exact syntax and

use of the various functions, were placed at the beginning of each section.

Then more detail is included up to a complete description towards the end of

the section. A student only has to read through a section until he gained

sufficient knowledge for his specific application. The table of contents can beused as a reference index to fmd a specific section.

The exercises follow the same problems and route as the Assembler exercises

in Volume I, up to exercise 8 on Potting the Ducks. After that, the user

should have sufficient understanding to attempt the rest of the exercises or his

own projects, by himself.

------------------------------------Ch.12 PIC16F84 Micro-Controller Programming in C 391

Page 110: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 110/260

 

392

Notes:

PlC Micro-Controller Operation and Applications - Vol. II

Page 111: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 111/260

 

1. Introduction

By writing sourceprograms in the C-ProgrammingLanguage for PlC Micro-

controllers,as opposed to using the Assembler Language,many of the tedious

house-holding duties are taken over by the compiler. Items such as the

placing of the variablesused by a program, or which GOTO jump instruction

to place below aBit Testand Skip ifSet/Clear instruction for the correct path

to be followed, will be done automatically by the compiler program. Aprogram in C is alsomuchmore structuredthan an assemblerprogram. This

makes the logic easier to understand when looking at the program after six

months or more. Some of the more well known higher level programming

functions, such as IF statements, FOR loops, DO-WHILE loops and CASE

statements are available to the programmer. In addition, mathematical

operations, such as addition, subtraction, multiplication and integer and

modular division is taken care of by the compiler through some existing

libraries. To summarise, the software development time required for a

program in C can be much less than what will be required for an equivalent

program in Assembler.

Programming in C, however, is not the final answer to all the problems. A

systemstill operateson the principle oflogic levelsread fromthe input ports,

and based on these values, certain decisians are made and specific logic levels

to outputports are generated. The correct timing and sequencing of the data,

and the interpretationof the input and output data still play an important role.

The only part made easier by the C-program, is what happens to the datainside the controller. Due to the limited code and internal memory of the

controller, the C-functions available are limited in scope and operation.

Special care must still be taken of what data, and especially the size of the

data used in a C-program. In addition, the C-compiler must be instructed

exactlywhat to do, and the syntaxof the instruction lines or statements, must

be 100% correct. A thorough knowledge of the internal operation and the

assembler instructions of the controller will be an advantage. It will help to

feed the correct information intothe program and to select the correct options

for the most efficient operation.

Ch.12 PIC16F84 Micro-Controller Programming in C 393

Page 112: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 112/260

 

The implementationof a C-program is similar to that of assemblerprograms.A source file is written on a text editor and stored as a fIle with a .C

extension. The source file will contain certain C-compiler directives to

instruct the program how to interpret the source file. It will also contain the

programming statements in a specific format. This source file is fed throughthe C-Compiler Tool Program, MPLABC.EXE. It will test for errors,

compile the program and generate the normal error-, listing- and hex output

files. T-heerror- and listing files can be inspected, and the hex file can be

loaded directly intothe ProgrammerDriver to programthe device. Generated

fIles can also be loaded into a simulator for logic and simulated time testing.

The scope of the C-programming language is quite extensive with a great deal

of fmer detail in some of the functions. Parameter passing to and from

functions, the inclusion of existing modules and library functions, and also the

use of standard assembler instructions in a C-program can be done. It even

includes the use of interrupt' sub-routines, written in C. Yet a user does not

have to be fully proficient in the language to be able to use it. By following

simple recipes and examples, successful programs can be written with limited

knowledge. A fair amount of background, such as the structure of a C-

program, what identifiers, data types, variables, operators, etc. are, must first

be acquired. All the detail of each section does not have to be known first.

A superficial first time glance at the general format and syntax of the various

sections is required to do the first exercise. The second exercise will require

a bit more in depth knowledge of some of the sections, so the user must

familiarise himself with more and more detail, as it is required.

These notes have been compiled so that it can be used as a future reference

for the C-Ianguage. The structure and usage of the language have been

divided into sections. Each section will explain one concept oftl1e language,

such as identifiers,operators, loops, pointers, etc. The contents pages can be

used as a reference to find the various sections. Each sectionswill start witha brief summaryof the section, the standardformat and syntaxofthe function,

and simpleexamples. Then a more detailedsummarywill followwith a more

complex format and more advancedexamples. After that a brief description,

followed by a more detailed description, and so on. A fIrst time user only

needs to get a basic idea of the exact syntax and what a specific functiondoes, to be able to use the function. As his knowledge increases, the more

advanced formatcan be studiedand applied. As a reference,a user may only

need to look at the initial summary and syntax of a function, or re-read a

section only up to the level required for his specific application.

394 PlC Micro-Control/er Operation and Applications - Vol.II

Page 113: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 113/260

 

A set of exercises and examples, and also some helpful hints in the

application of C-programs are included at the end of this chapter. It isrecommendedfor a first time user to read through the notes up to section 14

onOperators,before the first example and exercise are attempted. This will

supplythe user with somebackground on the general structure and buildingblocks of a C-program. All the details do not have to be known by heart for

the fIrst time, and the user can go back and re-read some sections in more

.detail as it is required.

The C-compiler MPLABC.EXE version 1.1, that has been used for test

purposes while these notes were written, does not recognise the PlC 16F84

processor. The standard includefile for the PlC 16C84A has therefore been

used throughoutthe exercises. The File Register and memory maps of these

two processors are identical. Therefore, it would make no difference to thecode generated.

2. The Basic Building Blocks of a C-Program

A program is built up by some of the following building blocks:

* Compiler directives, that will instruct the compiler how to interpret the rest

of the program.

* Key words, that will identifYa certain type of operation to follow.

* User-defmed identifiers are used for the names of variables, constants,

procedures, functions and macros.

* Various operators, such as +, -, =, etc., are used to instruct the compilerwhat to do with the data.

* Finallythere are program flow and delimitermarkers, such as {, }, ;, /*, */,

etc., that will group sets of statements together.

Ch.I2 PICI6F84 Micro-Controller Programming in C395

Page 114: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 114/260

 

3. KeyWords in the C-Language

There are 28 key words in thi~ version of C and an additional 6 words that are

reserved and cannot be used as user-defined identifiers. After each key word,

the compiler expects a sequence of specific information to follow. Thestatements and syntax used in C are very compact. Every word and operator

used, and also the context and place where it is used, is important. It informs

the compiler exactly how to interpret the program. The format and syntax of

a program must therefore be very precise. This preciseness helps to make a

program more compact, but it can also make some statements much more

complex than what meets the eye. Initially, one may have to analyse existing

statements repeatedly until the syntax is interpreted and understood with ease.

The 28 keywords are includedbelow. The six reserved words are printed initalics underneath. They are not implemented by this version of C for PlC

micro-controllers. They are standard C key words and are still reserved. One

key word, bits, is not a standard C key word, and is PlC C-compiler specific.

There are also someReservedwords for the compiler directives, but they are

normally preceded by a # marker. These directives and pre-processorstatements will be covered in detail in a later section.

396 PlC Micro-Control/er Operation and Applications - Vol. 11

Key words: bits long switch typedefbreak else main unsignedcase enum union voidchar extern return volatile

const for shortcontinue goto signeddefault if while

do into struct

Reserved: auto float sizeo!double register static

Page 115: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 115/260

 

4. Identifiers

An Identifier is a user-defined word, that is not a key word or one of the

reserved words. It can be the name of a variable, a constant, a procedure, a

function,a macro or a program statement label. It must startwith a letter, anditmay containno internalspaces. The rest of the identifiermay consist of any

combination of alpha-numerical char&cters. It can also contain some

.punctuationor underscore ( - ) characters, as long as it will not be confused

with normal operators, such as +, -, t, *,., etc. Identifiers are case

sensitive, i.e. if the identifier is defined as small-, capital- or a mix between

small and capital letters, then the same combination must be used in the rest

of the program..

5. The Use of Capital and Small Letters, Spaces and New Lines

To set a standard, all the names of procedures, functions and variables are

normally used as small letters. Only key words are forced small letters.

Defined macros are usually capital letters only. A macro is a set of words,

numbersand operators defined in a singlemacro name. It will be replaced by

the original defined contents during compilation time.

The numberof spaces ornew linesused ina C-programhave no significance,

andmaybe included at will. Where it will play a roll, is when it is placed in

the middleof a word, left out where at least one space is required, or between

the quotes of a string: "Here the placement and number of spaces and newlines will count!"

6. The use of Comments in a program

The abundantuse of comments in a program is highly recommended. It will

guide and refresh the user in the logic used when the program was written.

Even the program name, description and date of a program should beincluded. Comments will not make the final machine code longer. Their

absence, however, may make future interpretations of what the program is

supposed to do, to take much longer to re-understand!

Ch.12 PIC16F84Micro-Control/er Programming in C 397

Page 116: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 116/260

 

A comment may be inserted anywhere in a program where a space may be

placed, exceptbetween quotationmarks. Itmay be a fewwords long, or coverseveral lines. A comment must start with a 1*,and end with a *1. It will

informthe compiler to ignore everythingafter the first 1*,up to where the fIrst

*1is encountered. These markers can alsobe used to block out somestatementsin a program temporary. Comments may not be nested: Le. another comment

must not be placed within the comment markers. The compiler will start tointerpret.the statements immediatelyafterthe first end-of-commentmarker wasreached.

Another way to specifYshort comments, is the use of a double slash, 11.This

will ignore everything following the markers up to the end of that line. Thenew line at the end of the line is used as the end-of-comment marker.

7. The General Use of Procedures and Functions

Procedures and functions are in principle the same as the calling of a sub-

routine. A procedure or a function is defmedelsewhere,and the main program

willjump to and execute the "sub-routine",before itwilljump back to continue

the main program. The difference between a procedure and a function is that

the procedure will jump to the other routine to do something there, and justreturn. A function in turn, will jump to the other routine, do some operations

there, but it will return a value back to the main program.

An example of a procedure is a routine that will place a specific code on one

of the output ports. What was done in the routine will not influence the rest of

the program directly. A procedure will be executedby simplyplacingthe name

of the procedure in a program line. A function again, will be for example, a

routine that will read a value trom in input port and bring the value back into

the main program. The functioncan be placed in an equation. The return valueof the functionwill then be used in the equation. The differenceis, a procedurewill return nothing (a void), while a function will return a value.

Another procedure or function may also be called trom within a procedure or

function. This can be done IIp to 8 levels deep -the depth of the stack of the

PIC'84. Before a procedure or a functioncan be used, it must fIrstbe declared

or defmed outside and before the calling routine. The correct method and

syntax will be discussed in a later section under TheDeclaration and Use of

Procedures and Functions.

398 PIC Micro-Controller Operation andApplications - Vol.II

Page 117: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 117/260

 

8. Statements

A statement is an operation that must be executed. It may imply a group of

operations,but is stilItied up in one group. A statement must end with a semi-colon. Examples are:

x=O;

x++;

time( );

x = readkey( );

II Replace variable x with zero.

II Increment variable x by 1.

II Call and execute the procedure time().

II Call function readkey and place return value in x.

II Empty statement - do nothing: e.g. whiIe(l);

9. Blocks

A block is a group of statements tied together between a set of braces - Braces:

{ }, as opposed to brackets, [ ], or parenthesis (). For clarity, the whole group

is normally indented as well.

Ch.12 PlC16F84 Micro-ControllerProgramming in C 399

Page 118: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 118/260

 

10. The Structure of a C-~rogram

Shownon the next page, is the basic structure of a C-program. Every program

must have a main program block, called main(). This is where the programwill start.

A normal program for a Personal Computer will have a starting point and an

ending point, where control will be handed back to the operating system. Aprogram for amicro-controller, however, does not have an end. Itmust either

repeat itself continuously, go into the SLEEP mode at the end, or just sit and

idle continuously until either the power is switched off, or the Eeset button is

pressed. In short, the C-program for a micro-controller never exits out of the

main program. To complywith the standardC-format, the main program must

be declared as returning a void (nothing).

A Simple C-Program Structure Example:

#pragma <controls for the C-compiler >

#include <16C84A.h> 1*Tells compiler which processor is used *1

void main( )

{II Start of main program with an initial....II brace around the statementsof the module.

local variable declaration;

I st program statement;

2nd program statement;

etc., etc. .....

Stop or idle statement;

} IIClosing brace of the module.-------------------

400 PlC Micro-Controller Operation and Applications - Vol. 11

Page 119: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 119/260

 

A More Complex Structure of a C-Program:

#include <16C84A.h>

#include <other include files>

#pragma <controls for the compiler>

#define MACRO_NAME <items that would replace the macro name>

global variable declarations;

global constant declarations;

1*Tells compiler which processor is used *1

type fUDctioD_name(vars..) IIDeclaration and definition of a function

{ IIOpening brace for the function statements

local variable declaration;

1st statement;

2nd statement;

return return_value;

type function_name(vars..); IIDeclaration only. Defmition not included.II The definition must be included elsewhere

void main( )

{ local variable declarations;

1ststatement;

etc. etc..;

key_word - startinlL a_loop

{ II Starting brace for loop statements

1st loop statement;

2nd loop statement;

} IIClosing brace for loop statements

next main program statement;

etc. etc ;

} II Closing brace for main program

type functioD_name( vars...) /I Define previous declared-only function

{ local variable declaration;

1st statement;

etc. etc ;

}

Ch.l2 PlCl6F84 Micro-Controller Programming in C 401

Page 120: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 120/260

 

Discussion of the C-Program Structure

In the simple example, the program starts with the pre-processor lines, that tells

the compiler what settings are required. These wiUbe discussed in full, but for

now the only important one is the processor used. This is impoI1:ar!t,because thesame compiler is also used for the other members of the family with different

architectures and memory sizes.

Then follows the mainprogram. It is alwayscalled main( ), and th9arenthes~after the name identifies it as a procedure. It is followed by the opening brace.

Braces are { }, as opposed to brackets, n, -or-parenthesis, ( ). The voidlS

included to comply with the general structure of C-programs.

At the top of the main program, the local variables are declared. These are thevariables that will be used and are only valid in the main moduli. Thisdeclaration ends-With a semi-colon. Then follow the programming statements,

each ending with a semi-colon. Finally the closing brace ties the statements of

the main module together.

In the more complex example, a few more items have been added: There is a

statement to include some other program modules. These may be for example,

the maths library, math.h, that contains standard functions for multiplication

and division. These need only be included if they are going to be used in theprogram. A macro definitionfollows. This definitionmay also be placed later

in the program, as long as it is declared before it is used.

The declaration of global variables outside any of the main or other routines,

allows these variables to be usedby any of the other functions,without having

to declare them first. These global variables can also be used for parameter

passing to aDd from procedures and functions. Some memory saving

techniques also involve the use of global variables.

The structure of a function declaration and defmition follows. This declaration

and definition must be placed somewhere in the program outside and before the

module that it is called from.' That the structure of the function is in principle

the same as the structure of the main module -opening brace, declarations,

statements and closing brace. If the function must return a value, a return

statement must be included at the end of the function.

402 PlC Micro-Controller Operation and Applications - Vol. 11

Page 121: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 121/260

 

The next function declaration does not include the defmition part. ~tual

definitionis includedlater, after the mainmodule. In this case, the declaration

line ends in a semi-colon, in place of the opening brace. The format for the topline of the actual definition after the main module, must be similar to the

declaration line usedbefore the calling routine, but without the semi-colon. It

is just placed at a different position. This option allows the user to place hismain module at the beginning of the-program, -with all the fuDction and

procedure defillftionsafFerwards. - 9nly ~e d~claration l~es n~~cLQ..b~

included before the mam routine.--

The main routine follows. It also contains a basic loop structure. The loop

structurewill startwith a key word, such as for example, the DO key word. It

is followeddirectlyby an openingbrace for the loop statements. A semi-colon

isNOT included. This brace and the programming statements of the loop arenormally indented to identify the group. A closing bracket will group them

together as a loop. After the loop, the main program continues up to the fmal

closing bracket.

After the main routine, all the definitions of the declared-only functions can

follow. NoEND statement is included in the program. The compilerwill count

the numberof opening and closingbraces, and ends offwhen they are equal and

no more keI words are ~~c<:un.!.er~<!..

11. Data Types

The data types available for PlC micro-controllers are as follows:

void

bitschar (signed and unsigned)

int (signed and unsigned)

long (signed and unsigned)

pointer (near or far)

no data type

8 data bits (in one byte)I byte or I character

I byte treated as a number

2 bytes treated as a number

address pointing to RAM or Code

A more detailed list of data types and data type modifiers, and also the

maximum value limits, are shown on the next page:

Ch.i2 PIC16F84Micro-Control/er Programming inC403

Page 122: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 122/260

 

Modifier and Type Maximum Value Limits

void None (used when no value is returned)

bits 8 Data bits (individually accessible)

char o to255

unsigned char oto255

signed char -128 to +127 (two's complement)

int oto255

unsigned int (also unsigned) oto255

signedint -128 to +127 (two's complement)

short int (also short) -128 to +127 (two's complement)

long int (also long) oto65535

unsigned long int oto65535

signed long int -32768 to +32767 (two's complement)

near pointer (e.g: near *p) o to 3Fh (Internal Registers and RAM)

far pointer (e.g:far *p) o to 3FFFh (Code memory)

Discussion of Data Types

To enable the compiler to do the correct and most efficient operation on data

in the controller, the data type must be specified in a variable declaration

statement before it can be used. In thisway, the maximumsize of1.hedata and

memoryspace required are knownbeforehand and the compiler does not have

to provide sufficient space just in case the values are bigger.

404 PIC Micro-Controller Operation and Applications - Vol. 11

Page 123: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 123/260

 

Take for example a statement that must add two bytes together and store the

result in anotherbyte, e.g. Z= x + y. Strictly speaking, x and y can be any value

from minus a very large number up to a very large positive number. Adding

two very large positivenumbers together will result in an even bigger positive

number. The instructions required to do such a multiple byte addition can be

quite extensive. A four-bytenumber plus another four-byte number can result

in a number requiring up to five bytes long. If it is known that the numbers x

and y are only limitedto 8 bits each, then all the instructions to add the higher

'emptybyteswill be unnecessary.If it is further known that the sum will not be

bigger than onebyte, then even the testing if a carry resulted from the addition

is unnecessary. Also knowing that the two numbers will always be positive

with a positive result, unsigned values can be used. It allows the use of larger

values, Le. 255 in place of+127. The final operation may be limited to a few

instructions only.

By defIning the data types, and therefore the size limits as well, the optimum

code can be generated by the compiler. Conversion between data types is

possible,but to prevent~~~beingJost,conversionsmustbe doneupwards,Le.from a smaller data type to a bigger type. It is done by casting the varable or

constant to another data type. This conversion must also be done before the

operationthat will result in the bigger size data. If a byte value is going to beadded to anotherbyte value, the result may be two bytes long. Then the bytes

must first be defmed or converted to long or unsigned long values with zerohigh bytes,before it is added. The compilerwill then generatethe correct code

and prevent the data of the higher byte being lost.

The casting of a data type to another data type is done by placing the new data

type in _p~enthesis just before the existing variable or constant name, e.g: -

IIDelaration of 8-bit signed integer

//16-Bit signed long integersigned int a;

sighed long b;

b = b + (long)a;

Ch.i2 PICi6F84 Micro-Controller Programming inC 405

-.

Page 124: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 124/260

 

12. The Declaration of Variables

The simplified format for the declaration of a variable is:

.~ [The mor.ecomplex format i~:

[modifier] data_type variable_name [= init value [@ add]] [,var2, ]

Examples of VariableDeclarations:

charvar1;charvarl = 0;inta,b,c;intd= 5, e = 6, f;

bitsflags;char array[5];

char count @ OxOC

char cnt2 @ &count

II Initial value specified.

IIMore variables of the same type.

II Accessible as a byte or individual bits

II Character array with 5 elements, 0 to 4.

II count will be placed at address OCh

II cnt2 will be placed at the address of count

Discussion on the use of Variables

A variable is a value stored inmemorythat can change during the executionof .

a program. The storage location is given a name and a specific size of memory

is allocated during the declaration of the variable. Such a variable name can

then be used in an expression or calculation to use or change the current data

in that memory location.

A localvariable is declared in the beginning of a module and can onlybe used

in that module. If another procedure is called from within that module, thatsame variable cannot be used in the other module. The value muSteither be-

transferred into the new procedure using special techniques of parameter

passing. Here a new variable will be created and the transferred value will be

loaded into the new variable. Complete detail can be found under the section

on The Declaration and Use of Procedures and Functions. !>noti!.ermethod

of transferring values between-m_oduless to s~J~ use g~bal ~ariables.

406 PlC Micro-Control/er Operation andApplications - Vol.Il

Page 125: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 125/260

 

Once a procedure is completed, the values in the local variables are lost and

cannot be accessed ftom any other module. The compiler also does not

automatically release the space occupied by the local variables for the local

variables of other routines. This will use up the limited memory space very

quickly if special care isnot taken for memorymanagement. Global variablesare declaredat the beginningbefore the main routine or any other functions or

procedures are declared and defmed. They are then available to all modules.

Individual bits of a byte can be accessed by declaring the byte as a bits data

type. A bit can then be accessed by using the '.' operator, followed by a

number ftom 0 to 7. An example is:

bitsflags; // Declaration

flags.2= 0;flags.5= 1;flags.C= 0;

// Clears only bit 2 of flags

// Sets only bit 5 of flags// Cmusthavebeendefinedbefore.

(Note: The '.' operator also works for File Registers, e.g. PORTH.3 = 0)

The Format of a Variable Declaration

Variable declarations are nonnally ptaced either before and outside any

procedure as global variables, or at the top in a module, just after the opening

brace, as a local variable. Transfer variable parameters to functions and

proceduresare declaredin the top declaration line of the function between the

parenthesis.

The variabledeclaration starts with a key word, that is either a data type, such

as void, char, int, long, etc., or a data type modifier, such as signed or

unsigned.

After at least one space, the unique name of the variable follows. It can be in

capital letters or small and is case sensitive. Itmust start with a letter, followed

by any combination of alphanumeric, allowable punctuation or undersc<:!~e-characters. The name may not contain any spaces. If more variables of the

sametypere required, the rest of the variable namesmay follow, separated by

commas. Spaces are not reguired, but can be used for clarity.

Ch.i2 PlCi6F84 Micro-Controller Programming in C 407

Page 126: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 126/260

 

An initialvalue may be allocated to a variable by adding an equal sign and the

value immediately after the variable. Spa~s a.!:-e1Q!I~<I!!ir~ but can be

included. The initial value will be loaded into the variable before any of theinstructions of the module are executed.

fA specific address location for the variable may be forced by usiug.the @ sigJ1., - --- -- - -- ~- --

" after the variable name (and initial value), followed by a valid address. The

~~ ad_dress~pecificationmay also be referred toas the address of anothervariable,.by using the & sign directlybefore the other variable, for example,&charvar1.

-If the location ISnot specified, the compiler will select varIable-locatIOnsat

will. The user-defmed variables may not be the only variables that require

memory space. When existing libraries are used, such as the math.h include

file, quite a few additional variables may be defmed in these files. Memory

management and conservation are therefore always important.

A variable declaration must always end with a semi-colon, except function

transfer parameter variables in parenthesis. These will be dealt with in thesection on the declaration and definition of Procedures and Functions.

Declarations for pointers, arrays, structs and unions will be dealt with in

separate sections.

The Definition of Re-usable Global Variables for Memory Conservation

One can make all the variables global right at the beginning, but then one will

loose the flexibility of having specific variables with suitable names in one

module. A 10-times counter in a module may have to be used as a lOO-times

counter or a second FOR-loop counter in another module.

It is possible to force a local variable to be at a specific memory location, andtherefore re-use some local variable memory space and keep the names

sensible. The solution is to identify the maximum number and type of local

variables that will be required for any procedures during the planning stage.

This number and type of variables are then defmed as global variables with

general names, such as charvar1, charvar2, intvar1, longvar1, etc. The

compiler will then allocate these variables tomemory locations at will, when

the program is started. At the beginning of eachmodule, local variables mustbe declared with sensible names, and forced into the same locations as the

general global variables with the at, @, and the address of, &, fimctions.

408 PlC Micro-Controller Operation and Applications - Vol. 11

Page 127: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 127/260

 

The local declarationwill then specifYthe address of one ofthe general global

variables as the address location. Examples follow below:

char loop @ &charvar I; II Forces the location to be the same

II as the address of charvar I.

II lobyte at same location as longvarl

II hibyte at the next location.

int lobyte @ &longvarl;

int hibyte @ &Iongvar1 + 1;

"Anothermodule can declare a local variable later as:

char counter @ &charvar 1; II To use the same variable location.

13. Constants

The fonnats for the declaration of constants are shown below:-- --- - -

const data_type identifier =value;

const data_type identifier = value,identifier= value;

Examples of constant declarations:

const char eof= 26;

const int vat = 14;

const signed int scale = 23, shift = -13;

constunsignedlong=42455;

const char array[3] = {OxCC,Ox66,0x33};IStoredincodeEEPROM

The Use of Constants

In some type of programs it may be required to frequently use some constant

values, suchas scale factors,VAT calculations,etc. If these constantvalues are

fixed and will never be changed, then tbe numeric values can be used as is in

the programming statements. If, however, there is a chance that these values

might change in the future, then the numbers should rather be defined a~

constantsat the beginningof the program, and the constant identifierused inthestatements instead. - ---

Ch.12 PlCJ6F84 Micro-Controller Programming in C 409

Page 128: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 128/260

 

During compilation time, the constant identifiers will be replaced by their

defmed values. When there is a change in a value, then only the defmition line

has to be updated. That will update all the values used in the program

automatically during compilation time.

By using a constant identifier in place of the actual value, the clarity of astatement can also be enhanced for future inspection. It will remind the user

what was done in a specificstatement. Take the example where the value read

IToma sensormust be multipliedwith a specificscale factor. A statement such

as " output = temp * scale; " makes more sense than" output = temp * 324; If.- ---

Constants can also be defined as local constants or global constants, depending

on the position in the program that they are defmed. Global constants can als~

be defmed by the #define directive.

AJookup table based in the code can be used by declaring the lookup values as

a constant array. Offset values are then used as the index to array element~

The Format of a Constant Declaration:

The format of a constant declaration starts with the key word COIst, followed

by the data type and the user-defmed identifier name. Small letters are

normally used, but it can also be capitals or mixed, and it is case sensitive.

After the identifier followsan equal sigh and then the value. Ifthere are more

constants of the same type to be declared, these can follow after a commawith

the value of each identifier specified. The declaration must end with a semi-colon.

Various methods of value specification can be interpreted by the compiler. The

default radix is decimal. Decimal and other formats for constant value

specifications are shown below:

const char one=49; IIDecimal 49 (default radix decimal)

const char one =Ox31; II Hexadecimal (preceded by Ox..)

const char one = 071; IIOctal (preceded by the number 0)

const char one = 'I'; IIASCII char 49 (in single quotes)

const char string[] = "Help"; IIStringconstantindoublequotes.const char eof= 26; IIEnd-of-file character

const char newline = '\n'; IINew Line escape sequence (OAh)

constchararray[3]= {OxCC,Ox66,Ox33};II Stored in code EEPROM

410 PlC Micro-Controller Operation and Applications - Vol. 11

Page 129: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 129/260

 

Other Escape Sequences often used:

\a\b

\f\n\r\t

\v\\\?\'\It

Bell (alann) character

Backspace characterForm feed character

New Line character

Carriage return characterHorizontal Tab character

Vertical Tab character

Backslash

Question mark character

Single quote characterDouble Quote character

07h

08h

OCh

OAbODh

09h

OBh

5Ch

3Fh

27h

22h

Most of these escape sequences will only have real significance when used on

a computer screen. They can be used by a micro-controller if the controller is

linked to a PC to generate some menu or monitoring data display directly on the

computer screen.

Ch.J2 PlCJ6F84 Micro-Controller Programming in C 411

Page 130: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 130/260

 

14. Operators

r The format for the use of operators in a statement is:

( variable- n~e ~ o~erand o~erat-or o;erand operator operand;-- - -.L...

\ where the operands are either variables, constants or functions.

A unary operator operates on one operand (to the left or to the right).

A binary operator operates on two operands (both sides)

l A bitwise operator operates on the corresponding bits of operands.

Summary or Operators and their Precedence:

Precedence Operators Type

highest ()[]-t.!-++--+-*++--* / %+ -

« »< <= > >=

= !=&

unary

unary

iillary

binary

binary

binary

binary

binarybitwise

bitwise

bitwise

binary

binary

(Special)*= /= %= &= "= 1= «= »= Assignments

Separator/Delimiter

& (type)

1\

I&&

11

?:=+=-=

lowest

Theprecedence indicates what operator is evaluated fIrst. Openltors of equal

precedence are operated on from left to right. If there can be any ambiguity,

parenthesis should be used.

412 PlC Micro-Controller Operation and Applications - Vol. 11

Page 131: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 131/260

 

Parenthesis, Brackets and Pointers: ( ) [ ]

Parenthesis, (...), group together sections of an expression that must be

evaluated first. Theymay also be nested: (...(...)..)

Brackets, [ ], are used to specify the parameters of an Array.

.(Braces, { }, are used to group program statements together.)

is a pointer to a structure member.

separates the index for a struct, union or bits data types. For bits the

indexmay be from 0 to 7 only. It will also work with char and int data

types to select a specific bit of the byte, e.g: STATUS.S is RPO.

Unary Operators:

+a value stays as is, e.g: if a = -16 then +a = -16.

-a negate value, e.g: if a = 16 then -a = -16.

++a will increment a before it is used,e.g: if a = 2, then after c = ++a, c will be 3 and a will also be 3.

a++ will increment a after it was used,

e.g:if a = 2, thenafter c = a++, c willbe 2 and a willbe 3. .

--a will decrement a before it is used,

e.g: if a = 2, then after c = ua, c will be 1 and a will also be 1.

a-- will decrement a after it was used,

e.g: if a = 2, then after c = a- -, c will be 2 and a will be 1.

Can be used as a single statement, e.g: a++; is the same as a = a + 1;

Ch.!2 PIC!6F84 Micro-Controller Programming in C 4/3

Page 132: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 132/260

 

414

Arithmetic Binary Operators:

Usually operates on similar data types, e.g: int to int, or long to long. Ifused

for different data types, it will result in the highest order. If the destination

variable is smaller, data may.be lost. The order is: Long, int, char.

*Multiplication of long or int.

/ Division of long or int. Integer division results in the integer dividend

and the remainder is discarded, e.g. 5 / 3 = 1.

% Modulus, or the Remainder of integer division, e.g. 5 % 3 = 2.

+ Add operators. Use spaces to prevent confusion with unary +a.

Subtract right-hand operator from left-hand operator.

Relational Operators: (Lower precedence than ArithmeticOperators)

Compare operators and result infalse (0), or in true (non-zero value)

Equal to: a = = b results in true orfalse. Both a and b stay unaltered

- as oppose to a =_b:.~h_e~ ~- is!.eI?!~edby b.

> Left operator bigger than right for a true result.

>= Left operator bigger or equal than right for a true result.

< Left operator smaller than right for a true result.

<= Left operator smaller or equal than right for a true result.

!= Operators not equal for a true result.

PlC Micro-Controller Operation and Applications - Vol. II

Page 133: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 133/260

 

Logical Operators: (Lower precedence than Relational Operators)

&& Logical AND for true and/a/se results: a> b && c = = d.

11

Logi~1 OR for true and/a/se res1!lts:a> b 11 = d.

Lo~ical NOT for true or/a/se results: !a (Unary operator).--

Note:

(c<d)

Use parenthesis to prevent confusion, e.g. (a>b) &&

Bitwise Logical Operators: (Operate on the operands bit by bit)

& Bitwise AND, e.g: OxOF& Ox63is 00001111B==-=--:::.--=- AND 01100011B

= 000000 lIB

Bitwise OR.

Bitwise XOR.-- --«

Bitwise ~hift L~!1 filling with O's:x « 3 shifts x 3 bits left.

»Bitwis~ S~ft Ri~t~-------

Ifunsigned, fills with O's

If signed and positive, fills with O's.

If signed and negative, fills with I's.

One's complement: alii's become- O's and all O's become I's.--

Assignment Operators:

= Left variable is replaced by right expression.

+= Short form for x = x + 2 is x += 2.

-- Shortformfor x= x- 2 is x -= 2.

*= Short form for x = x * 2 is x *= 2.

Ch.12 P/C/6F84 Micro-ControllerProgramming inC 4/5

-J

Page 134: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 134/260

 

/= Short fonn for x = x / 2 is x /= 2.

%= Shortfonn for x= x % 2 is x%= 2.

«= Shortfonn for x = x «2 is x «= 2.

»= Shortfonn for x =x »2 is x »= 2.

&= Short fonn for t= t & f is t &= f. (t and f are true or false operators.)

1\= Short fonn for t = t 1\ f is t 1\= f.

1= Short fonn for t = t If is t 1= f.

ConditionalExpressions: .

? : If true, then fIrst expression, else, second expression.

Eg:z= (a > b)? c: d If (a> b), then z = c, else z = d.

------------------------------

(Note: For first time users it is recommended to skip over at this point and

attempt thefirst exercises at the end of this chapter. Therest of the contentand

a more thoroughstudy of theprevious sections can be done as it is required.)

416 PlC Micro-Controller Operation and Applications - Vol. 11

Page 135: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 135/260

 

15. The If-Else Conditional Statement Format and Usage

1. if (condition) statement;

next_statement;

2. if (condition)

{ statement_I;

statement_2;

statement_3;

}

next_statement;

3. if (condition) statement_I;

else statement-2;next_statement;

/* Execute statement if condition true */

/* else skip and continue. */

/* skip or do the block */

/* Do only statement_I if true. */

/* Or do only statement_2 if false. *//* Do after statement 1OR 2. */

4. Statements 1 and 2 above can also be {Braced Blocks}

5. if (condition){ statement;

statement;if (condition) statement;

else statement;

next_statement;

}

else statement;

next-statement;

6. if (condition) statement;

else if (condition) statement;

/* A nested if */

/* Associated with ifwithin braces */

/* End block

/* Associated with 1st if

*/

*/

/* Test if 1st ifwas false */

/* Execute and jump to after else. */

else if (condition) statement;

else if (condition) statement;

else statement; /*Executeif noneof the above. *//* Can be an empty statement, ";11 */

/* Continue after anyONE ifabove*/next_statement;

(See the switcll in the next section to replace multiple else if statements.)

------------------Ch.I2 PlCI6F84 Micro-Controller Programming in C 417

Page 136: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 136/260

 

16. The Switch (or CASEstatement)

The switch function replaces a multiple of else if statements. The generalformat is as follows:

switch (expression)

{ case constant_expression:

/* key word plus some expressionthat would result in a value. */

/* A constant_expression will alwaysresult in the same value. Note the

colon, :, after the line. */

statement;

break;

case constant_expression:statement;

case constant_expression:statement;

statement;

statement; /* Braces not required between cases. */

break; /* Break out of switch */

case constant_expression:statement;

break; /* Break out of switch */

case constant_expression:statement; /* No break; See notes below */

case constant_expression:

statement;default:

statement;

/* Break out of switch */

/* Can be left out */

}

next_statement;

Notes on the Evaluation of Case Statements:

When the expression after the key word switch has been evaluated, it is

compared with each constant expression after the case key words. If a match

of a similar data type is not fOWldafter a case statement,the statementsafter the

colon of the case line will be ignored up to the next case statement. Then the

original expression will again be compared in the next case line.

418 PIC Micro-Controller Operation and Applications - Vol. Il

Page 137: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 137/260

 

Ifmatch is found, itwill execute all the statements followingthe colon up to the

end of the switch, including the default statements. If a break statement is

encountered, the program will break out of the switch.

If no match was not found, only the default statements will be executed. The

default linewill capture any value and these statements will be executed. If the

default or any of the followingcasematchesmust not be executed after a match

is found in a case line, the set of case statements must end with a break key

'word and semicolon, to jump out of the switch block.

-----------------..-

Ch.12 PlC16F84 Micro-Controller Programming in C 419

Page 138: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 138/260

 

17. The While Loop

Operation: Evaluate a condition before the execution of a group of statements

and execute it if the condition is true, or jump over the group if false.

Format:

wbile (condition) statement; /* A true or false condition */

/* Up to end of single statement*/

while (condition)

{ statement;

statement;

statement;

/* No semi-colon */

} / *Up to end of braced block */

Use break tojump out of the loop.

Use continue to jump back immediately and do the conditiontest again.

Example:

To simulatean Idle Statewhile the micro-controllerwaits for a timer roll-over:

bits INTCON;

while (INTCON.TOIF= = 0); /* While TOIFflag is clear, do n;n

(nothing) */

------------------

420 PlC Micro-Controller Operation and Applications - Vol. II

Page 139: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 139/260

 

18. The Do-While Loop

Operation: Evaluate the condition after the execution of a group of statements,

Le. the routine will be executed at least once. If the condition is true, the

routine will be repeated from the beginning, else it will continue with the nextstatement after the while conditional test.

Format:

do

{

/* Start of routine with no colon*/

statement;

statement;

statement;

} while(condition) ;/* Note the colon after the test. */

Use break to jump out of the loop.

Use continue to jump forward to test the condition immediately.

-----------

Ch.12 PIC16F84 Micro-Control/er Programmin~ in C421

Page 140: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 140/260

 

19. The For Loop

Operation: Repeat a statement or block of statements for a fIxed nwnber of

times. Some variables may change for every repetition.

Format:

for (initial_setting; conditional_test; change-per_Ioop)

statement; /* single or a braced block */

Example:

int ij = I; /* declare variables i andj */

for (i =0 ; i < 9 ; i++)

j++;

/* i counts from 0 to 9. ~xecute */

/* 9 times while condition is true. */

Use break to jwnp out ofthe loop.

Use continue to jwnp back, increment, and do the condition test.

20. Program Labels

The loops in C do not require user-defmed labels to return to the beginning of

the loop. The only labelsthat willbe generated automaticallyare the names of

the main-, and any other procedures and functions. To defme a label as a

destinationfor a GOTO statement,a user-definedidentifIeris placedagainst the

left margin, followed immediately by a colon. A label can also be used to

indicate a point in the program where a breakpoint must be inserted in the

Simulator. Program labelsare module specifIcand a label in onemodule is notaccessible from another module.

Examples:

end:

break!:

/* A label called end */

/* A break point for the simulator. Note: The breakpointmust still be defmed and set in the Simulator. */

422 PlC Micro-Controller Operation and Applications - Vol. 11

Page 141: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 141/260

 

21. Nested Loops

Any of the WIDLE, DO-WHILE or FOR loops, or a mixture ofloop-types may

be nested up to 15 times. A break statement will break out of the current loop

into the previous nested loop. To break out of a few nested loops, the GOTOstatement may be used.

22. The GOTO Statement

If the program must jump out of a deeply nested situation, say when a

terminating error occurs, then the GOTO instruction may be used. The

destination label must be defmed in the same procedure or function module.

The definition of a programming label is shown in a previous section.

Usage:

,

GOTO end;

,

end: /* Programming label with a colon */,

-----------------------

Ch.12 PIC16F84 Micro-Controller Programming in C 423

Page 142: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 142/260

 

23. The Use of Pointers

A pointer is the address of a variable of a specific data type. A pointer must

also be declared, similar to any variable, before it may be used. A typical

declaration of a pointer that would point to an integer, is:

int *p;

long *q;

/* P points to an integer variable */

/* q points to a long variable */

The two pointer operators are & and *. They are unary, and operate on the

operand immediatelyto their.right, withouta space. If p is pointer and c is the

variable p is pointing to, then for:

p = &c; P is replaced by the address of c, and if

c= *p; c is replaced by the contents of p.

The contents of a pointer, *p, can be used in statements as if it is a normal

variable, with all the standard aritlunetic operators:

(*p)++; /* increment *p after usage */

++*p; /* increment *p before usage */ ,

*p+=2; /* *p = *p + 2 */

i= 2 **p; /* i is two times *p */

If both p and q have been declared as pointers to variables of the same data

types, then after p =q; pointer p will point to the same variable as q.

For *p =*q; the contents ofp will be replaced by the contents of q.

For i= *q; or i =q; then i will be replaced by the contents of q.

Note that parenthesis and brackets have a higher precedence than the pointer

operator, *, Le. use parenthesis for (*p)++.

(See a later section for the use of pointers in parameter passing to functions.)

424 PlC Micro-Controller Operation and Applications - Vol. 11

Page 143: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 143/260

 

24. Arrays

An array is a group of variables of the same data type and with the same

variable name. The different elements of an array are referred to by a positive

integer value index, from 0 upwards, in brackets after the array name. Thenumber and type of elements are defined in the declaration of the array.

,Examples:

int a[lO]; /* Declare 10 integer values for array a[ ],

starting at a[O], up to a[9]. */

char b[4] = {4,6,2,67}; /* Define the 4 initial character values ofb */

Only I dimensional arrays are supported.

A special use of pointers and arrays are demonstrated by the following

example: If a pointer to an element in an array is declared, by...

inta[5];int *p;

/* Declaration of integer array a[], and */

/* Declaration bf a pointer to an integer */

...then the statement p =&a[O); will point the pointer to the first element of

the array.

After x =*(p + 2); xwill contain the value of the third element of array a[ ).

--------------------------------

Ch.12 PICI6F84 Micro-Controller Programming in C 425

Page 144: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 144/260

 

25. Strings

A string is a special char data type array. The maximum size must be defmed

in the declaration statement as one more than the number of required elements.

A character array may contain less significant characters than the maximumallowed for. To indicate the end of the significant characters, a '\0' is used.

Asan example,onemay allow say 10charactersfor the nameof something,but

the name is only 6 characters long. The \0 in the 7th elementwill prevent the

garbage of the rest of the array to be associated with the name as well. An

element of a string is referred to by an index number, starting from O.

To declare a stringwith initial values, use:

char str[7] = {'W','i','I','I','e','m','\O'};

char name[IO] = "Willem"; IIWill place the \0 in the 7th element.

charver[ ]= "Ver1.l "; IIWill adjust to size 7 automatically.

26. Structures

A Structure is a user-defined~et of data that can containdifferent types of data,as opposed to an array, that is made up of the same type of data. It offers the

user an easy way to handle one set of data of different types, belonging

together. The user must define the struct as a new data type, with its own data

type name. Then user variables can be defmed to be of this new data type.

The format of a structure defmition is as follows:

struct structure name

{ data_type member!;data_type member2;

1*The user-defined data-type name *1

1*Type and name of flfSt member *11*Type and name of 2nd member *1

data_type membem;

} variable_name;

1*Last member type and name *I

1*Can be a comma-separated list *1

Once defmed, additional variables of the same type can be defmed as:

struct structure_name variable(s);

426 PIC Micro-Controller Operation andApplications - Vol.II

Page 145: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 145/260

 

A new structure may also contain a data type of another pre-defined structure,

called nested structures.

To access the data, the '.' operator is used between the structure variable name

and the member name: variable_name. membern =value of defmed data type.

Example: A micro-controllermonitors two temperatures and must store the

data together with the date (DDMM) and the time (HHMM).

struct record

{ long date;

long time;

int toptemp;

int bottomtemp;} reading;

II User data-type name is record

II User variable name is reading

The first temperature reading is taken and stored in toptemp (3rd member):

reading.toptemp = gettempl();

The second reading is taken and stored:

reading.bottomtemp = gettemp2( );

Now the data and time are read from some external timer device:

reading. date = getdate( );

reading.time = gettime();

The data is stored together in 6 bytes of memory as follows:

2 bytes for date, 2 bytes for time, 1byte for toptemp and 1 for bottomtemp.

Ch.I2 PlCI6F84 Micro-Controller Programming inC 427

Page 146: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 146/260

 

27. Unions

A Union is a set of variables of different data types, that occupies the same

memory area, one at a time. The declaration and access method is the same is

that of structured, but the memory usage is different. It presents anothermethod of memory economy.

The fonnat of the declaration of a Union, is as follows:

.union union_type_name 1* The user-defined data-type name

*1

{ data_type member 1;

data_type member2;

1* Type and name of first member *1

1* Type and name of 2nd member *1

data_type membem; 1*Type and name of nth member *1

} variable_or_list_oC variables; 1*Can be a comma-separatedlist*1

The data types of the members may include previously defined structures and

arrays. The width ofthe union will be the width of the widest member. When

data is stored, it will start to occupy the memory area :trom the beginning. New

data stored will also start :trom the beginning and overwrite the previous datastored.

Once defmed, other variables of the same union type may be defined as:

union union_type_name variable;

Example:

union set!

{ int i;

char a[3];

longb;

} areal, area2;

II Union type name

II I byte integer

II 3 single byte array

II 2 byte integer

112 variables of union type setl

The width of each union variable will be the width of the widest member, the

character array of 3 bytes. The data storage in each union variable will be as

shown on the next page:

428 PIC Micro-Controller Operation and Applications - Vol.II

Page 147: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 147/260

 

1 i 1

1--- a[O] --1--- a[l] 1 a[2] 1

1 hi b 1 10 b 1

I byte 2 J byte 3

To access the union, the '.' operator is used, similar to structures:

union_variable. member_name = value;

Examples:areal.a[2] = 23;

area2.b = 45678;

-----------------------

28. The typedef Function

The standard data type and modifier names can be changed to suit a user's

personal taste by using the typedej function. This will normally be used onlyif a specific data type is going to be used.often and it is worth the effort. The

compiler will take note of the new data type name, and treat it as a new keyword.

The format for the typedejfunction is:

Example:

typedef offset signed long int;

offset x-position,y -position; liThe 2 variables are now declared

II as signed long integers.

Ch.i2 PlCi6F84 Micro-Control/er Programming in C 429

Page 148: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 148/260

 

29. Enumeration Declarations and Use

Enumeration of constants is used to make more sense in the use of constant

values. Take an example where a LED will be ON when a bit value is 0, and

OFF when the value is 1. Instead of always having to remernber that theONIOFF state this LED is inverted, specific values for ON and OFF can be

defined, using the enum key word. Similarly, a few output devices may bedecoded by hardware to specific address locations. These locations can be

defined as words at the beginningof the programusing the enumstatement,andthen use these sensiblewords to refer to the addresses. If the decoded address

changes, then only one change need to be made in the enum statement.

The format for the enum statement:

enum enum_type {enum_name[= constant] , enum_name};

Examples:

enum ledstate {on,off}; lion = 0 and off= 1.

enummonth {JAN=l,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,

OCT,NOV,DEC};

Notes: The value allocation ofthe enum_names will start at 0, and increment

up to 255. If a value is allocatedby "=constant",the numberingwill continuefrom this value upwards. The same result can be achieved with the #define

directive, but then each value must be specified individually.

The Usage of the Enumeration Constants

bits PortB @ Ox06;

enum ledstate {on,off};II Declaration ofPortB as bits data typelion = 0 and off= 1.

Port.3 = on; IIwill place 0 on bit 3 of Port B

--..---------------------------

430 PlC Micro-Con.troller Operation and Applications - Vol. II

Page 149: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 149/260

 

30. The Declaration and Use of Procedures and Functions

A functionor a proceduremay need values ttom the calling module to operateon. In such a case, the values must be passed into the function or procedure,

when it is called. Usually a new set of local variables are declared for each

pifferent functionor procedure. These are then discarded when the execution

of the module is done. To pass the values into a function or a procedure, the

variablesmust be declared in the parenthesis after the name of the function or

procedure definition line. If no parameters are passed, a pair of empty

parenthesis must still be included. This will identify the module name as a

function or a procedure.

When the function or procedure is called, the same format and sequence of

parametersmust be includedin the calling statement The parameter values are

then copied into the newvariables, and only the new variables are operated on.

The original variables stay unaltered. After completion, all the new variables

are discarded. It is possible for a function or a procedure to operate on the

original variables by using pointers, but this will be discussed later.

This version of C only allows two bytes of data to be passed to a function or a

procedure. These bytes may either be two char or int type variables, on onelong data type variable.

The return data type for functions are also defined in this line. Procedures, that

does not have a return value, must be declared as a void data type. Only one

value with a maximum size of two bytes may be returned ttom a function.

A function or a procedure may also need its own additional local variables.

They must be defined in the normal fashion, just before the statements.

Before a function or a procedure is called ttom a module, it must either be

defined completely, or just declared before the module. This declaration

statement has the same format as the first line of the function or procedure

definition, but followed by a semi-colon;

Ck12 P1C16F84 Micro-Controller Programming in C 431

Page 150: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 150/260

 

The Definition of a Procedure

The fonnat for the defmition of procedures is as follows:

void procedure_name() 1*No passing parameters& no (;) *1{ local_variable_declarations;

statement;

statement;

}

void procedure - name( data_type variable - name,data - type var_name)

{ local_variable_declarations;

statement;

statement;

Procedure Declaration Format if placed before the Calling Module

void procedure - name( ); 1*Note the use of the (;) here. *1

The Usage of a Procedure

,

statement;

procedure_name();statement;

II in main or callingmodule

IINo passing parameters

statement;

procedure-name(x,y);

statement;

II x and y are local variables of the ...II calling module.

432 PlC Micro-Controller Operation and Applications - Vol. 11

Page 151: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 151/260

 

Example:

A procedure to blank out the high nibble of a character and place the value on

Port B is shown below. The value will be .passed to the procedure in the caning

statement. Assume that Port B has been set to be an output beforehand.

#include <16C84A.h>

void setportb( char b);

main( )

{ char out;

out =Ox5E;setportb(out);

next_statement;

}

void setportb( char b)

{ b &= OxOF;

PORTB = b;

}

Notes:

/* Defme Processor and Register names */

/* declaration before calling module */

/* Calling module */

/* Output from say a lookup table *//* Caning statement with parameter */

/* No ; here. */

/* No return value */

If the whole setportb( ) procedure was placed before the main( ) module, the

declaration-only statement of setportb( ) wilInot be required. The procedure

setportb( ) was defmed as a void return data type, and the procedure does notneed a return statement at the end.

(The Defintion of Functions )

Ch.12 PIC16F84 Micro-Controller Programming in C 433

Page 152: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 152/260

 

The Definition of Functions:

Fllllctions are defined in the same way as procedures, except that !lreturn data

type is specified, and the procedure ends with a return statement. The general

format is shown below:

data_type function_name() /* No passing parameters.

{. local_variable_declarations;

*/

statement;

statement;

return variable; /* The same data type as function. */

data_type function_name(data_type variable_name, data_type var_name)

{ local_variable_declarations;

statement;

statement;

return variable;

}

Function Declaration Format if placed before the Calling Module

data_type function_name(); /* Note the use of the ; here */

data_typefunctn- name(data_type variable- name,data_type var_name);

The Usage of a Function:

statement;

z = function_name( );

statement;/* No passing parameters */

statement;

z = function_name(x,y); /* z, x and y are local variables

of the calling module */

statement;

434 PlC Micro-Controller Operation and Applications - Vol. 11

Page 153: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 153/260

 

Example:

As an example, a simple function that will add two integer values and return the

sum, will be used.

#include <16C84A.h>

int sum(int d,e); /* function declaration only */

main( )

{ int a,b,c;

a=2;

b=3;

c = sum(a,b);}

int sum(int d,e)

{ int f;

f= d + e;

return f; // return d + e; is also valid, without using f}

31. The Use of Pointers to Pass Parameters to a Function

In the previous examples, only one parameter of a function can be passed back

to the calling module. If a function must change more variables, one may pass

pointers to the function, in place of variables. The pointers are defined in the

parenthesis of the first line of the definition statement. These pointers will be

redefined and set equal to the addresses of the variables in the calling statement.

By changing the contents of the pointers in the function, the original variableswill be changed.

In sucha case onedoesnot need a return value asbefore, and the function then

becomes a procedure. In a similar manner, a procedure can now also change

the contents of variables, so that, strictly speaking, it will then become a

function. In the end there is hardly anydifferencebetween the two. The name

can be used as a single standing statement, or if it returns a value, it can form

part of an expression.

Ch.12 PlC16F84 Micro-Controller Programming in C 435

Page 154: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 154/260

 

The Definition of a Function, using Pointers:

void function -name( data_type *pointer - name, data- type *pntr_name)

{ local_variable_declarations;

statement;

statement;

return variable;

}"

Note: The data type must be included for each pointer!

Function Declaration Format if placed before the Calling Module:

The Usage of a Function using pointers:

int x,y; /* Declaration of variables. */

statement;function_name(&x,&y);* SpecifYaddressesofx andy */statement;

Example:

#include <16C84A.h>

void sum(int *d,int *e); /* declaration before calling module */

main( )

{ inta,b,c;/* Callingmodule */

a=2;

b=3;

c = sum(&a,&b); /* Carry addresses over to function */

}

436 PIC Micro-Controller Operation and Applications - Vol. 11

Page 155: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 155/260

 

void sum(int *d,int *e)

{ int f;

/* Definition of function */

f= *d+ *e;returnf;

}

---------------------------------

32. Pre-Processor Directives

Pre-processordirectivesdo not generate anycode. They are used to instructthe

compilerhow to interpret the program. These directives follow after a # sign,and are normallyplaced at the beginningof the program against the leftmargin.

These lines do not end with a semi-colon, except for the #pragma directive.

The pre-processor directives that will be discussed, are the following:

#asm and #endasm

#define and #undef

#if, #else, #error and #endif#ifdef and #ifndef

#pragma#include

The #asm and #endasm Directives

It is possible to include standard assembler instructions directly into a

C program. To inform the compiler that assembler instructions follow, the

#asm directivemustbe used. The #endasm informs the compiler that normal

C-statements will follow from here onwards. The default radix for these

assembler instructions is the hexadecimal numbering system.

A single assembler instruction does not require an #endasm directive. The

instructionmust then be within parenthesis, (...), double quotes, "..." or < ... >

markers,and endingwith a semi-colon. The first space of the instruction must

be left open. It is reserved for symbols only.

Ch.12 PICI6F84 Micro-Controller Programming in C 437

Page 156: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 156/260

 

For more than one assemblerinstruction,the first instructioncan followdirectlybelow the #asm directive. The instructions must be in the nonnal assembler

fonnat. At least one space must be left open at the left margin. Labels can be

placed by itself in the line above the instruction it points to. After the last

instruction, the #endasm directive follows,without a semi-colon.

Examples:

#asm ( BSF PORTB,3); II Single instruction. Note the space.

#asm

MOVLW OF5

MOVWF temp

TOPDECFSZ temp,fGOTO TOP

II Default radix is hex.

II temp may be a C-variable

II Label against the marginII ¥TIemonics at least one space away from margin

#endasm

Note: These directives will allow one to re-use some existing assemblermodules by includingthembetween the assembler start and end directives. One

must be careful with variable defmitions to fixed addresses, that maybe used

in existing assembler modules. They may interfere with the compiler'sallocation of variables and overwrite some C variable values.

The #define and #undef Pre-processor Directives

The #define directive is a useful way to enable one to replace some name or

number throughout a program, without physically going through the program

step-by-step. Say there is a scaling factor of25 used throughout the program.If the scaling factor changes, all the statements using the scaling factor will

have to be updated. The #defme directiveis used tomake SCALEequal to say

25. The name SCALE is then used in all the statements. To change the value,

only the original defmition need to be changed to update all the references.

The format for the #define directive is:

#define NAME replacement text up to the end of this line

438 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 157: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 157/260

 

TheNAME is usually in capitals to identify it as a defmed name, followed by

the replacementtext or numbers. The replacement text can be any combination

of letters, spaces and numbers. It is terminated by the end of the line. If more

space isrequired, the definition can continue on the next line, after ending the

first line with a '\' marker. During compile time, all the places where NAME

was used, will be replaced directly by the replacement text.

The #undefNAME directive will cancel the existence of NAME from there

onwards, down to the end of the program.

Examples:

#define SCALE 25

Macros

Macroswith variables can also be created by the #defme directive. It is done

by placing the variable symbols in parenthesis directly behind the name,

followedby an expression where these variables are used:

#defme MAX(A,B) «A»(B)?(A):(B))

A statement c=MAX(x, y + z);

will be replaced by: c=«x»(y+ z)?(x):(y + z));

When the macro MAX(a,b) is used, it will return the bigger value of a or b.

---------------------

Ch.12 PlC16F84 Micro-Controller Programming in C439

Page 158: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 158/260

 

The #if, #else, #error and #endif Directives

These directives are usually associated together. They are not used to generate

code as their conditional statement equivalents, but to give the compiler some

direction under certain conditions. Note that these directives do not end witha semi-colon.

The general format is:

#if conditional_expression II Evaluate to 0 (false) or not 0 (true)

I set of source code

#else

another set of source code

or #error "Error message"

#endif

Example:

#defme MAX COUNT 100

#defme ELEMENTSIZE jIISet up system values

#if MAX COUNT * ELEMENT SIZE> 256-

#error "Data size too big!" IIWill stop compiler & return message

#else

#defme DATA_SIZE MAX_COUNT *ELEMENT_SI~

#endif

440 PlC Micro-Controller Operation and Applications - Vol. 11

Page 159: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 159/260

 

The #ifdef and #ifndef Directives

These directivestest if a symbolhas been defined or if the symbolhas not beendefined. The #else and #endif directives are also used together with these

directives.

Format: #ifdef symbol

source code

#else

other source code

#endif

The #pragma Directive

There are quite a few options for the #pragma directive. Only a few significant

ones will be discussed. The others can be found in the C-Compiler User Guide.

The #pragma directive is the only directive that must end with a semi-colon.Most of the essential pragma statements will automatically be inserted when the

16C84A.h file is included. (See the contents of the 16C84A.h file in section

33.)

Only one of the pragma options can be of some general use. It is the

Suppress/Allowthe listingfrom here on. It can be used toprevent, for example,

the contentsoflong include files to appear in the listing as well. The standard

header and libraryfiles have beenmodified sightly to suppress the listing of all

information, except the actual code or programming statements in the listingfiles. A user must be careful with the use of the listing inactive option, -I. It

may suppress and not show the rest of the user program.

Examples:

#pragma option -I;

#pragma option +1;

II Suppress listing from here on. Note the" ;"

IIAllow listing from here on.

Ch.12 PIC16F84 Micro-Controller Programming in C 441

Page 160: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 160/260

 

The #include Directive

The #include directive will instruct the compiler to load and include the file

specified, at that point in the program.

Format: #include < [d:][path] include_file.h >

Examples:

#include <16C84A.h>

#include < C:\PIC\math.h>

#asm#inc1ude

#endasm"delay.h" II Assembler program module

33. Listing of the 16C84A.h Include File (Seediscussionfterwards)

#ifndef l6C84A_H

#pragma option -1;1*

PIC16C84A Standard Header File, Version 1.00

(c) Copyright 1996Microchip Technology, Inc., Byte Craft Limited

RAM locations reserved for temporary variables: OxOC -OxlO *1

#define 16C84A H

11 Hardware Defmition -----------------------------------------------

#pragma processor PlC 16C84A;

// Memory Definitions ------------------------------------------------#defme MAXROM Ox400

#defme MAXRAM Ox50

#pragma memory ROM [MAXROM -Ox05] @ Ox05;

#pragma memory RAM [MAXRAM -axIl] @axIl;

442 PlC Micro-Control/er Operation andApplications - Vol.II

Page 161: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 161/260

 

// Internal Compiler VariabIes ---------------------------------------char temp-WREG @ OxOC;

char - WImage @ OxOD;

charternp_WImage @ OxOE;

char temp_STATUS @ OxOF;charternp]SR @ OxlO;

.1/ Interrupt Vectors -------------------------------------------------

#pragma vector __RESET @ OxOOOO;

#pragma vector __INT @ Ox0004;

// Special Function Registers ----------------------------------------#pragma portrw INDF @OxOO;

#pragma portrw TMRO @ OxO1;#pragma portrw PCL @ Ox02;

#pragrnaportrw STATUS @ Ox03;

#pragma portrw FSR @ Ox04;

#pragma portrw PORTA @ Ox05;

#pragma portrw PORTB @ Ox06;

#pragma portrw EEDATA @Ox08;.

#pragma portrw EEADR @ Ox09;

#pragma portrw PCLATH @ OxOA;

#pragma portrw INTCON @OxOB;

#pragma portrw OPTION

#pragma portrw TRISA

#pragma portrw TRISB

#pragma portrw EECONl

#pragma portrwEECON2

@ Ox81;

@ Ox85;

@ Ox86;

@ Ox88;

@ Ox89;

registerwWREG;

// STATUS Bits -------------------------------------------------------#detine C 0

#detine DC 1

#detine Z 2

#defme NOT PD 3

#defme PD

#detine NOT TO 4

#detine TO 4

3

Ch.i2 PlCi6F84 Micro-Controller Programming in C 443

Page 162: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 162/260

 

#defme RPO

#defme RP1

#defme IRP

5.

6

7

// PORTA Bits --------------------------------------------------------

#defme TOCKI 4

// PORTB Bits --------------------------------------------------------

#defme INT 0

// INTCON Bits -------------------------------------------------------

#defme RBIF 0

#defme INTF 1

#defme TOIF 2#deftne RBIE 3

#define INTE 4

#defme TOlE 5

#defme EEIE 6

#deftne GlE 7

// 0 PTI 0 N Bits -------------------------------------------------------

#defme PSO 0

#defme PS1 1#defme PS2 2 .#defme PSA 3

#defme TOSE 4

#defme TOCS 5

#defme INTEDG 6

#deftne NOT RBPU 7

#defme RBPU 7

// EECON1Bits -------------------------------------------------------

#detine RD 0

#defme WR 1

#defme WREN 2

#defme WRERR 3

#defme EEIF 4

444 PlC Micro-Controller Operation and Applications - Vol. 11

Page 163: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 163/260

 

// AssemblerMacros--------------------------------------------------#define_SWAPF(f,d) #asm(swapff,d)#define_RETFIE() #asm(retfie)

#endif

Notes: The PICI6C84A processor is specified. It has the same memory

. specification as the 16F84. The C-compiler does not know the 'F' processor

yet. Note the standardname definitions for all the File Registers of the PlC as

they are used in the data book. The only different names are the NOT_TO,

TO_, NOT_PD, PD_, NOT_RBPU and RBPU- bit names and the full

OPTION name. All names are in capital letters. TOCKI is included for the

RA4 port input, and INT for the RBOexternal interrupt input, but the port pin

names, such as RBO,RA2, etc., are not included.

The addresses of the Page I registers are all defmed as Ox8..,to identify them

as Page I registers for the Compiler and some simulators. The Compiler will

automatically set the RPObit in the STATUS register if Page 1 registers are

accessed, or clear the bit for Page 0 registers.

RAM addresses OChto lOhare reserved for local variables for the C-compiler

existing libraryand include files. User variable are placed from IIh upwards.

Note also the inclusion of the RESET and INTerrupt vectors at code addressesOOOOhand 0004h.

34. Assembler Instruction Equivalents in C

There are four PIC'84 assembler instructions that can be used virtually as is in

C. Themain differenceis to add a set of parenthesis to the instructionsto makethem procedures:

Assembler C-Syntax Operation

CLRWDT

NOP

SLEEP

SWAPF f,d

CLRWDT(); Clear Watch Dog Timer

NOP( ); No Operation

SLEEP( ); Go into SLEEP mode

SWAPF( f); Swapnibblesof Register to

f

Ch.I2 PlCI6F84 Micro-Controller Programming in C 445

Page 164: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 164/260

 

35. The Use of an Interrupt Sub-Routine in C

The vector defmition in the 16C84A.h file allows a user to write his interrupt

sub-routine directly inC. The only provision is that the name of the routine is

specific and must be as shown in the example below:

void __INT(void)

{. varible_declarations; II if any

statement;

statement;}

The generated code will be placed at the interrupt vector 0004h, and the

RETURN statement from a procedure with this name will automatically be

replaced by a RETFIE instruction.

36. The Startup Routine

The compilerallows for, and will automatically look for and include a startuproutine. It may be included or left out. This startup routine will be executedbefore the main routine starts. It allows the user to do somt; tests on the

hardware after a reset. It can for example, be used to test if the reset was a

Watch Dog Timer reset or a Power-up reset. These tests may be required if

there is, for example,an LCDDisplayModule that needs to be initialised after

every power up, but not afte a normal reset.

The format and use of the startup routine are as follows:

void __STARTUP(void)

{ statement;

statement;

}

446 PIC Micro-Control/er Operation and Applications - Vol. 11

Page 165: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 165/260

 

37. Standard Existing Header Files and Library Functions

There are a number of existing functions in the C-include libraries. They can

be implementeddirectlyby a user. The only provisions are that the headerfile

(extension .h) must be included in the program before the function is called,and the format of the calling instruction must be correct.

.If multiplicationor divisionare going to be used, then the math.h file must be

included by the statement:

#include <math.h>

.There are two general generic function libraries, CMATH.H and CTYPE.H,

and five 14-bitcore include files:MATH.H, DELAY14.H, EE14.H, AD7l.HorAD74.Hand SER14.H. TheAD7x.H and SER14.H are only significant for

the PIC16C71 and PIC16C74 controllers, and will not be discussed here. A

summaryof the header files of the others are included. Theywill indicate what

is available, and also the expected format of the calling statement, in bold.

Multiplication and division are not called for by a function as such, the

operators are simply used in an expression, e.g. c = a * 4;.

CMATH.H

abs( parameter)Returns the absolute value of the parameter.

max( parameter_a, parameter_b)

Returns the maximum of parameter_a and parameter_b.

mine parameter_a, parameter_b)Returns the minimum of parameter_a and parameter_b.

CTYPE.H

isalnum( parameter)

Returns a logical TRUE if parameter is an alphabetic or numeric

character; otherwise, returns a logical FALSE.

Ch.I2 PlCI6F84 Micro-Controller Programming in C 447

Page 166: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 166/260

 

isalpha( parameter)

Returns a logical TRUE if parameter is an alphabetic character;

otherwise, returns a logical FALSE.

isascii( parameter)Returns a logical TRUE if parameter is anASCII character; otherwise,

returns a logical FALSE. An ASCII character is defined as a value

b~tween 0 and Ox7F

iscntrl( parameter)

Returns a logical TRUE if parameter is an ASCII control character;

otherwise, returns a logical FALSE. An ASCII control character is

defmed as a value between 0 and OxIF, or Ox7F.

isdigit( parameter)

Returns a logical TRUE if parameter is a numeric character; otherwise,

returns a logical FALSE.

islower( parameter)

Returns a logical TRUE if parameter is a lowercase alphabeticcharacter;otherwise, returns a logical FALSE.

isprint( parameter)Returns a logical TRUE ifparameter is a printable character; otherwise,

returns a logical FALSE. A printable character is defined as a valuebetween0x20andOx7E.

ispunct( parameter)

Returns a logical TRUE if parameter is a punctuation character;

otherwise, returns a logical FALSE.

isspace( parameter)

Returns a logical TRUE if parameter is a spacing character; otherwise,

returns a logical FALSE. A spacing character is defmed a~a horizontal

or vertical tab, line feed, form feed, carriage return, or space.

isupper( parameter)

Returns a logical TRUE if parameter is an upper alphabetic character;

otherwise, returns a logical FALSE.

448 PlC Micro-Controller Operation andApplications - Vol.II

Page 167: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 167/260

 

isxdigit( parameter)

Returns a logical TRUE if parameter is a hexadecimal digit; otherwise,

returns a logical FALSE.

tolower( parameter)

Returns the lowercaseversion of parameter. Ifparameter is not a letter,. it is returned unchanged.

toupper( parameter)

Returnsthe uppercase version ofparameter. Ifparameter is not a letter,

it is returned unchanged.

MATH.H

This file must be included if multiplication, division, or modulus operations areused.

void __MUL16xI6(void);

Internal library routine for performing 16by 16-bitmultiplication.

char __MUL8x8(void);

Internal libraryroutine for performing 8 by 8-bit multiplication - returns

a 1 byte answer.

char __DIV8BY8(void);

Internal library routine for performing 8 by 8-bit division.

void __LDIV(void);

. Internal library routine for perfol1\ling 16by 16-bit division.

Ch.l2 PICl6F84 Micro-Controller Programming in C 449

Page 168: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 168/260

 

DELAY14.H

void Delay_Ms - 4MHz (registerw delay);

Pause for delay milliseconds when operating at 4 MHz.

void Delay_lOxUs- 4MHz(registerw delay);

Pause for (delay times ten) microseconds when operating at 4 MHz.

Note: Delays for other frequencies also exist.

EE14.H

int Read_EEProm(registerw addr);

Read a value from the EEPROM data at the specified address.

void Write_EEProm(registerx addr, registerw data);

Write a value to the EEPROM data at the specified address.

38. The MPLABC14.LIB and other Library files

TheMPLABC14.LIBfilewill automaticallybe includedafter theuser program.

It contains the multiply and divide routines, and will also include all the other

libraI}'files, such asDELAY14.LIB and EE14.LIB, if the header files for these

libraries have been included in the user program. The header files will only

declare the procedures before the main program and other procedures. The

actual procedures are in the library files. Code will only be generated for a

specific library procedure, if it has been called by the user program. This can

result in a rather long listing file with a great deal of unused program lines.

Someof these header and library files have beenmodifiedslightlyto onlyshowused program lines in the listing file.

450 PlC Micro-Controller Operation and Applications - Vol. JJ

Page 169: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 169/260

 

Notes:

Ch.12 P1C16F84 Micro-Control/er Programming in C 451

Page 170: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 170/260

 

Notes:

452 PlC Micro-Controller Operation and Applications - Vol. II

Page 171: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 171/260

 

39. Exercises, Tutorials and Examples

The descriptions and application notes of the exercises have been written to

apply for both the MPLAB IntegratedDevelopment Environment, and also for

a standard DOS environment. This will also make these notes applicable foruserswho maynot have colour screens and sufficient memory and hard drive

space availableto runWindows. It is assumed that the student has a reasonable

knowledge ofthe PlC architectureand have competed theAssembler exercisesin Volume 1.

Setting up the DOS Environment

The minimum specification to run tlie MPLABC compiler in a DOSenvironmentis a 386 IBM compatible computer and a DOS Version of 5.0 or

higher. The files required in the main PlC Compiler directory are as follows:

EDIT.COM

MPLABC.EXE

DBMI16BI.OVL

PS.EXE

PP.EXE

16C84A.H

CMATH.H

CTYPE.H

MATH.H

DELAY14.H

EE14.H

MPLABC14.LIB

DELAY14.LIBEE14.LIB

11Useful Optional files

IDE .BAT

P84.EXE

V84.EXE

R84.EXE

E84.EXE

IIASCII format text editor (ver. 2.0)

IICompiler Program (ver. 1.1)

IIOverlay file for MPLABC

II Simulator to test the logic (ver. 4.0)

IIDevice Programmer Driver (ver. 5.0)

II Include header files

IILibrary files

II Batch.file to load files and run the toolsIICommand Line '84 Programmer Driver

IICommand Line '84 Program VerifierIICommand Line '84 Device Reader

IICommand Line '84 Device Eraser

Ch.12 PIC16F84 Micro-Controller Programming in C 453

Page 172: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 172/260

 

To keep the generated files for each project or exercise separate, it is

reconunended to open a separate sub-directory for each exercise. If the tool

programs are going to be run by conunand-line instructionsinDOS, the system

pathmust be set to point to the directory that contains the main tool programs,the include files and the library files. This will enable one to run these

programs from within a project sub-directory. All the project specific

generated files will then be.stored in the project directories. A typical pathsetting instruction is: C:\PIC> path =C:\PIC.

Alternatively, a batch file can be created that would run the tooi programs by

key selection. The path and project name are entered once as an inputparameterwhen the batch file isrun. The batch filewill then add extensions to

the path and project name as input parameters when a tool program is run.

Everything can then be run from the directory containing the tool programs.The batch file, IDE.BAT, can be written as shown below. The paths to the

various tool programs must co-inside with the user's local disk and directory

system. The text editor EDIT.COMmay be left in the mainDOS directory. It

requires a help file in the same or default directory:

echo off

ifEMPTYTEST%I==EMPTYTEST:START

clsecho PROJECT Name: %1

echo.

echo Project Files:

dir %1.* /b /pecho.

echo Select Tool Program to run:echo. .echo T Text Editor for source file

echo C C-Complilerecho L View Listing Fileecho S Simulator

echo P Progranunerecho E Exit

echo.

goto HELP

C:\DOS\CHOICE /C:TCLSPE

if errorlevel 6 goto EXIT

454 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 173: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 173/260

 

if errorlevel 5 goto PROGRAMMER

if errorlevel4 goto SIMULATOR

if errorlevel 3 goto LIST

if errorlevel2 goto COMPILE

:TEXT

C:\DOS\EDIT %1.C

goto START

:COMPILE

C:\PIC\MPLABC %l.C laINHX8M

pause

goto START

:LIST

C:\DOS\EDIT %l.LST %l.ASM

goto START

:SIMULATOR

C:\PIC\PS %1

goto START

:PROGRAMMER

C:\PIC\PP %l.hex

goto START

:HELP

cls

echo Run with Drive, Directory and Project name as input parameterecho.

echo Format: [d:][path]IDE [d:][path]proLname (No extension)

echo.echo Example:" C:\PIC> c:\pic\ide c:\pic\p3\bcd "echo.

:EXIT

Ch.12 PIC16F84 Micro-Controller Programming in C 455

Page 174: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 174/260

 

The Text Editor, EDIT.COM (ver. 2.0) allows two files to be loaded

simultaneously, with an easy switch-over from one file to the orher. This is

useful for inspectingerrors in the listing file, and correcting them in the sourcefile. A similar batch file can also be written to run in a DOS window in the

Windows environment. A detailed description of this type of operation isincluded at the end of Volume I, and also in the appendix to Chapter 14 ofVolumeII.

Once the required directories have been created and the files installed, the first

exercise can be attempted. The exercises follow the same pattern as the

exercises forAssembler languageprograms in VolumeI of these notes. They

can be programmed and tested on the PIC84 Basic Board.

-----------------------------------The MPLAB IDE Environment

It will be assumedthat the MPLAB IDE system,and also the MPLABC.EXE

program for windows, have been installed and all the header and" library files

are available. BeforeMPLAB isrun, Windows Explorer can be 'used to open

separate sub-folders for each exercise. It can be doneby selectingthe MPLAB

folder, and using the File, New, and Folder options. The new folderscanthen,

for example,be named Cl, C2, C3, etc. It is not a good idea to give the same

name to the folder and the project, stored in that folder. Windows some timesrefuses to store a file with the same name as the folder.

"WhenMPLAB is running the flIst time, a few system settings have to be

selected before a newproject is created.

By clickingonthe Options selectiononthe main menu bar, a pull downmenuwill appear. Here the Development Mode must be selected. The diamondnext to the MPLAB-SIM must be selected, and the Processor must be the

PlC 16F84. This selection is for the Simulator, not for the Compiler. A click

on the Reset option will return to the main desktop.

Also under the Options selection, the Default Editor Modes can be selected,

and set to the C-Language. A Tab setting of 4, and Strip trailing spaces can

also be selected. To save and exit, select Apply, Save and Close.

456 PlC Micro-Controller Operation and Applications - Vol. 1I

Page 175: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 175/260

 

The last setting on the Option menu is the Processor Setup and Hardware.

Here the Watch Dog Timer can be set for the Simulator. This setting is

normally done in the configuration byte for programming into the controller,

and not by software instructions. To exit, select WDT None, and OK.

Under the Project option of themainmenu bar, the Install language tool must

'be selected. The Language must be MicroChip, the Tool name, MPLABC

vl.IO, and the Executable, MPLABC.EXE.

Stillunder the Project option, the New Project mustbe selected. A project file

must be opened to store all the settings for a project. It must have a .pjt

extension, and must be stored in one of the user sub-folders. A name such as

setleds.pjt can be entered, and the sub-folder Cl selected. When the OK

button ispressed, the Edit Project windowwill appear. It the windowdoes not

appear automatically, it can also be selected under the Project main menu

option, and Edit Project.

In the Edit Project window, the Target filename will appear in a box as

SETLEDS.HEX. Check that the Development Mode is still MPLAB-SIM

and the Target Processor is still the PICI6F84. The name setleds.hex in the

Project files box lower down can now be clicked, and then Node Properties.In the Node Propertiesbox, the INHX8M file type must be selected, and only

the Error and Listing files enabled. The Language tool must again be

checked to be MPLABC v1.l, or reselected if necessary. The OK button can

be clicked, and again OK in the Edit Project window to return to the main

desktop. If an error occurs that setleds.hex cannot be found, just click OK.

This file must still be generated. All the settings so far can be saved by

selecting Save Project on the Project menu.

Under the main menu File option, New can be selected, and an Untitled editwindow will appear. This is where the source program will be written in C.

The sourceprogram, even if it is still empty, can be stored and given a name by

the Save As option in the File menu. It must also be stored in the Cl folder,as setleds.c.

Ch.12 PICI6F84 Micro-Controller Programming in C 457

Page 176: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 176/260

 

To make everything ready for writing and testing of the source program, this

file must also be added to the project file in the Edit Project windowunder the

Project menu. The Add next to the Project files box must be selected and

setleds.c found through the Browse option. The edited settings of the project

can now be saved by the Sav.eProject option of the Project main menu.

The fIrstexercise can now be attempted.

-------------------------------Notes:

,

458 PlC Micro-Controller Operation and Applications - Vol. 11

Page 177: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 177/260

 

Exercise 1: Setting the LEDs

Problem: Write a programin C to set the LEDs of the Basic Board toB'0101101O', and go into the SLEEP mode.

Recommended reading: From the beginning up to the section on Operators

(sections 1to 14,p-391 to p-416), and also the sections and on the 16C84A.H

peader files (section 33, p-442) and Assembler Equivalent Instructions in C(section 34, p-454).

Program Example:

/* Exercise 1 SETLEDS.C

Writing B'0101101O' to the LEDs */

#include <16C84A.h>

void main( )

{ TRISA = 0;TRISB = 0;PORTA=OxOA;

PORTB = Ox05;SLEEP();NOP();

/ / Set ports as Outputs

/I Right-hand nibble B'IOI0'

/I Left-hand nibble B'OI0 I'

}

Discussion

The #include <16C84A.h> directive must be included at the beginning of

everyprogram to specify the device. It specifies the memory size available andother important settings for the C-compiler. This file also defines all the

standard PIC'84 register names. The user can use these names directly in his

programs. Note the use of capital letters only for these names.

The main programstartswith void main(). If the void is left out, the compiler

will flag an error that: ItA return value should be specified. It

Ch.J2 PlCJ6F84 Micro-Controller Programming in C 459

Page 178: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 178/260

 

The first two instructions will set the ports as outputs. It is not required to

selectPage 1first. The compilerwill selectthe page automaticallybeforethese

registers are accessed.

The required data is then placed on the ports. It is specified directly in theequation in the hexadecimal format. The C-compiler does not allow the use of

the standard assembler binary format, B'lOlO', or decimal format, D'247'.

Finally the device is placed in the SLEEP mode to stop execution. Note the

parentheses after SLEEP( ) to identify the statement as a C procedure. The

NOP( ) is added as an existing code address for the PC to point to when thedevice is in the SLEEP mode.

Compilation of the Source File in the DOS Mode

The IDE .BAT file, described earlier can be used. I must be run from the main

PlC directory by the following command-line instruction:

C:\PIC> IDE C:\PIC\Cl\SETLEDS

The complete path to the user file, i.e, C:\PIC\, does not have to be included,

but it is entered only once, and the full path is safer. The text editor can thenbe selected by pressing the T key. If the program SETLEDS.C does not exit,

it will be created, and the name will be C:\PIC\Cl\SETLEDS.C.

Groups of statements in the C-Ianguage are normally bound together by a set

of braces. The group is also indented, to make the grouping clearer.

Sometimes the nesting of these braces can be quite deep, and indented some

distance from the leftmargin. The limiteddisplay space available in a window

to inspect the file may hide a big part of the well-indented statements. To

compensate for this, it is recommended to set the automatic tab distance of thetext editor to be used to 2 or 3, and to save it as the default setting. This will

still show a clear indentation, without taking up too much space.

When savingthe file, the path and nameare already specified, and do not have

to be typed in. The default directory must be the project directory, say

C:\PIC\Cl, and the program entered as is into a file. After making sure the

default directory is either selected, or specified in the name, the file can be

stored under the name, SETLEDS.C.

460 PlC Micra-Control/er Operation and Applications - Vol.II '

Page 179: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 179/260

 

To compile the program in command-line DOS, the instruction must be:

C:\PIC\CI> MPLABC SETLEDS.C laINHX8M

The laINHX8M switch specifies the format of the hex file that must be

generated. After compilation, a report message will appear to show if there

.wereanyerrors or warnings. If therewere, the listing filemust be loaded in the

text editor to find where they are, and what they are.

When the batch file is used, its display window will show the existing .ASM

file, and this file will be loaded and run through the compiler when the C-key

ispressed. The.C extensionand output Hex file type, INHX8M, are added bythe batch file automatically. The generated listing file can then be loaded by

pressing the L-key, to view any errors. One may alsobe curious to see how the

compiler has assembled the program.

Running the Simulator PS.EXE

The PS.EXE simulator uses the listing file ITomthe C-compiler as the source

file. It teststhe first text line to contain the word 'MPLAB-C' in the listing file.It will identify the file as a C-compiler listing file. The assembler code, code

address andgenerated assembler instructionswillbe extracted and shown in the

Source file window. The original C-program statements are included and

spread out on the right-hand side of the Source file window. It shows what

assembler codesweregenerated for eachC statement. Labels are not normally

used inC-programs,so the C statementsmaybe used by the user to tracewhere

he is in the original C-program. The next assembler instruction to be executed,

will be highlighted.

The !DE.BAT filewill specify the path and project name as an input parameter

to thePS program,to load the listing file automatically on startup. Single Step

or Fast Mode simulation can start immediately. A user can then follow the

execution of the assembler instructions to the end of the program.

Ch.12 PlC16F84 Micro-Controller Programming in C 461

Page 180: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 180/260

 

Testing on the Basic Board

As a fmal test, the Hex file can also be loaded into the pp .EXE Programmer,

by pressing the P-key in the batch file. If the configuration byte has not been

programmedbefore, it can be set in the programmer, and programmed into theBasic Board together with the user program. The program on the board can

then be tested by setting the Programmer in the Execute mode. After testing,

the power to the board can be switched off and the user ~an quit the

Programmer to return to the batch file.

The command-line programmer driver P84.EXE can also be used to program

the board. The SETLEDS.HEX file name must be included as an input

parameter to the program, e.g:

C:\PIC> P84 C:\PIC\Cl\SETLEDS.HEX

This program does not show any menus and other options, it cuts through and

immediately starts to program all the addresses included in the Hex file. If a

verify error occurs, the user will have the option to continue, or to quit. After

completion, the Programmer Board is set to the Execute mode and the board

will start to run the program immediately.---------------------------Compilation of the Source File in Windows MPLAB

After entering the SETLEDS program in the Text Editor window, it must be

saved. The window can stay open. To run the source program through the

compiler,the Make Project in the Project menumustbe selected. The button

showing an icon of a funnel will do the same. When the cursor is on this

button, the function of the button will appear in a box in the lower left corner

of the screen. The source filewill be compiled and a report windowwill showif there are any warnings or errors. The listing file can be viewed through the

Windows main menu option, by selecting the Absolute listing option, or by

Opening a file in the File menu.

Errors can then be corrected in the source C file. A Hex file will only be

generated if there are no errors. The source file will be saved automatically

when the Make Project (Compiling) option is selected.

462 PlC Micro-Controller Operation and Applications - Vol. 1I

Page 181: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 181/260

 

Simulation on MPLAB-SIM

To monitor the executionofthe program, the values for Port A and B must be

displayed on the screen. Under the Windows menu option, the Special

Function Registers window can be opened. It will show the current tris andport values. A user can now Single Step through the program by clicking the

footprints icon, or pressing the F7 key. While the program is executing, the

current assembler instruction on the listibg window, and the current statement

'on the C-programwindowwillbe highlighted. When a value is changed in the

Special Function Register window, it will change colour for one step.

Programming and Testing on the Basic Board

A shortcut to the DOS programPP.EXE can be created in Windows Explorer.

The PP.EXE program in any folder must be selected with a single click.

Throughthe File menuand the Create Shortcut option of Windows explorer,

a shortcut icon is created. It can be named, say PP, and for convenience, the

icon can be moved and placed with the MPLAB group in the Programs and

Microchip MPLAB folder (seeWindowsHelp). The PPprogram can then run

without an input parameter. The DOS window can be set to the full screen

mode by pressing Alt+Enter. This will enable proper mouse control if the

mouse driver has been installed for DOS programs in the Autoexec orConfig.sysprograms on startup of the PC.

Fromwithinthe PP.EXEprogram, the hex file can be loaded and programmed

intothe Basic Board for testing. After testing, the PP program can stay opened,

but hidden behind MPLAB by pressing the Alt+<Tab> keys. It can then be

toggled in again by the Alt+<Tab> key to be active, when requierd.

------------------------------........-------

Ch.i2 PlCi6F84 Micro-Controller Programming inC 463

Page 182: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 182/260

 

464

Notes:

PIC Micro-Controller Operation and Applications. Vol. 11

Page 183: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 183/260

 

Exercise 2: A 10 milli-second Delay Routine

Problem: Write a program in C to delay for 10milli-seconds and stop.

Recommended Reading: The While Loop (section 17, p-420, the #includedirective(in 32, p-437), and also the DELAYI4.H existing function include file

(37, p-447).

Program Example

/* Exercise 2 DELAY.C

A Simulated 10milli-second delay */

#include <16C84A.h>

#include <DELAY14.h>

void main( )

{

Delay_Ms-4MHz(IO);

brkp: while(l) ;

}

Discussion

New in this program is the use of an existing function: Delay_Ms_4MHz().

This function will delay a program for the number ofmilli-seconds, specified

in the parenthesisof the calling statement. More detail on the type of operation,

called the transfer of parameters to functions will be done in a later exercise.

For now, some delay is required in the next exercides to make the display on

the Basic Board practical. The function must just be used as shown. Thefunction is declared in the DELAY14.H header file, and exists in the

DELAY14.Lm file. The compilerwill load the existing code from these files

automatically. All that is required is the directive #include <DELAY14.H> at

the top of the program.

In place of a SLEEP instruction to stop action on the device, the while key

word and an empty statementare used. The condition between the parenthesis

is set as a non-zero value to make the test always true.

Ch.I2 PlCI6F84 Micro-Control/er Programmi,!g in C465

Page 184: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 184/260

 

Nonnally, a single statement, or braces and a block of statements must follow

this key word. Here, a single empty statement is used, (;). The processor will

stay and continue to execute this statement until power is removed or the Reset

pressed.

A program label has also been included at this statement as brkp:.

used to defme a breakpoint in the simulator at this code address.

taken to.execute the delay routine will be tested on the Simulator.

It will be

The time

Compilation of the Source File in the DOS Environment

Run the IDE.BA T file with the new directory and project name specified as the

input parameter. Copy the program into a file called DELAY.C. Compile theprogram and inspect the listing file if there were any errors or warnings.

Simulator Testing

The default system frequency of the PS.EXE program is set to 4 MHz. Each

machine cycle will therefore take I micro-second to execute. Another

frequency may be set in the Options selection of the main menu.

A break point must be set on or at the fIrstassembler instructionafterthe brkp:program label in the Source file window. It can be set by pressing the (+) key

while the main menu is active, to move a break point marker, «), forward. It

is shown in the spacesjust after the code addressesat the leftmargin, and it can

be placed by pressing the <Enter> key. This will place a soft break point. A

soft break point will be removed automaticallywhen the break occurs. A hard

break point can be placed through the Windows and Break. Point menuselections. The next exercise will also show how to define anu load a lable

symbol automatically into the Symulator. A hard break point is not removed

automatically. (See also theHelp menu of the Simulatorfor more infonnations

about the use and the setting of break points.)

A user can now Single Step through the program up to the instruction that calls

the delay routine. The <Del> key will clear the System Timer and Cycle Step

counter. The program can then be executed in the Fast Visual mode by

pressing the <PgDn> key, or even faster in the Quiet mode by pressing the F 10

key. When the break point is reached, the execution will stop, and the user can

read the expired System Time in the File Register window.

466 PlC Micro-Controller Operation and Applications - Vol.II

Page 185: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 185/260

 

The 10 milli-seconds will take approximately 4 seconds to simulate in the

Visual mode, and 1 second in the faster Quiet mode.

In the Visual Execution mode, the speed can be slowed down by keeping the

Control key downto show the Speed Bar in the Infonnation window. The Leftand Right Arrow keys will make the speed slower or faster, and the <PgUp>

and <End> keys will jump to the upper and lower limits of the speed control.

.The speed can also be pre-selected in the main menu, before execution starts.---------------------------------------Testing the Delay.C program, using MPLAB

-

Close the previous project in the Project menu and select to create a New

project. The newproject canbe called delay.pjt and placed in another folder,say C2. Follow the same procedure to specify the environment settings and

Project filesasbefore. Type in the delay.c program, save it, and run it through

the compiler.

A break point must be set at the program label brkp:. This can be done by

selectingtheDebug and Break Settings fromthe menus. In the Break Setting

window, the name of the break is break! by default. The Start point can be

selected by clicking the down arrow next to the Start box, and selecting the

symbol brkp from the list. Clicking the.w"boxwill add the break point to thelist. A break point can also be selected (or disabled) by placing the cursor on

the lineand clickingthe right button. On the small menu, break point must be

selected. The Stopwatch windowmust also be opened through the Windows

menu selection. Check that the frequency is set to 4 MHz.

The program can now be Single Stepped (F7) up to the delay routine calling

instruction,and the time reset to Zero. The Fastmode of simulation, called the

quiet mode can be selected through the Debug, Run and Run menu options.

Thismodecan alsobe selectedby clickingthe Green Traffic Robot icon, or by

pressing the F9 key. The colour of the bottom line of the screen will turn

yellowwhenthe program isrunning. After about 20 seconds, the executionwill

stop. The expired time can be read from the Stopwatch window. A slower

mode of execution, called the Animate mode, will update the screen after

executingeachinstruction. Thismode can be selectedthrough the Debug, Run

and Animate menu options, or pressing the Cntrl+F9 keys. The 10 milli-

seconds will take approximately 7Y2minutes to be simulated.Notes:

Ch.12 PlC16F84 Micro-Controller Programming in C 467

Page 186: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 186/260

 

468

Notes:

PlC Micro-Con/roller Opera/ion and Applications - Vol. 11

Page 187: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 187/260

 

Exercise3: A 4-BitBinary Counter

Problem: Writea program in C to display a 4-bit binary counter on the LEDs

of the Basic Board with and increment every 1 second.

RecommendedReading: TheDeclaration of Variables (section 12,p-428), the

a++ operator (section 14,p-445), the DO-WHILE loop(section 18, p-443), the

.FOR-loop(Section 19,p-444), and usingassembler instructionsin a C-program

(section 32, p-459).

Program Example

1*Exercise 3 CNT4.C

A 1second 4-Bit Binary Counter *1

#include <16C84A.h>

#include <DELAY14.h>

void main( )

{ int i;

#asm(Cnt SET i ;F:); IIDefine variable symbol for the PS Simulator

TRISA = 0;

PORTA=O;do

{ for (i=0;i<10;i++)Delay_Ms-4MHz(lOO); 112* 1 for Simulator

brkp: PORTA++;

} while(l) ;

}#asm(BrkPnt SET brkp ;L:); IIDefine Label symbol for PS Simulator

Discussion

A local variable is declared in the main program as a counter for the FOR loop.

The DO-WHILE loop is used to repeat the program continuously. In this case,

the WHILE appears after the block of statements. For a DO-WHILE loop theblock will be executed at least once before the WHILE condition is tested.

Ch.I2 PlCI6F84 Micro-Controller Programming in G 469

Page 188: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 188/260

 

The specification for the FOR loop consists of the initial value (;fthe counter,

followed by the condition test to continue the loop, and the change of the

counter for every loop. Directly after the FOR loop specificationmust follow

either a single statement, or braces and a block of statements. A single

procedure call is used after the FOR statement in this program.

A program label, brkp:, has been insertedto mark a point inthe loop for timing

tests on.the simulator. Initially, the FOR loop count can be 2, and the delay

functioncan be 1milli-seconds,a total of2 milli-secondsper loop. To simulate

a delay takes considerablylongerthan the real time. With thesereduced values,

the logic of the operation can be tested within reasonable time. The 1 second

delay of the final program will take approximately2 minutesin theQuietmode,

and 5 minutes in the Visualmode for the PS.EXE program to simulate. For

MPLAB-SIM, it would take approximately 33 minutes in the quiet mode and12Yzhours in the Animate mode to simulate 1 second real time!

Simulation and Testing in the DOS Environment

Copy and store the program in the 3rd project sub-directory.

In the PS Simulator program, inspect the listing file in the View mode of the

Source file window, by pressing <Enter> when the window is active, or by

clicking the cursor inside the window. The RAM address allocated to the i

variable is indicated on the left side of the screen. It is placed on, or below the

declaration line of the i variable in the C-program. It is shown as a two digit

hexadecimal value, two space,sfrom the left margin. The C-compiler reserves

RAM addresses OChto lOh for systemvariables, before it will start to allocate

user variables. The single assembler defmition line will defme a user RAM

variable Cnt, and SET the value to the same address that i was allocated to by

the compiler. The contentsof this variable canbe displayedbyopeninga UserRAM Monitor window through the Windows menu. The size of the window

can be reduced in height to show only the address of the Cnt variable. The

symbolnamewill automaticallybe loadedwhen the F: markerwas included asthe first characters in the comment line of the assembler instruction. The

window can then be placed in a corner, out of theway,not to interferewith the

monitoring of the Source file.

A hard break point must also be inserted at the first instruction next to, or after

the Brkpnt: program label.

470 PIC Micro-Col1troller Operation and Applications - Vol. 11

Page 189: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 189/260

 

An Access Break Point may also be inserted to stop the program every time

the Cnt variable is either readfrom, written to, or both. Access Break Points

are selected similar to the Code Address break points, except that a RAM

address is specified.

The program can now be Single Stepped and the execution monitored up to

where the delayprocedure is called. Then the program can run in a fast mode

up to the break point, single stepped through the Port increment, and run in a

'fast mode again up to the next break.

In this way a user can monitor the essential instructions within a reasonable

time, withoutspendinghours stepping thoughthe boring delay loops. If it still

takes too much time to run through the delay loops, one can edit and alter the

instructionthat loads the preset value into the delay counter to a much smaller

value, inthe Source Window Edit mode, Another method is to simply edit and

replace the CALL (delay loop address) assembler instruction with a Nap.

Once the logic is tested, the loop values can be incremented to 10 times

100milli-secondsfor the final timing test. A single breakpoint can be defmed

at the label address Brkpnt, and the simulated time tested for one loop.

Finally, the program can be loaded into the Basic Board for real time testing.

------Simulation on MPLAB

The program can be copied and saved in a new project folder.

The listing file can be inspected to fmd the RAM address allocation of thei variable of the main routine. It is a local variable, and therefore it will not

appear in the general symbol list. The C-compiIer does not re-use local

variables after a procedure was completed, so a user may consider making all

his variables global. It will not save available variable memory space.

Ifi is made a global variable by placing above the main routine, a New Watch

window can be opened through the Windows menu, and the i symbol selectedand Added to the Watch window.

Ch.12 PlC16F84 Micro-Controller Programming in C 471

Page 190: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 190/260

 

The Delay_Ms- 4MHz will still take a long time to complete. One mayconsider to replace this delay calling statement with a simple NOP( ) in the

original C-program. Then one can step through the progJ;am within a

reasonable time to test the logic, before programmed onto the Basic Board for

real time testing.

~~

Notes:

472 PlC Micro-Controller Operation andApplications - Vol.II

Page 191: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 191/260

 

Exercise 4: An 8-Bit Binary Stopwatch

Problem: Write a C-program to drive an 8-bit binary stopwatch on the LEDs

of the Basic Board. The RB7 push button must be used as the STOP control,

and RB4 as the RUN control. A reset must re-start the counting ITomzero.

Recommended Reading: Constant declarations (Section 13, p-409);

!he IF statement (Section 15, p-417).

Program Example

/* Exercise 4 SW.C

An 8-Bit Binary Stopwatch */

#include <16C84A.h>

#inc1ude<DELAYI4.h>

void main( )

{ const char STOP = 7;

const char START = 4;

TRISA = 0;

TRISB = OxFO;

OPTION = 0;

PORTA=O;

PORTB = 0;

while(l)

{ Delay_Ms- 4MHz(100); /I I for Simulator or a few NOP()'sPORTA++;

if (PORTA > 15){ PORTA = 0;

PORTB++;

/* High nibble as Inputs */

/* RB P1;111-upsnabled */

}

if(pORTB.STOP ==0)while(pORTB.START= = 1);}

Ch.12 PIC16F84 Micro-Controller Programming in C 473

Page 192: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 192/260

 

Discussion

The controls on pins RB7 and RB4 are declared as local constants to the main

program. The high nibble pins of Port B is set as inputs to read the push-

buttons and the Port B internal pull-up resistors are enabled on the OPTIONregister.

The continuous loop containsthe delay, the increment,andthe control pin tests.

Note the use of the dot operator ( . ) to specifYa single bit of Port B for the

control tests: If the stop button is pressed (= 0), the programwill continuously

do the while test while the RUN button is released ( = 1). When the RUN

button is pressed ( = 0 ), the program will continue. A switch debounce delay

routine is not required for this type of two button control.

Simulation and Testing in the DOS Environment

The STOP and RUN symbols are not defined as Bit symbols for the Simulator

in this exercise. When a bit in the User Bits monitor window is allocated to a

port, the output buffer value will be shown. In this exercise, these symbols are

used for input pins. When the program is simulated, the function keys Fl to F8

can toggle input pin levels for Port B, and the Shift+F4 to Shift+F8 can be used

for Port A. The function and number of the pin must be remembered, or written

down, so the user will know what key to press to get the required level change

on an input pin. To have a visual on-screen record of the pins and their

functions, a user can defme a Pin Name Line for each port. This line can be

displayed in the Information line of the Simulator during simulation.

The editing of a Pin Name Line for Port B can be done through the Optionswindow and the Name PortB Pins menu selection. The flashing cursor in the

information line allows a user to alter the default line, or to dcfine his owndefmitionline for up to 52 characters. Any ASCII characters above 29 can be

entered through normal keys, or through the Alt and number pad keys, e.g.

Alt+(1 7 9) will place the box character ( I) at the current cursor position. A

typical line for this exercise, togetherwith the related Port B pins and function

keys, are shown below:

B>:lstartl - I - IStop - I - I - I -RB7 RB6 RBS RB4 RB3 RB2 RB1 RBO

F1 F2 F3 F4 FS F6 F7 FB

I Unfo line)

(Port B pins)

(Function keys)

474 PIC Micro-Controller Operation and Applications - Vol. II

Page 193: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 193/260

 

The name block for each pin is also a hot spot for mouse click controls of the

input pins, so the spacing is important. It allows 5 characters for each name.

When a pin is configured as an Input, the name will be highlighted. If the pin

is cleared, the back ground colour of the.box will also be highlighted. Output

pinnames willbe shown in normal colours. Port A names have 10 characters

for eachpin name.

The <Enter> key will store the new line, and the <Escape> key will keep the.old one.

When the simulator runs in one of the fast modes, the Port B linewill be shown

in the Information window. A similar line can be defined for the Port A pins,

and will be displayed while the Alt key is kept down. In the 'Ready' or Single

Step modes, the Port B line can be shown by keeping a Shift key down. The

functionkeys for Port B will also operate while the Shift key is kept down. A

mouse click on an input pin name will toggle the pin, and change thebackgroundcolour. The state of the pins can therefore be viewed in a glance.

A new Pin Name definition line can also be loaded automatically 1Toma

special comment line included in the user program. This will be used and

explained in the next exercise.

The correct operation of the program can be tested on the Simulator, and alsothe action of the button controls. Note that the control keys must be pressed a

second time to simulate the release of a button on the port pins.

Once completed, the delay can be re-adjusted to 100 msec, the program re-

compiled, and loaded into the Basic Board for testing.-------------------------------

Testing the Program using MPLAB

The pressing of the buttons can be simulated by opening an Asynchronous

Stimulus Dialog window, through the Debug and Simulator Stimulus and

Asynchronous Stimulus menus. Twelvebuttons are available. They must be

defined to place specific logic levels on specific pins, by placing the cursor on

a button, and pressing theRight-hand mouse button. From the sub-menu the

Assign Pin option can be selected. A listof the availablepins will appear, and

the appropriate pin can be selected by a double click.

Ch.J2 PICJ6F84 Micro-Con/roller Programming in C 475

Page 194: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 194/260

 

The first button can be used for RB? and the second forRB4. Then the Toggle

action must be selected for both pins. While the program is running, clicking

a button will toggle the value of the port, provided it is an input. When the

program does not run and a button is clicked, a single step must fIrst be

executedbefore the action is recorded. The reset value for Port B isOOh,andmust be set to B'lOOlOOOO'efore the pin test instructions are done the fIrsttime.

The del!iymust be reduced to a smaller value, say 1milli-second, or replaced

by a fewNOP( ) instructions. Then the program can run in the Animatemode.

The PortA increment,and also the action ofthe pushbuttons can bemonitored.

A Special Functions Register window can be opened, reduced in size, and

rolled to show only the port values. A few instructions can be stepped throughand the Simulated buttons clicked once, to set the Port B inputs to 1.

When the program runs in. the Animate mode, the Port A value will be

incremented by one about every 40 seconds (for a I msec delay). When the

RB? (STOP) button is pressed, the program will stay on the pin testing

instruction. RB? must be pressed again, to release the simulated external

button, before RB4 can be clicked to RUN the Port A increment again. RB4

must then be clicked again to release the simulated external button.

Finally, the delay routine can be reset to the original 100milli-sfconds and the

program can be tested on the Basic Board.

------------Notes:

476 PlC Micro-Controller Operation and Applications - Vol. 11

Page 195: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 195/260

 

Exercise 5:An 8-BitBCDUp/DownCounter

Problem: Write a program in C for an 8-bit BCD counter with single button

STOP/START control. It must count down while another button, DOWN, is

kept down. The counting period must be 0.25 seconds.

Recommended Reading: Declaration of Procedures ( 30, p-431 ).

'program Example

1*Exercise 5 BCD.C

8-Bit BCDUp/Down Counter *1

#include <16C84A.h>

#inc1ude<DELAYI4.h>

const char RUN = 7;

const char DOWN = 4;

signed int a = 0; /I Global variable for C-compiler

signed int b = 0; /I do.

#asm(A SET a ;F:); ffSymbol allocation and marker for the PS Simulator

#asm(B SET b ;F:); IIdo.

void inc( );

void dec( );

void idle( );

void main( )

{ TRISA =0;TRISB =OxFO;

OPTION =0;

while(1){ Delay_Ms- 4MHz(250); If lms for Simulator or a fewNOP( )'s

. if(PORTB.DOWN = = I) inc();else dec( );

PORTA = a;

PORTB = b;

if (PORTB.RUN = = 0) idle();

1*High nibble inputs *1

f* RB pull-ups

}

} /I Continued....

Ch.12 PlC16F84 Micro-Controller Programming in C 477

Page 196: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 196/260

 

void inc( )

{ a++;

if (a> 9)

{ a=O;

b++;if(b> 9) b = 0;

}

void dec( )

{ a--',

if (a < 0)

{ a=9;

b--',if (b < 0) b = 9;

}

}

void idle() IIUse a NOP() as a delay for the Simnlator

{ do Delay_Ms- 4MHz(50); while (PORTB.RUN == 0);do Delay_Ms- 4MHz(50); while (PORTB.RUN == 1);do Delay_Ms- 4MHz(50); while (PORTB.RUN = = 0);

}

IIA special comment line for automatic loading of a Pin Name Line follows:

;IIPinsB:B>:1Run 1-1-IDown 1- 1- 1- 1- I

Discussion

In this program, three procedures are defmed, one for BCD increment, one for

BCD decrement and one to let the program idle after the STOP/ST ART controlbutton was pressed, The program will stay in this routine until it was released,

pressed, and released again. The two digit values of the counter will be stored

in two global variables a and b. They are declared global so that the

procedures can also have direct access to these variables. When t~e variables

are counting down, they may pass through the zero point and become negative.

In this case, it is more sensible to declare these variables as signed integer

values, If signed variables are used, then the test for negative can be done for

the value smaller than zero, in place of equal to 255.

478 PlC Micro-Controller Operation and Applications - Vol. II

Page 197: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 197/260

 

The two variables are of the same data type, so they may also be declared in the

same line, e.g. signed int a = 0, b = 0;. The two constants to indicate the pin

number of the two controls are also global. This will enable one to use them

in all the procedures.

Note the use of the DO-WHILE stateJ11entsto control the running of the

program in the idle( ) procedure. This procedure will be called when the RUN

is pressed for the first time. The program will wait in the first loop until the

'button is released. The 50 milli-second delay will eliminate switch bounce.

The secondloopwill be executed while the button is released. The third loop

will be executed while the button is pressed and kept down the second time.

Onlyafter the button is released for the second time, will the program return to

the main procedure and continue counting.

The use of the DO-WHILE statement in place of the WHILE statement, will

force the program to do the delay first, before the state of the button is tested.

If WHILE only statements were used, switch bounce can move through the

procedure rapidly. Examine the logic of the example below for an imaginary

rapid switch bounce:

{ while (pORTB.RUN ==0) Delay_Ms- 4MHz(50);while (PORTB.RUN == I) Delay_Ms- 4MHz(50);

. while (pORTB.RUN ==0) Delay_Ms- 4MHz(50);}

Simulation and Testing

Simulationandtesting of the program is the same as for the previous exercise.

The special Pin Name defmition comment line at the end will be loaded

automatically into the PS Simulator. It is triggered by the ;//PinsB: marker.

Once the logic and action of the push button controls were confirmed on the

Simulator, the delays can be updated and the program tested on the Basic

Board. The switch bounce delays can only be tested and adjusted for a

comfortable user interface when the program runs at real time speed.

---------------------------------

Ch.12 PlC16F84 Micro-Controller Programming inC 479

Page 198: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 198/260

 

480

Notes:

PlC Micro-Control/er Operation and Applications - Vol. 11

-

Page 199: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 199/260

 

Exercise 6: BCD Up/Down Counter using the Internal Timer

Problem: Write a program in C for an 8-bit BCD counter with single buttonSTOP/START control. In this case the counter must reverse the count direction

every time the DIR for DIRection button is pressed and released. The countingperiod must be 0.1 seconds.

.Recommended Reading: Passing of Parameters to Procedures (30, p-431).

Program Example

1*Exercise 6 BCDT.C

8-Bit BCD Up/Down Counter (Timer) *1

#include <16C84A.h>

const char RUN = 7;

constcharDIR= 4; II.Directioncontrol

;//PinsB:B>:IRun 1- 1- I Dir I - I - I - I - I

signed int a = 0;signed int b = 0;

#asm(A SET a ;F:); IISymbol allocation and marker for the PS Simulator

#a§m(B SET b ;F:); II do.

void inc( );

void dec( );

void idle( );

void delay(unsigned int d);

void main( )

{ char updn = 1;

#asm(UpDn SET updn ;F:);

II Up count on reset

II Local variable symbol for transfer to PS.

TRISA = 0;

TRISB = OxFO;

OPTION = Ox07;

while(1)

{ delay(195); 1150000+ 256 = 195delay(195); 112x 50000 Ils= 0.1 sec

if (PORTB.DIR = = 0) updn '"'=1; IIXOR 01

II High nibble as Inputs

II Pull-ups, Prescaler: 256

Ch.I2 PlCI6F84 Micro-Controller Programming in C 481

Page 200: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 200/260

 

if (updn = = 1) inc();else dec( );

PORTA = a; .PORTB = b;

if (pORTB.RUN = = 0) idle();}

}

void inc() (Same as exercise 5)

void dec() (Same as exercise 5)

void idle( )

{ do delay(l95); while (PORTB.RUN ==0) ;

do delay(l95); while (PORTB.RUN == l) ;do delay(l95); while (PORTB.RUN ==0) ;

}

void delay(unsigned int d)

{

#asm(D SET d ;F:);

TMRO = 256 -d;INTCON.TOIF = 0;

while (INTCON.TOIF = = 0);

//Symbol name for local variable in delay()

}

Discussion

Here a function is declared and a parameter passed by the calling routine. It is

the sameas for theDelay_Ms- 4MHz( ) functionused before,but the user must

now write the procedure himself. The data type and the variable name are

specified in the parenthesis of the function declaration. The 'names of the

Timer, the interrupt flag, TOIF,and the INTCON registers are d.~finedin the

16C84A.h include file, and can be used as is to specify a register, or with the

dot operator ( . ) to specify a bit.

For the direction control one requires an additional variable to record the

previous setting. When the DIR button is pressed, the 1 or 0 value in the updn

variable will be complemented by the bitwise XOR operator, /\. If the button

is kept down for the program as it is, the direction will change for every loop.

482 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 201: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 201/260

 

As an exercise, the user must use another variable bit to store the state of the

button for every loop. Only when the state of the button has changed from not

being pressed in the previous loop, to being pressed for this loop, must the

direction change.

Simulation and Testing

The delay can be shortened for the Simulator by specifying the prescaler to

have a divideby value of2, (OPTION = OxO1),and the parameter for the delaycalls decreased to 2.

The switch bounce delays and the direction reverse button action can be tested

and adjusted for a comfortable user interface on the Basic Board.

--------

Ch.i2 PlCi6F84 Micro-Control/er Programming in C 483

Page 202: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 202/260

 

Notes:

484 PlC Micro-Controller Operation and Applications - Vol. 11

Page 203: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 203/260

 

Exercise 7: Disco Light Chaser

Problem: Designof a Disco Light Chaser. It will displayvarious lightsequences on the LEDs of the Basic Board.

The light sequences must be stored in the code memory by means of look up

tables. There must be four different sets of 8 light sequences each. The

cUfferentlight sets must be selectable by two push-buttons.

There must also be 10 different speeds, selectable by two other push buttons.

The speeds must vary &om 0.1 second to I second in steps of 0.1 second.

The current set, and also the current speedmust be stored inEEPROM to retain

these values when power is switched off. When the power is restored, thesystem must continue at the same speed and with the same set it was using,before the power break.

The Configuration Byte and the initial EEPROM Data must also be included

in the Hex file for programming into the Basic Board.

Possible light sequences are shown below:

Possible Light Sequences:

1000000I0100001000100100000110000001100000100100

01000010

10000001

100000011100001111100111111111110111111000111100

00011000

00000000

11000011011001101011110111011011001111000110011011000011

10000001

11001100

01100110

00110011

10011001

11001100

01100110

00110011

10011001 etc.

Recommended Reading: Read the sections on Constants (Section 13, p-409)

on Arrays (Section 24, p-425), on Header files (Section 37, p-447).

Ch.12 PIC16F84 Micro-Controller Programming in C 485

Page 204: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 204/260

 

Program Example

/* Exercise 7 DISCO.C

Disco light chaser */

#incIude <16C84A.h>

#includ~ <ee14.h>#incIude <math.h>

#incIude <delay14.h>

const char eespeed = Ox3E; // EEPROM Address for Speedconst char eeset =Ox3F; // EERPOM Address for Set

#asm(ESpeed SET eespeed ;E:);#asm(ESet SET eeset ;E:);

const char FAST=7; // ButtononRB7const char SLOW =6; // do. RB6

const charUP = 5; // do. RB5

const char DOWN=4; // do. RB4

;/lPinsB:B>:1 Run I - I -IDownI - I - I - I - I

unsigned int speed;unsigned int set;

unsigned int cnt;

unsigned int disp;

#asm(Speed SET speed ;F: );

#asm(Set SET set ;F: );

#asm(Cnt SET cnt ;F: );

#asm(Disp SET disp

// Ring counter for sequence

11Store for lookup value

;F: );

const char a[32] = { // Lookup TableOx81,Ox42,0x24,Ox18,0x24,Ox42,Ox81,OxOO,

Ox81,OxC3,OxE7,OxFF,OxE7,OxC3,Ox81,OxOO,

OxC3,Ox66,Ox3C,Oxl,Ox3C,Ox66,OxC3,Ox81,

OxCC,Ox66,Ox33,Ox99OxCC,Ox66,Ox33,Ox99};

void delay(unsigned int d);

486 PlC Micro-Controller Operation and Applications - Vol. 11

Page 205: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 205/260

 

void main( )

{ TRISA=0;TRISB = OxFO;

OPTION = 0;

speed = Read_EEProm(eespeed);set = Read_EEProm(eeset);

while(1)

{ for(cnt = O;cnt< 8;cnt++)

{ disp = a(set*8 + cnt];

PORTA = disp;

SWAPF(disp);

PORTB = disp;

delay(speed);

// Initial Setup

if(PORTB.SLOW = = 0)

{ if (speed> 1)

{ speed--;

EECON1.EEIF = 0;

Write-EEProm( eespeed,speed);while (EECON1.EEIF == 0);

}

}

if(pORTB.FAST ==0){ if (speed < 10)

{ speed++;EECON1.EEIF =0;Write -EEProm(eespeed,speed);

while (EECON1.EEIF = = 0);

}

}

if(pORTB.UP = = 0)

{ set++;

set &= Ox3;

EECON1.EEIF = 0;

Write - EEProm( eeset,set);

while (EECON1.EEIF = = 0);

while(PORTB.UP = = 0);

}

Ch.i2 PICi6F84 Micro-Controller Programming inC 487

Page 206: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 206/260

 

if(PORTB.DOWN ==0){ set--;

set &= Ox03;

EECON1.EEIF = 0;

Write-EEProm(eeset,set);while (EECON1.EEIF ==0);while(pORTB.DOWN ==0);

.}}

}

}

void delay(unsigned int vspeed)

{

#asm(Vspeed SET vspeed ;F:);

for(vspeed =O;cnt< (vspeed + l);vspeed++){ Delay_Ms- 4MHz(lOO); IIUse Delay_lOxUs-4MHz(33) or smaller

} II for the Simulator.

}

void loadee( ){

#pragrna memory ROM [Ox0140]@ 0x2000;#asm

ORG 0x2007 IIConfigurationByteDW Ox3FFI

II Configuration Byte and EEDATA

ORG 0x213E

DW 5

DW 0#endasm

#pragrna memory ROM [MA{CROM-loadee) @ loadee;}

488 PIC Micro-Controller Operation and Applications - Vol. II

Page 207: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 207/260

 

Analysis

A lookup table can be created in C by defining a constant aITaywith fixed

values, as shown in the example above. To access a specific element, an

expressionsuchas x= a[disp]; can be used. The index, disp, can also be aconstant value or a calculation. The index numbers of the an-ayrange ftom 0to 31.

If the table presents 4 sets of 8 sequences each, the sequences can be repeated

in an 8-times FOR loop, with cnt an incrementing counter ftom 0 to 7. The

CUITentet number, set, varies between 0 and 3. The element calculation can

then lie done with the expression disp = a[set * 8 + cnt]. When the

multiplicationoperator is used, the math.h header file must be included at the

beginning of the program.

The main loop consists of one of the sequences ftom one set being retrieved

ftom the lookup table an-ayand displayedon the LEDs. The loop also contains

the delay part, and reads the buttons and react if any has been pressed.

Only the variable set may go negative, so it can be a signed int data type.

Standard functions to store and retrieve data to and ftom the EEPROM exist in

the EE14.h include file. (Section 37.) .To read ftom the EEPROM, use function: x = Read_EEProm(EE_address);

To write to the EEPROM, use procedure: Write_EEProm(EE_address,data);

In the real situation,theminimumdelay of 100milli-seconds is longer than the

10milli-seconds required between EEPROM Data writes. For reduced speed

simulation, the extra test for the EEIF to be set before continuing has been

included. MPLAB-SIMwrites to the EEPROMdata immediatelyand does notsimulate the 10milli-secondswaiting time to completethe programming of the

EEPROM data. It does however require the 55, AA writing sequence to

EECON2, before a writewould take place. PS.EXE simulatesboth, and a eITor

messagewillbe givenwhen a user attempsto access the EEPROMwhile a write

cycle is in progress. The EETimer can be cleared to reduce the waiting time.

Ch.I2 PICI6F84 Micro-Control/er Programming in C 489

Page 208: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 208/260

 

The variable delay operation was done by feeding a variable value to the delay

procedure. The speed variable can vmy from 0 to 9, to represent a speed from

0.1 seconds to 1.0 seconds. The FOR loop in the delay routine therefore starts

at 1, up to (vspeed + 1), where vspeed is the local variable transferred to the

delay routine.

The Configuration Byte value and the initial EEPROM Data oytes can beincludeq as shown in the loadee() routine. This routine is not cfliledfrom the

main routine, because it does not contain executable data. It would, however,

be compiledand codewill be generated. The #pragma memory s.tatementsare

included to set the code address to the required program memory values, and

to reset it againfor the rest of the program that follows in the include libraries.

The specified EEPROM data values will also be loaded into both simulators

automatically. If the configuration byte contains the bit to enable the WatchDog Timer, the WDT will be enabled automatically in the PS.EXE simulator.

Simulation and Testing in the DOS Environment

The globaland local variablesymbols,and also the EEPROMbytesymbolswill

be loaded into the Simulator a,utomatically,provided theywere defined by the

assembler SET directives with the special symbol allocationmarkers. A User

RAM window can be opened to view and monitor appropriate bytes. An

EEDATA window can also be opened to monitor the two EEPROM bytes.

The last chapter of this volume contains the Operating Manual of the PSSimulator. The exact format and use of the various automatic information

transfer markers and lines are explained in detail.

----------------------------------

490 PlC Micro-Controller Operation and Applications - Vol. 11

Page 209: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 209/260

 

Simulation on MPLAB

To viewthe values of the variables speed, set, cnt and disp, a Watch window

can be opened through the Windows menu. The four control buttons must be

selected and set in the Asynchronous Stimulus Dialog window, and toggledto be high soon after the program starts. An EEPROM data window can also

be opened to monitor the values. To run the program in the Animate mode, the

delay routine can be reduced to approximately 30 micro-seconds, Le.

belay_lOxUs- 4MHz(3).

The display values on the lower nibbles of Port A and B can be monitored by

addingtheports to theWatchwindow. 1'hiscan be done by clicking the cursor

on the left top corner of the Watchwindowto enable a sub-menu. On this sub-

menu, the Add Watch optionmust be selected, PORTA and PORTB Added,and through the Properties option selected to be displayed as 8-bit binarynumbers.

Ch.12 PIC16F84 Micro-Controller Programming in C 491

Page 210: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 210/260

 

Notes:

492 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 211: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 211/260

 

Exercise8: Potting the Ducks

There are theseDucks flyingpast fonn right to left in a circular loop. As a duck

disappears off the left-hand side, a new one will appear from the right. Your

gun is pointingat bit number 4 and the triggermay onlybepulled while a duckis at position number 4. If the trigger is pulled before or after, one more duck

will start flyingin fromthe right-hand side. If a duck ispotted, itwill disappear

.and your score will be incremented by 1. If all the ducks are in the pot, the

LEDs must give two Hip, hip, hurrahs!

Two keys must be used to control the speed of the ducks. Another key to

display your score in a two-digit BCD number, and the fourth key can be the

trigger. The current speed, position and score must be stored in EEPROM.

Whenthe power isremoved fromthe board and restored, the samesettingsmustbe used to continue the game.

Hints: Use a nonnal8-bit variable, say disp, to store the stateof the ducks, and

only separate the nibbles when they must be displayed on the ports. The«

operator will shifta byte to the left,but it will alwaysmove a zero into the LSB,and the MSB will be lost. To roll the ducks out at the left-hand side and in at

the right-hand side, use a variable to store to previous value, say prevdisp.

After the shift, test the MSB value of prevdisp and set the LSB of the current

disp only if the MSB ofprevdisp was set.

It is simpler to store the 2 digit BCD score in two separate bytes for both the

BCD incrementingand the outputto the ports. While the score is displayed,the

state of the ducks will be preserved in the separate variable, disp.

Store the settings in EEPROM only when there was a change in the speed, thescore or the number of ducks available.

Analyse the problem, write the program and test it on the Simulator and theBasic Board.

----------------------------------

Ch.I2 PICI6F84 Micro-Controller Programming in C 493

Page 212: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 212/260

 

Notes:

494 PlC Micro-Con'troller Operation and Applications - Vol. 11

Page 213: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 213/260

 

13. Introduction to the Rest of the PlC Family

Table of Contents

Page

Chapter Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 497

The Lower RangeMembers of the PlC Family. . . . . . . . . . . . . . . . .. 499

The Mid-Range of the PlC Family. . . . . . . . . . . . . . . . . . . . . . . . . . .. 501

Comparison Between the 12Cxxx, 14000 and 16Cxxx Controllers. .. 502

EEPROM and FLASH Code Memory. . . . . . . . . . . . . . . . . . . . . . . .. 503

Code MemoryCore Width and Size. . . . . . . . . . . . . . . . . . . . . . . . . .. 504

Special Function Registers and User RAM 506

Device Pin and Port Comparisons. . . . . . . . . . . . . . . . . . . . . . . . . . .. 511

Configuration Bits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 513

Instruction Set Comparisons and Conversions. . . . . . . . . . . . . . . . . .. 518

TheSLEEPModeandWake-upITomSLEEPReaction 519

The Power Control Register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 520

SpecialisedModules in Various PlC Devices. . . . . . . . . . . . . . . . . .. 521

The Timer Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 522

Timer 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 522

(Continued...)Rev.5 6/02

DNdB

495

Page 214: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 214/260

 

Table of Contents: (Continued...)Page

Timer2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 524

TheCaptureModule. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .525

TheCqmpareModule. .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 526

ThePulse-Width-ModulatorModule 527

The Second Capture/Compare/Pulse-Width-Modulation Module. . .. 530

Analogue-to-Digital Conversion in General. . . . . . . . . . . . . . . , . . . .. 531

The ADCModule of the PIC16C7x and PIC'924 Devices. . . . . . . .. 532

The ADC Module of the PIC14000 .. . . . . . . . . . . . . . . . . . . . . . . . .. 536

The Parallel Slave Port. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 537

The Serial Ports. . . . . . . . ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 538

The Serial Communication Interface Module (USART) 538

Voltage Comparator and Reference Modules. . . . . . . . . . . . . . . . . .. 539

The LCD Direct Drive Modules of the PICI6C923 and '924 540

The Additional Battery Monitoring Features of the PIC14000 540

The High Range PlC Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . .. 540

Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 541

---------------------

496 PlC Micro-Controller Operation and Applications. Vol. 11

Page 215: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 215/260

 

13. Introduction to the Rest of the PlC Family

Chapter Summary

This chapter introduces the other members of the PlC family of micro-controllers. Someof the lower range devices, such as the 12C5OXand 16C5x,andmostof the mid-range devices, such as the 16C6x, 16C7x, 16C8x, 16F8x

JUld16C9xx,arecomparedto the PlC 16F84. Similaritiesand differences are

pointed out.

Direct-comparisons are made under the following headings: A general

comparisontable;CodeMemory size and access for 12-and 14-coredevices;

SpecialFunctionRegister and RAM access and size; Device Pins and Ports;

Configuration bits; Instruction Sets; SLEEP mode and Watch Dog Timer;Power Control Register; and also Special Functions, such as additional

Timers, Capture/Compare/Pulse-Width-Modulators, Analogue-to-DigitalModules, etc.

The Special Functions of some devices are explained in more detail to get a

basic idea of the operation. It is not the intention of these notes to replace the

data books of these devices. These notes may be used as a guide to a user to

make the best selection of a specific device to solve a specific problem.

Somedevices contain quite a sophisticated built-in Serial Port and USART.

An the various modes for the Serial Ports, the settings, registers and the

operationare too longand complexto summarise in a fewpages. Onlya briefoverview is included. It is left to the student for self study directly trom the

appropriate data sheets.

Finally,the higher range ofPlC micro-controllers is briefly introduced. It is

similar in operation and internal architecture as the mid- and lower range

devices, but some of the differences are too great for a simple comparison.These devices are also left for self study, or a possible future course or

workshop.

--------

Ck13 Introduction to the Rest of the PlC Fami~497

Page 216: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 216/260

 

498

Notes:

PlC Micro-Controller Operation and Applications - Vol. 11

Page 217: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 217/260

 

The Lower Range Members of the PlC Family

The lower rangemembers of the PlC family consist of the following types:

PIC12C508, PIC12C509,PICI6C54, PICI6C55, PICI6C56, PICI6C57,

PICI6C52, PICI6C54A, PIC16C58A

The features of the lower range devices are to a great extent identical to the

PICI6F84, with only a few critical differences. Most of the hardware and

software applications of the PIC16F84 can be transferred directly to one of

these lower range ofmicro-controllers,provided the differenceswere checked

for compatibility. Small changes may have to be made to some instructions

and the hardware layout.

The major difference between the lower range and medium range of PlC

controllers, is that the lower range controllers have no interrupt features.

They do havea Wake-up-ftom-SLEEPfeature ftom the Watch Dog Timer or

by applying a system reset. The 12C50x devices also have a wake upfrom

pin level change on some of the General Purpose Input/Output ports.

The number oftotal deviceand general Input/Output pins of the lower range

vary from 8-pinswith 6 I/O pins, 18-pins with 12 I/O pins, and 28-pins with19generalpurpose I/O pins. The 28-pin devices have and additional Port C.

Apart fromthe 12C50xdevices, the lower range micro-controllers cannot be

serially programmed while in-circuit. A special parallel programmer, such

as the PICSTART or the PRO MATE Universal Programmer is required.

Device varieties include Factory Mask Programmed, One-Time Program-

mable and EPROM based code memory chips.

Smallerdifferences in the softwareand hardware are summarised as follows:Hardwaredifferences include the dedication of the Real Time Clock/Counter

input pin that cannot be used as a general purpose I/O port. There are no

internal pull-ups on the Port B pins, and no special Power-Up Timer. The

internal file register organisation of these chips is the same as the Page 0

registers of the PlC 16F84. ThePage 1 registers, such as the OPTION and

TRISn registers are accessed by the OPTION and TRIS instructions. Theyhave the sameeffect as the MOVWFOPT andMOVWF TRISn instructions.

The contents of the Work Register will be moved into the selected register.

Ch.I3 Introduction to the Rest of the PlC Family 499

Page 218: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 218/260

 

The program memory core size is only 12 bits wide. Therefore. the CALL

and GOTO instructionscannot contain the complete destination addresses to

all locations in the code memory. When calling a sub-routine, the 9th bit of

the program counter will always be cleared and the higher Program Counter

bits (where applicable), must be set by software in the STATUS register.This will have an influencewhere sub-routinesmayor may not be located ina program layout. The operation of the CALL, the GOTO, and instructions

modifying the Program Counter, will be pointed out for every member

according to code memory size.

The program counter stack is only two levels deep, but it is wide enough to

contain the completeProgram'Countervalue. Thismeans that althoughthere

are some limitations of where to place the sub-routines, they can be called

ITomanywhere in the program.

The absence of an interrupt structure in these controllers makes the RETFIE

instruction superfluous, and only a RETLW is available. The normalRETURN instruction is not available either. Other instructions that are not

available, are the ADDLW and the SUBLW instructions. These can be

replaced by first loading a literal in a spare byte. Then the normal ADDWFand SUBWF instructions will have the same effect.

The Reset Address of all the lower range device's is at the highest available

address in the specific code memory. After executing this instruction, the

Program Counter will roll over to address OOOOh.

500 PlC Micro-Controller Operation and Applications - Vol. 11

Page 219: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 219/260

 

The Mid-Range of the PlC Family

The mid-range members of the PlC family that will be compared in thesenotes are as follows:

PIC12C671, PIC12C672

PIC14000,

?IC16C554, PIC16C556, PIC16C558,PIC16C61, PIC16C62, PIC16C62A, PIC16C63,

PIC16C64, PIC16C64A, PIC16C65, PIC16C65A,

PlC 16C620, PIC16C621, PIC16C622,

PIC16C70, PIC16C71, PIC16C71A, PIC16C72,

PIC17C73, PIC16C73A, PIC16C74, PIC16C74A,

PIC16F83, PIC16C84, PIC16C84A,PIC16F84,PIC16F627,PIC16F628,PIC16F873,PIC16F874,PIC16F876,PICl6F877,

PIC16C923, PIC16C924

The various features of the controllers will be compared in a table format

first Then comparisonswillbemade betweenboth the mid- and lower range

devices under the headings of:

* Code Memory size and access

* Special Function Register and RAM acoess and size* Device Pins and Ports

* Configuration bits

* Instruction Set

* SLEEP mode and Watch Dog Timer

* Power Control Register, PCON

* Special Functions, such as additional Timers, Capture/Compare/ PuIse-Width-

Modulators, Analogue-to-Digital Modules, etc.

The finerdetail of these features, and also the exact operation of the specialfunctionsshouldbe studied from the individual data sheets of the applicable

controllers before implementation.

Similarities between all of the mid-range devices are that they are all

In-Circuitseriallyprogrammable and have the same basic internal structures

and instruction sets. The commonReset and Interrupt Vector addresses forall the devices are OOOOhnd 0004h. .

Ch.13 Introduction to the Rest of/he PlC Family 501

Page 220: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 220/260

 

Comparison Between the 12Cxxx, 14000 and 16Cxxx Controller:s

502 PlCMicro-ControllerOperationandApplications Vol.11

1:: !i

1ii/o°:1Code Data PiDs

t

:El

J ]

.. 0DeviceEPROM (E) RAM

j e IS':;j

FLASH(F) EEPROMTot. I/O IN .fi.,g '" ::: A §812C508 512 E 25 8 5 1 0 1 5

12C50BA 512 E 25 8 5 1 0 1 5

12C509. lK E 41 8 5 1 0 1 5

12C509A lK E 41 8 5 1 0 1 5

12C671 IK E 128 8 5 I 4 I 4 14

12C672 2K E 128 8 5 1 4 1 4 14

14000 4K E 192 28 22 - 11 2 I I 8 2 6

16C554 512 E 80 18 13 - 3 1 12

16C554A 512 E 80 18 13 - 3 1 12

16C556A lK E 80 18 13 - 3 I 12

16C558 2KE 128 18 13 - 3 1 12

16C55BA 2KE 128 18 13 - 3 I 12

16C61 lK E 36 18 13 - 3 1 5

16C62 2KE 128 28 22 - 7 3 I I 6

16C62A 2K E 128 28 22. 7 3 1 1 Y 13

16C62B 2K E 128 28 22 - 7 3 I I 5 Y 13

2f(-

16C63 4K E 192 22 . 10 3 1 1 2 Y 13

16C63B 4K E 192 28 22 - 10 3 I I 2 Y 13

16C64 2K E 128 40 33 . 8 3 1 1 1 616C64A 2KE 128 40 33 - 8 3 1 1 I Y 13

16C65 4K E 192 40 33 - 11 3 1 1 I 2 Y 6

16C65A 4K E 192 40 33 - 11 3 1 I I 2 Y 13

16C65B 4K E 192 40 33 - 11 3 I 1 I 2 Y 13

16C66 BKE 368 28 22 . 10 3 I I 2 Y 13

16C67 8K E 368 40 33 - 11 3 1 1 1 2 Y 13

16C620 512 E 80 18 13 - 4 1 Y 2 13

16C62OA 512 E 96 18 13 - 4 I Y 2 13

16C621 lK E 80 18 13 - 4 1 Y 2 13

16C621A lK E 96 18 13 - 4 1 Y 2 13

16C622 2KE 128 18 13 - 4 1 Y 2 13

16C622A 2K E 128 18 13 - 4 1 Y 2 13

16C641 2K E 128 28 22 - 4 I Y 2 14

16C642 4K E 176 28 22 - 4 1 Y 2 14

16C661 2KE 128 40 33 - 5 1 1 Y 2 14-16C662 4K E 176 40 33 - 5 1 I Y 2 14

16C71 lK E 36 18 13 . 4 1 4 5

16C72 2KE 128 28 22 - 8 3 I I 5 Y 13

16C72A 2K E 128 28 22 - 7 3 1 I 5 Y 13

Page 221: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 221/260

 

EEPROM and FLASH Code Memory

The PlC 16F62x, PIC16F8x and PIC16F.8xx devices have EEPROM or

FLASH code memory. This memory is are Electrically Erasable and

Programmablewithoutthe normal DV light erasing cycle. The difference is

in the technology used to manufacture the code memory cells. From the

programming and user's point of view, they are the same. One TimeProgrammable (OTP) varieties of the above devices are also available. All

the above devices also contain some bytes of EEPROM user memory inaddition to the normal volatile user RAM.

All the other PlC devices that are reprogrammableuses EPROM technology.

These ceramicwindowedversions can onlybe erased by exposureto DV light

for a prescribed period. Once the software has been developed on one of

these EPROM devices, the device can be replaced with an OTP device, that

ismuch cheaper.

Ch.13 Introduction to the Rest of the PlC Family . 503

J i2i

f6g

. :ICode Data PIns

Jj § p.

:sDeviceBPROM(E)RAM §LASH(F) EEPROMot. I/OIN ;:J '"16C73 4K E 192 28 22 - 11 3 I I 2 5 Y 6

16C73A 4K E 192 28 22 - II 3 I I 2 5 Y 13

16C73B 4K E 192 28 22 - II 3 I I 2'5 Y 13

16C74 4K E 192 40 33 - 12 3 I I I 2 8 6

16C74A 4K E 192 40 33 - 12 3 I I 1 2 8 Y 13

16C74B 4K E 192 40 33 - 12 3 I I I 2 8 Y 13

.16C76 BKE 368 28 22 - 11 3 I I 2 5 Y 13

16C77 8K E 368 40 33 - 12 3 I I I 2 8 Y 13

16C710 512 E 36 18 13 . 4 I 4 Y 14

16C711 lK E 68 18 13 - 4 I 4 Y 14

16C715 2KE 128 18 13 - 4 I 4 Y 14

16C923 4K E 176 64 25 27 8 3 I I Y 12

16C924 4K E 176 64 25 27 9 3 I I 5 Y 12

16F83 512 F 36t64E 18 13 - 4 I 14

16C84 IK F 33ffi4E 18 13 . 4 I 5

16F84 IK F 68ffi4E 18 13 . 4 I 14

16F84A lK F 68ffi4E 18 13 - 4 I 14

16F627 IK F 244+128E28 22 - 10 3 I I 2 2 Y Y 13

16F628 2KF 244+128E 40 33 . 10 3 I I 2 2 Y Y 13

16F870 2K F 128ffi4E 28 22 . 11 3. I 1 5 Y Y Y 13

16F871 2KF 128ffi4E 40 33 . II 3 I I I 1 8 Y Y Y 13

16F872 2KF 128ffi4E 28 22 . 10 3 I I 2 5 Y Y Y 13

16F873 4KF 192+128E 28 22 . 13 3 I I 2 5 Y Y Y 13

16F874 2KF 192+128E 40 33 . 14 3 I 1 I 2 8 Y Y Y 1316F876 8K F 368+256E 28 22 - 13 3 I I 2 5 Y Y Y 13

16F877 BKF 368+256E 40 33 . 14 3 I I I 2 8 Y Y Y 13

Page 222: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 222/260

 

Code Memory Core Width and Size

12-Bit Core Width: (12C508, 12C509, '52, '54, '54A, '56, '57, 58A)

These devices constitute the Lower Range devices. The code memory size,the starting and ending addresses, the Program Counter width, and also the

source of the more significant bits for the GOTO, CALL and modify PCLinstructions are summarised in the table below:

* The 12-bit instruction is not wide enough to supply the full GOTO or CALL

destination addresses. Additional higher bits must be set by software in the

Status register bits 5 and 6, before these instructions are used. For the CALL

and Computed Jump instructions that modify the PCL register, the 9th PC bitwill always be cleared, and additional higher bits must be supplied by bits 5

and 6 from the STATUS Register. This implies that sub-routines and look-up

tables must be placed, or at least start on addresses with the 9th bit cleared,

e.g: OOOhto OFFh, 200h to 2FFh, 400h to 4FFh and 600h to 6FFh.

The Stack is only 2 levels deep, but wide enough to accommodate the full

Program Countervalue. Sub-routinesmay thereforebe called fromanywhere

in the program, although their placement is restricted.

The 12-coredevices can onlybe programmed in the parallel mode. Only the

8-pin 12C508 and 12C509devices, are seriallyprogrammable.

The Reset addresses of all the lower-range devices are located at the end of

the available codememorymap. After executingthis instruction,theProgramCounter will roll-over to address OOOOh.

504 PlC Micro-Controller Operation and Applications - Vol. 11

Code Devices Addresses PC *GOTO *CALL and

Size width Instruction alter PCL

384 '52 000-17Fh 9 bits 9 instruct. '0'+8 instruct.

512 '12C508, '54, '54A, '55 000-1 FFh 9 bits 9 instruct. '0'+8 instruct.

IK 12C509, '56, '57 000-3FFh 10 bits 1 sta+9 inst 1 sta+'0'+8 inst

2K '58 000-7FFh II bits 2 sta+9 inst 2 sta+'O'+8 inst

Page 223: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 223/260

 

14-Bit Core Width: (12C67x,14000,'C52x,'C6xx,'C7x,'C8x,'F8xand'C92x)

These devicesconstitutetheMediumRange devices. The codememory size,

the starting and ending addresses, the Program Counter width, and also the

source of the more significant bits for the GOTO, CALL and modify PCL

instructions are summarised in the table below:

* The 14-bitinstructionis not wide enough to supply the full GOTO or CALL

destination addresses for the 4K device. An additional higher bit must be

placed in the PCLATHRegister bit 3 by software before the instructions are

used. Sub-routines and Look-up tables can be placed anywhere in the

available code memorymap.

The Stack is 8 levels deep and wide- enough to accommodate the full

Program Counter value. Return ftom sub-routines can therefore go back to

anywhere in the program.

The 14-core devices can all be programmed serially.

The Reset and Interrupt Vector addresses of all these devices are located at

addressesOOOOhnd0004h.Afterexecutingthe lastinstructionavailablefora device, the Program Counter will roll-over to address OOOOh.

Ch.13 Introduction to the Rest of the PlC Family 505

Code Devices Addresses PC GOTO and* Modify PCL*Size widt CALL Inst. Instructions

b

512 '554, '620, '70, 'C83, OOO-IFFh 9 bits 9 instruction pclath+8 in w'F&3

lK 12C67l, '556, '621, 000-3FFh 10 10 instruction pclath+& in w

'61, '621, '71, 7lA" bits'C&4A, 'F&4,F627

2K 12C672, '55&, '62, 000- 7FFh 11 11 instruction pclath+8 in w

'62A, '64, '64A, '622, bits

'72,F62&

4K 14000, '63, '65, '65A, OOO-FFFh 12 1 pclath.3 + pclath+& in w

'73, '73A, '74, 74A, bits 11 instruct. '"

'923, '924,F&73,F&76

&k F874,F&77 0000-lFFF 13 2 pclath.4,3 + pclatch+& in w11 instruct.'"

Page 224: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 224/260

 

Special Function Registers and User RAM

The various devices will be compared in sets of increasing User RAM

available. A systemof two or four pages has been introduced to increase the

available File Register address space, without increasing the instructionaddress width beyond 7 bits. The address paging is done by the setting or

clearing of one or two bits in the STATUS Register, RPOand PRI. Special

Functioll Register addresses that are not used are not implemented, Le. they

do not exist. They cannot be used for general purpose storage registers.

Some of the Special Function Registers and User RAM addresses are

available from all pages, while some addresses will access different registers

from different pages. Specific device applications mustbe studied form thedata sheets.

24 User RAM Bytes: ('55)

25 User RAM Bytes: (I2C508, '52, '54, '54A, '56)

OOh

SFR

06h

07h (No Port C)

25 User

RAM bytesIFh

506 PlC Micro-Controller Operation and Applications - Vol. 11

OOh

SFR

07h (Port C)

08h

24 User

RAM bytesIFh

Page 225: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 225/260

 

36 User RAM Bytes: ('61, '70, '71, 'C83, 'F83, 'C84)

p o

STATUS.5: o

41 User RAM Bytes: (12C509)

FSR.5: o

Ch.13 Introduction to the Rest of thePlC Family507

n - -

OOh 80h

SFR SFR

OBh 8Bh

OCh 8Ch

36 User (Same as Page 0)

RAM bytes

2Fh AFh

Ui8.- v .........Ft'-

OOh 20h

SFR (Same as Page 0)

06h 26h

07h 27h

9 User (Not Used)

RAM bytes

OFh 2Fh

IOh 30h

16User 16User

RAM bytes RAM bytes

IFh 3Fh

Page 226: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 226/260

 

68 User RAM Bytes: ('7lA, 'F84, 'C84A)

STATUS.5: o

72/73 User RAM Bytes: ('57, '57A)

FSR <6:5>: 00 01 10 11

*The '57A device has only 18 pins and no Port C. This address is availableas an additional 1RAM byte.

508 PIC Micro-Control/er Operation and Applications - Vol. 11

- - -

OOh 80h

SFR SFR

OBh 8Bh

OCh 8Ch

68 User (Same as Page 0)

RAM bytes

4Fh CFh

- - - - ...-,...-- ...-Jiio.'w-

OOh 20h 40h 60h'

SFR (Same as Page 0) (Same as Page 0) (Same as Page 0)

07/06h (Port C*) 26h 46h 66h

08/07h 27h 47h 67h

8/9 User (Same as Page 0) (Same as Page 0) (Same as Page 0)RAM bytes

OFh 2Fh 4Fh 6Fh

IOh 30h SOh 70h

16User 16 User 16 User 16User

RAM bytes RAM bytes RAM bytes RAM bytes

IFh 3Fh SFh 7Fh

Page 227: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 227/260

 

80 User RAM Bytes: ('554, '556, '620, '621)

p o p

STATUS.5: o

128 User RAM Bytes: (12C67x, '62, '62A, '64, '64A, '72, '558, '622 )

p o p 1

STATUS.5: o

Ch.13 Introduction to the Rest of the PlC Family 509

- --

OOh SOh

SFR SFR

IFh 9Fh

20h AOh

.80 User (Not used)

RAM bytes

6Fh CFh

- - - - - - - -

OOh SOh

SFR SFR

IFh 9Fh

20h AOh

32User 32User

RAMbytes RAMbytes

3Fh BFh

40h COh.64 User (Not used)

RAM bytes

7Fh FFh

Page 228: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 228/260

 

176 User RAM Bytes: ('923, '924)

STATUS <6:5>: 00 01 10 11

192 User RAM Bytes: (14000, '63, '65, '65A, '73A, '74A, F873,F874)

STATUS.5: o

224/368 User RAM Bytes: (F627,F628/ F876,F877)

STATUS <6:5>: 00 01 10 11

510 PlC Micro-Controller Operation and Applications - Vol. 11

- _V' ...."'........... ..."'"' .l.u.I:.,",J

OOh 80h 100h 180hSFR SFR SFR SFR

IFh 9Fh 11Fh 190h

20h AOh 120h lAOh80 User 80 User (Not used) (Not used)

RAMbytes RAM bytes6Fh DFh 16Fh lDFh

.70h FOh 170h IFOh

16User (Same as Page 0) (Same as Page 0) (Same asPage 0)RAMbytes

7Fh FFh 17Fh IFFh

...."';"" v ..a",....

OOh 80h

SFR SFR

IFh 9Fh.

20h AOh

96 User 96 User

RAM bytes RAMbytes7Fh FFh

... -... ...a):.,-,... ....\1,"",k .La!:!.,,",..1

OOh 80h 100h 180hSFR SFR SFR SFR

16 bytes(876/7) 16b}tes(876/7)

IFh 9Fh 11Fh 190h

20h AOh 120h lAOh

80 User 80 User 48 bytes (627/8)RAM bytes RAM bytes 80 bytes (876/7) 80 bytes (876/7)

6Fh DFh 16Fh lDFh

70h FOh 170h IFOh

16User (Same as Page 0) (Same as Page 0) (Same as Page0)

RAM bytes7Fh FFh 17Fh IFFh

Page 229: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 229/260

 

Device Pin and Port Comparisons.

8-Pin Devices:

Devices: 12C508, 12C509, 12C671, 12C672

I Port I 5 1/0 pins 1I Inputpin.

J8-Pin Devices:

28-Pin Devices:

Note: The PIC16C5x low range devices do not have internal pull-ups on

Pori B. The 12C5OXdeviceshave pull-ups onport pins GPO,GPl and GP3.

Ch.J3 Introduction to the Rest of the PIC Family 51/

Devices: '52, '54, '54A, '56, '58A

PortA 5 pins 4 1/0 pins Ilnput pin

Port B 8 pins 8 1/0 pins

Devices: '554, '556, '558, '61, '620, '621, '622, '70, '71, '71A, 'C83, 'C84, 'C84A, 'P83,

F84,(F627,F628)

PortA 5(8) pins 5(7) 1/0 pins (I Input)

Port B 8 pins 8 1/0 pins, (USART, CCPI)

Devices: '55, '57

Port A 5 pins 4 1/0 pins Ilnput pin.

Port B 8 pins 8 1/0 pins

Port C 8 pins 8 1/0 pins

Devices: '62, '62A, '63, 72, '73, 73A, F873, F876

PortA 5 pins 5 1/0 or Analogue inputs or external Timer Clock.

Port B 8 pins 8 1/0 pins.

Port C 8 pins 8 1/0 Ext. Oscillator, CCPI, Serial and USART

Page 230: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 230/260

 

-'

512 PIC Micro-Control/er Operation and Applications - Vol. 11

-.........--- -. ---... \.-- --...---....

Devices: 14000

Port A 4 pins 4 I/O or Analogue inputs.

Port C 8 pins 8 I/O or Serial Ports

Port D. 8 pins 8 I/O or Analogue inputs, Voltage Comparatorsor Serial Ports

Outputs 2 pins A Voltage Regulator control and an external

capacitor charge 'SUM' output

-- - -. --- - .. - -

Devices: '64, '64A, '65, '65A, '74, '74A, F874, F877

Port A 5 pins 5 I/O or Analogue inputs or external TimerClock

Port B 8 pins 8 I/O pins.

Port C 8 pins 8 I/O Ext. Oscillator, CCPI, Serial and Usart.

Port D 8 pins 8 I/O or Parallel Slave.

Port E 3 pins 3 I/O or Parallel Slave Control.

". ....- -.---...... ,--..,... ....---...-.......... --,

Devices: '923, '924:

Port A 5 pins 5 I/O or Analogue inputs or ext. Timer Clock

Port B 8 pins 8 I/O pins.

Port C 8 pins 8 I/O Ext. Oscillator, CCPI, Serial Port.

Port D 8 pins 8 I/O or LCD Common/Segment Drivers.

Port E 8 pins 8 LCD Segment Drivers.

Port F8 pins 8 LCD SegmentDrivers.

Page 231: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 231/260

 

Configuration Bits

3-Bits: ('52)CP

Code Protectiono=Enable1=Disable

x FOSCl FOSCO

Oscillator Selection00 =Not used01 =Not used10=XT Oscillator

11= RCOscillator

4-Bits: ('54, '54A, '55, '56, '57, '58A)

CP I

Code Protectiono=Enable1=Disable

5-Bits: (12C508, 12C509)

WDTE I, FOSCl I FOSCO

Watch Dog Oscillator Selectiono = Disable 00 = HS Oscillator

1= Enable 01 = XT Oscillator

10= LP Oscillator

11= RC Oscillator

CP

Code

I WDTE I FOSCl I FOSCO I

Watch Dog Oscillator

MCLRE

Reset InputSelection

Enableo=Disable1=Enable

5-Bits: ('61, '71, 'C84)

CP

Code

Selection

Protection Timer Enableo = Enable 0=Disable 00 = LPOscillator1= Disable 1=Enable 01 =XTOscillator

10 = Internal RC

11 = External RC

) PWRTE I WDTE I FOSCl I FOSCO I

Power-up Watch Dog Oscillator

Protection Reset Timer Timer0= Disable 0 =Disable 0'= Disable1=Enable 1=Enable 1= Enable

00 = HS Oscillator

01 = XT Oscillator

10= LP Oscillator

11= RC Oscillator

Ch.13 Introduction to the Rest of the PlC Family 513

Page 232: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 232/260

 

6-Bits' ('62 '64 '65 '73 '74), , , ,

[2! I CPO I

CodePWRTE I

Power-up

WDTE I FOSCl

Watch Dog

I FOSCO I

OscillatorSelection

Protection

00 =Full code01 = Top 3/4

10= Top 1/211= Disabled

ResetTimer Timero =Disable 0 =Disable1=Enable 1=Enable

00 = HS Oscillator

01 = XT Oscillator

10 = LP Qscillator11 = RC Oscillator

6-Bits: (14000)

I CPC [;] CPU I cCP I PWRTE I WDTEQ FOSC I

Calibration User Code Program Power-up Watch Oscillator

Protection Protection Protection Reset Timer Dog Selectiono = Enable 0 = Enable O=Enable O=Enable O=Disable O=HSOsc.

I = Disable I = Disable I=Disable I=Disable I=Enable I=Intemal

RCOsc.

12-Bits: ('554, '556, '558, '74A, '923, '924)

Protection

00 = Full code

01 = Top 3/4

10 = Top 1/211= Disabled

Reset Timer

o=EnableI =Disable

Timero =Disable1=Enable

00 = HS Oscillator

01 = XT Oscillator

10 = LP Oscillator

11 = RC Oscillator

Note: All the upper configuration bits must co-inside with the selected code

protection to have any effect.

514 PlC Micro-Control/er Operation and Applications - Vol. 11

13 12 11 10 9 8 7 - ....

ICPl

ICPO

I

CPlI

CPOI

CPlI

CPOI

xI

...6 5 4 3 2 I 0

CPOI

PWRTEI

WDTEI

POSClI posco I

Code Power-up Watch Dog OscillatorSelection

Page 233: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 233/260

 

13-Bits: ('62A, '63, '64A, '65A, '620, '621, '622, '72, '73A, '74A)

13 12

I CPl ~... .6 5

1 BODENG;Brown-out

SelectionResetO=Disable

1=Enable

11 10 9 8 7

I CPI I CPO I x I3 210

PWRTE I WDTE I POSCI I POSCO I

Power-up Watch Dog Oscillator

I

~Code*

~,I

Protection ResetTimer00 =Full code 0 =Enable

01

=Top3/4 1

=Disable

10 = Top 1/2

Timero =Disable 00= HSOscillator1= Enable 01= XTOscillator

10 = LPOscillator

11 = Disabled 11= RCOscillator

Note: All the upper configuration bits must co-inside with the selected code

protection to have any effect. The '620 and '621 have special partial

protected code schemes -see data sheets for detail.

The Brown-Out Reset: A Brown-out is a short drop in the power supply tothe micro-controller, as opposed to a power supply Black-out, where the

power will drop to zero. The short power supply drop may not be sufficient

to trigger the Power-up Reset circuitry; and the controller may fteeze or

execute unpredictable instructions. Internal Brown-out Reset circuits will

sense a short drop in supply voltage and generate a system reset. If the

Brown-out Reset is enabled, the Power-up Reset Timer will be enabled

automatically.

Note: The Power-upReset Timer default setting (unprogrammed) for

some of the newer devices is now to be Disabled, in place of

being Enabled when PWRTE = 1, as in the older devices.

(Configuration 14bits:...)

Ch.i3 introduction to the Rest of thePiC Family 5i5

Page 234: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 234/260

 

14-Bits: ('C83, 'F83, 'C84A, 'F84)

Note: All the upper configuration bits must co-inside with the selected code

protection to have any effect.

14-Bits: ('70, '7IA)

13 12 11

Icpolcpo~6 5 4

I BODEN~Brown-out Code*

Selection

Reset

O=Disable

I=Enable

10

~I

9 8 7 .......

t CPO I epo Icpol3 2 I 0

PWR~ WDTE I FOSCI I FOSCO I

Power-up Watch Dog Oscillator

Protection Reset Timer Timero = Fullcode 0= Enable 0 =DisableI =Disable I =Disable I = Enable

00 = HS Oscillator

01 = XT Oscillator

10 = LP Oscillator11 = RC Oscillator

Note: All the upper configuration bits must co-inside with the selected code

protection to have any effect.

516 PlC Micro-Controller Operation and Applications - Vol. 11

13 12 II 10 9 8 7 . ....

Iepo

Iepo

I

epoIepo

Iepo

Iepo

I CPO

L....6 5 4. 3 2 I 0

Iepo CPO

I PWRTE IWDTE

IFOSCl

IFOSCO

I

Code Power-up Watch Dog Oscillator SelectionProtection Reset Timer Timer

0 =Fullcode 0 = Enable 0 = Disable 00=HSOscillator

I = Disable I = Disable I = Enable 0I = XT Oscillator

10= LPOscillator

II =RC Oscillator

Page 235: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 235/260

 

14-Bits: (12C671, 12C672)

13

G;12 11 10

I cpa I CPI ~8 7 .......

I CPI I cpa I MCLRE I

MCLR on Pin Enable2 1 0

F~ FOSCI Fosca I

Oscillator Selection

000 =LP Oscillator001 = XT Oscillator

010 = HS Oscillator

011 = Invalid

100 = IntRC Oscillator

101 = IntRC (Clock on OSC2)110 = ExtRC Oscillator

111= ExtRC(Clock on OSC2)

9

654 3

J CPI I cpa I PWRTE I WDTE I

Code Protect* Power-up Watch Dog00 = Full code 0 = Enable 0 = Disable

01 = 200 -7FF 1= Disable 1= Enable

10=400-7FF11 = Disabled

MCLRE

o = MCLR Disabled

1 =MCLR on Pin GP2

Notes:

For Oscillatormodes 100 and 110 the OSC2 pin is available as an I/O pin.

Code Protection scheme 10 cannot be used for the 12C671.

All the upper configuration bits must co-inside with the selected code

protection to have any effect.

The New Generation PlC's (F873, F874, F876, F877, F627, F628)

The new generations PlC has additional features, such as Low VoltageProgramming, In-circuit-debugging, separate EEDATA protection, MCLR

pin can be used as an output, and an Internal RC Oscillator selection. The

specificsettings of the ConfigurationBits is too complex to include here, andshould rather be studied from the Data Sheets of the devices.

-------------------------------

Ch.13 Introduction to the Rest of thePlC Family 5/7

Page 236: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 236/260

 

Instruction Set Comparisons and Conversions

The lower range devices have 33 instructions, while the mid-range deviceshave 35 instructions:

Lower Range Mid-Range

AdditioAalinstructions: OPTION

TRIS f *

ADDLW

SUBLW

RETFIE

RETURN

Not available: ADDLW

SUBLWRETFIE

RETURN

CLRWDT ('52)

OPTION

TRIS f

* f= 5, 6 or 7 (for TRISA, TRISB or TRISC)

Notes:

The OPTION and TRIS f instructions have the same effect as to Move the

Work Register value into the OPTION or TRISn Registers. These registers

normally reside on Page I of the mid-range devices. The lower range devices

do not have registers on Page I. Only the 12C509 device has some additional

user RAM bytes on Page 1.

The ADDL W and SUBL W instructions can be simulated by fir3t moving a

literal value into the Work register and then into a spare byte. Then the

normal ADDWF and SUBWF instructions to this spare byte will have thesame effect.

The absence of interrupts in the lower range devices makes the RETFIE

superfluous. They also do not have the RETURN instruction from a normal

sub-routine, but only the RETLW.

The PICI6C52 device does not have a Watch Dog Timer, so the CLRWDTinstruction will have no effect.

-------...--...---...-------------

518 PIC Micro-Controller Operation and Applications - Vol. II

Page 237: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 237/260

 

The SLEEP Mode and Wake-up from SLEEP Reaction

All the PlC deviceshave a power conserving SLEEP mode. When placed in

thismode, the systemclock stops, and all the operations that are systemclock

dependent, will stop. The Watch Dog Timer has its own on-chip RCoscillator. When the WDT is enabled, it can wake the system out of the

SLEEPmode. Devices with a Timer 1have pin connections for an external

crystal. ThisTimer can still operate inthe SLEEPmode and wake the system

up on a roll-over interrupt. The Analogue-to-Digital modules of the 16C7x

devicesmay also be set to run on their own internal RC oscillators. A Done

Conversion interrupt can wake the system out of the SLEEP mode.

A positive or negative edge on an external pin or a change on specific pins

may generate an interrupt and wake the system out of the SLEEP mode. Thelower range devices do not have interrupt facilities, and the system can only

be woken out of the SLEEP mode by a hardware reset or a Watch Dog Timer

time-out. Only the 12C508 and 12C509 of the low range devices have the

facility to wake the system up on a Change of Pin Level. This is not an

interrupt as such that will branch to an interrupt sub-routine, it will only wake

the system up out of the SLEEP mode.

The PlC 16C52 does not have a Watch Dog Timer, and can only be woken up

by a hardware reset.

For the lowerrange devices,the systemwill always reset back to the starting

address after a Watch Dog Timer time-out, independent whether the device

was in the SLEEP mode or not. In the mid-range devices, however, the

systemwill only reset to the starting address if a WatchDig Timer time-out

occurredwhile the systemwas in the normal Running mode. If the time-out

occurswhile the device is in the SLEEP mode, the instructions will continue

fromjust after the SLEEP instruction.

The 14000 device also has a HIBERNATE mode. It will disable even Watch

Dog Timer time-out interrupts, and can only be woken up by a hardware reset.

The HIBERNATE mode can be enabled by software instructions.

-------------

Chi3 introduction to the Rest of the PlC Family 5i9

Page 238: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 238/260

 

The Power Control Register

Some devices also have a Power Control Register, PCON. It contains

additional information on the state of the controller after a power-up or

MCLR reset, and also after an interrupt or a Watch Dog Timer time-out.Theywill showwhat source created the situation. Softwaretestsand routines

on the PCON bits and the TO and PU bits in the STATUS Register can thendecide what appropriate action should be taken.

Devices: (12C671, 12C672, '554, '556, '558, '62, '64, '64, '73, '74, '923, '924)PCON: 2 1 0

I GpaR I

Power On Flago = Power on reset occurred

1 = No power on reset occurred

Note: Once a Power-On Reset was detected, the bit must be set by software.

Devices: ('62A, '63, '64A, '65A, '620, '621, '622, '70, '71A, '72, '73A, '74A)PCON: 2 1 0

I I paR I BaR JPower On Flag Brown-Out ResetO=Poweron reset O=Brownout reset

I=No power on reset I=No Brown out rst.

Note: Once a Power-On or a Brown out reset was detected, the bits must be

set by software.

Device: (14000) PCON:

(2 I o

paR I LVD I

Power On Flag Low Voltage Detect

O=Poweron reset O=Lowvoltagedetected

I=No power on reset 1=No low voltage det.

Note: Once a Power-Onreset or a Low Voltage Condition was detected, the

bits must be set by software.

520 PIC Micro-Controller Operation andApplications - Vol.If

Page 239: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 239/260

 

Specialised Modules in Various PlC Devices

The following specialised Modules in somePlC devices will be discussed:

* TimerI

*Timer2

* The Capture Modules

* The Compare Modules

* Pulse- Width-Modulator Modules

* TheAnalogue-to-Digital Converter Module

* The Parallel Slave Port

* The Serial Ports and USART

* The Voltage Comparator Modules

* The LCD Driver Modules

* The Intemal/Extemal Temperature sensing, Voltage Regulator and current

sensingmodules of the 14000.

-----------

Ch.I3 Introduction to theRest of the PlC Family 521

Page 240: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 240/260

 

The Timer Modules

* Timer 0 for all the PICs is the same as for the PICI6F84, complete with

pre-scaler and external timerl<:ounterfacilities through a port pin.

* Timer I is a 16-bittimer/counterwith a 3-bit prescaler. It can also be driven

by an externaloscillatoron pinsRCOand RCI, evenwhile the deviceis inthe

SLEEPmode. A roll-over interrupt will wake the device up.

* Timer 2 is an 8-bit timer with 4-bit pre- and post-scalers. It can also be used

as the Baud Rate Generator for the synchronous serial port.

* Both Timer I and Timer 2 can be used in the Capture, Compare or Pulse-

Width-Modulation (or CCP) circuitry.

Timer 1

Timer I is a two-byte or 16-bitRegister. It can be set to be either a Timer or

a Counter, depending on the source. This source can be disabled by setting

or clearing a bit in the Timer I Control Register, nCON. A dedicated

prescaler feeds the counter. It can be set to dividing ratios of 1:1,1:2,1:4 or

1:8. Timer I can operate in one ofthe followingModes:

* 16-Bit Timer with an internal system cycle source.

* 16-Bit Timer with a Synchronous external crystal source through pins RCO

andRC1.

* 16-Bit Timer with an Asynchronous external crystal source when in the

SLEEP mode, through pins RCOand RC1.

* 16-Bit External Event counter through pin RCO

* As part of the Capture/Compare/Pulse- Width-Modulator circuit.

When the Timer values are read while the timer is in operation, care must be

taken in the software against a roll-over between the two read instructions.

The prescaler is cleared on any write instruction to the high or low timer

bytes.

522 PIC Micro-Control/er Operation and Applications - Vol. 11 .

Page 241: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 241/260

 

The Timer 1 Control Register, TICON

o Timer/Counter ON/OFF:

Timer Clock Source:

0= OFFI=ONo = Internal

I =Externalo = In Sync.I = Unsync.o = DisabledI = Enabled

TICKPSO Ratio

o I: II I: 2o 1:4I I :8

2 Timer Source Synchronisation:

3.

Timer External Osc. Enable:

} """ Sol"" Tl,,:"'o

Unused II

Unused

4

5

6

7

Reset Value: 00000000

Notes: When the Timer source is set to the internal machine cycle, the

TlINSYNC bit setting is don't care. When an external source is used in the

SLEEP mode, the TlINSYNC bit must be set. If Timer 1 is used as part of

the CCP circuit, the TlINSYNC bit must be cleared.

An externallow ftequency crystal can be connected to pins RCOand RC1 foraccurate timing applications, even while the system is placed in the SLEEP

mode. A 32768 Hz external crystal, with a full prescaler setting of I:8, will

generate an interrupt every 64 seconds. The IC has an internal clock

amplifier that must be enabled by setting the Tl OSCEN bit in the Tl CON

register. A typical external oscillator circuit is shown below:

--------------------Ch.13 Introduction to the Rest of thePlC Family 523

TMRION

TMRICSTIINSYNC

TlOSCEN

TICKPSO

TlCKPSI

--

PIC16C64

RCO RCII32768HzI

33 ,0, I33pF

Page 242: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 242/260

 

Timer 2

Timer 2 is an 8-bit timer with both a prescaler, a post-scaler and a Period

Register (see sketch below). The source of the timer is always the system

cycle at f(osc/4. When the timer count reaches the value stored in the PeriodRegister, the timer is reset back to OOh. This reset signal is applied to the

post-scaler, and can also be used as a baud rate generator for the serial port.The post-scaler is a typical divide by n circuit. It can be selected to a ratio

ftom 1:1,1:2,1:3,1:4,1:5, etc. throughto 1:16. The outputof the post-scaler

can be used to generate an interrupt.

+1, +2, +4, +8

The Timer 2 Circuits

o

TheTimer2 ControlRegIster,T2CONT2CKPSl

}~Sdod' !

Timer ON/OFF: 0 =OFF

1=ON

Code Ratio

0000 1:10001 1:20010 1:30011 1:40100 1:50101 1:60110 1:70111 1:8

ncKPSO

o1x

Ratio

1 : 11:41:16

2

3

4

5Postscaler Select:

Code Ratio

1000 1:91001 1:101010 1:111011 1:121100 1:131101 1:141110 1:151111 1:16

6

7 I - I Unused

Reset Value: 00000000

---------------------

524 PlC Micro-Controller Operation andApplications - Vol.II

T2CKPSO

T2CKPS1

TMR20N

TOUTPSO

TOUTPS1

TOUTPS2

TOUTPS3

Page 243: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 243/260

 

The Capture Module

The Capturemodule is triggered fromport pin RC2. Itwill capture the 16-bit

value of Timer I in a two-byteCaptureRegister. When the capture circuit is

triggered, itwill also set the appropriate interrupt flag. Timer I can either be

drivenby the internal clock or an external count (in the synchronous mode).

A prescaIer can select the edge and various division ratio's for the trigger

.input. The whole circuit can be disabled if it is not used.

CCPIIFInterropt

PinRC2

CCPRlH CCPRIL

TMRlH TMRlH +1, +2, +4, +8

Tile Capture Circuit

The CCPICON Register Settings for the Capture Mode

3 2 1 0

ICCP1M3ICCP1M2 I CCP1M1 ICCP1MOICCP1CON CaDture Prescaler

x x x x 000 0 Module OFF

x x x x o 1 0 0 Trigger on Negative

x x x x o 1 0 1 Trigger on Positive

x x x x o 1 1 0 Trigger every 4th Positive

x x x x 0 1 1 1 Trigger every 16th Positive

----------Ch.i3 introduction to the Rest of the PlC Family 525

Page 244: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 244/260

 

The Compare Module

The Comparemodulewill continuouslycompare the 16.bit value of Timer 1

to a 16.bit CompareRegister. When a match is found,the output circuits can

either make port pin RC2 High or Low, or it can be used to reset Timer 1.The CCP1IF interrupt flag will always be set when a match is found.

CCP1IFInterrupt

CCPR1H CCPR1L

Pin

RC2

TMR1H TMR1L +1, +2, +4, +8

The Compare Circuit

The CCPICON Register Settings for the Compare Mode

3 2 1 0

I CCP1M3 ICCP1M2 ICCP1M1ICCP1MOCCP1CON ComDareOutDut Circuit

-------------

526 PlC Micro-Control/er Operation and Applications - Vol. II

x x x x 0 0 0 0 Module OFF

x x x x 1 0 0 0 Set RC2-> 1

x x x x 1 0 0 1 Clear RC2-> 0

x x x x 1 0 1 0 RC2unaffected

x x x x 1 0 1 1 Reset Timer 1

Page 245: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 245/260

 

The Pulse-Width-Modulator Module

The PWM module uses Timer 2 as a time base for the period of the output

signal. At the beginning of the period, when Timer 2 is reset to zero, the

output on port pin RC2 is set to 1. The Timer 2 value (8-bits), and also two

lesser significant bits, either from the system clock or from the Timer 2

prescaler, are continuously compared with a value in the Duty Cycle SlaveBuffer and two bits from the Control Register. When a match is found, the

outputpin is cleared. Timer 2 will then complete the period before the cycle

starts again. At the beginning of the period, the Duty Cycle Slave Buffer is

loaded with the value in the Duty Cycle Master register. The Duty Cycle

Valuemustbe smaller than the Period time, else the output will stay at high.

CCPRILCCPICON.5.4CCPIX CCPIY

SET

CCPRIH

CLR lo-Bit Comparator

PinRC2 Q

fose

Pulse-Width-Modulator Circuit Diagram

The CCPICON Register Settings for the PWM Mode54321

CCP1CON: o 0 0 0 = Module OFF

- - X Y 1 1 x x = PWMMode

Ch.i3 introduction to the Rest of the PiC Family 527

Page 246: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 246/260

 

PWM Period, Duty Cycle and Resolution Calculations

~ Period ~:, ,

I

:J *-Duty Cycle

!: Resolution, ,, ,

:.. DutyCycle-..:

I

: I :.- Period:: ResolutionI

A Typical PWM Wave Form

Period Calculations:

The Period is given by the formula:

Period = ( PR2 + 1) x 4 x tosc x (Timer 2 Prescaler value)

For 10MHz crystal, toscwill be 100 nano-seconds. PR2 can be any valuebetween OOhand FFh, while the Timer 2 Prescaler value can be lx, 2x, 4x

or 8x. Iffor example,theprescaleris setto lx, andPR2=249d:

Period = (249 + 1) x 4 x lOOns x 1 = 100000 ns = 100 f.Lsec.10 kHz]

The Resolution of the period is then 400 nsec, Le. the period can be

adjusted to be 400 nsec bigger or smaller by incrementing the PR2 register.

If the Timer 2 Prescaler value is changed, the Period and the Resolution

become2x,4x or 8xbigger: .

528 PlC Micro-Controller Operation and Applications - Vol.If"

Prescaler f(osc) PR2 Period Frequency Resolution

Ix 10MHz 0 400 ns 2.5 MHz 400 nseeIx 10MHz 249 100 f.Ls 10 kHz 400 nsec

2x 10MHz 249 200 f.Ls 5kHz 800.nsec

4x 10MHz 249 400 f.Ls 2.5 kHz 1.6 f.Lsec8x 10MHz 249 800 f.LS 1.25kHz 3.2 f.Lsec

Page 247: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 247/260

 

Duty Cycle Calculations:

The Duty Cycle ON time is given by the formula:

Duty Cycle = (4 x CCPRIL + 2X + Y) x tesc x (Timer 2 Prescaler)

Where X and Y is the bit values of bits CCPIX and CCPIY in the CCP

Control register, CCPICON.

For 10MHz crystal, tescwill be 100nano-seconds. CCPRIL can be any value -

betweenOOhand FFh, while the Timer 2 Prescaler value can be Ix, 2x, 4x or

8x. If for example, X and Y are cleared, the prescaler set to Ix, and theCCPRIL value is 200d:

Duty Cycle = (4 x 200 + 0 + 0) x 100ns x I = 80 flsec

The outputwave formwill then be mGH for 80 flsec and LOW for 20 flsec,

to make up the total period of lOOflsec. The Resolution of the Duty cycle is

100nsec, Le.it can be madebigger or smaller in 100 flsec steps by changing

the X and Y values, for a 10-bit resolution. The Duty Cycle and the

Resolution will also double for every setting of the Timer 2 Prescaler:

Note that theDutyCycle resolution will not changeif the PR2 register value

is changed. The 10-bit resolution allows 1024 increments only for the full

PR2 value of255.

------------

Ch.13 Introduction to the Rest of the PlC Family 529

Prescaler C(osc) CCPRIL XY Duty Cycle Resolution

Ix 10MHz 0 0 I 100 ns 100nsec

Ix 10MHz 200 0 0 80 fls 100 nsec

2x 10MHz 200 0 0 160 fls 200 nsec

4x 10MHz 200 0 0 320 fls 400 Ilsec8x 10MHz 200 0 0 640 fls 800 flsec

Page 248: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 248/260

 

The Second Capture/Compare/Pulse-Width-Modulation Module

The second CCP module has the same operation, registers and control bit

selection as the first module, and runs exactly in parallel to first module. It

uses the CCPR2L, CCPR2H, and CCPCON2 registers instead:

* It also uses Timer 2 for the Capture section, but the trigger input pin is RCI.

The inteJJ1lptflags are CCP1IE and CCP1IF in the PIE2 and PIR2 registers.

* Timer 2 is also used for the 2nd Compare module, and pin RC1 is then the

output. This output can also start the ADCmodule in addition to the reset ofTimer1.

* Timer 2 is used for both the PWM modules.

-----------------..-..-..

Summary of Timers and CCP Modules in Devices

The following devices contain Timers 0, 1 and 2, and have One CCP Module:

.'14000, '61, '62, '62A, '64, '64A, '72, '923, '924, F627, F628.

Devices containing the Timers and TwoCCP Modules are:

'63, '73, '73A, '74, '74A, F873, F874, F876, F877.

----------------------

530 PlC Micro-Control/er Operation and Applications - Vol. II

Page 249: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 249/260

 

Analogue-to-Digital Conversion in General

An analogue-to-digital converter is in principle a type of voltmeter. It will

measurethe potential difference between two points, and return the result in a

binary format.

A normal analogue voltmeter with a linear scale and a needle, can measure and

indicate an analogue voltage on the scale as so many parts of the full range of

the meter. If the full range is for example +5 volt, the range can first be divided

into five Ivolt divisions, and then each volt divided into 10 sections. One can

then read a result ot: say 3.4 volt, on the meter. The resolution for such a meter

will be I in 50, i.e. the scale can be read' to an accuracy of up to 1/50th of the

full scale value, or 0.1 volt. If the scale division stays I in 50, but the full scale

value is 10 volt, then the same resolution will give (lOV + 50) =0.2volt.o[

I

c::2

I. I. . . I3

[ 1.....

4 5 voltI. . . . I . .. I

Needle t (3.4volt)

Scale and Needle type Analogue Voltmeter

In an Analogue-to-Digital Converter, the full scale voltage range will be

divided intoa number of equalparts. The converter will return a binary codedrepresentation of the applied voltage as a ftaction of the full scale value. The

number of bitsused will decide the number of equal divisions (the resolution),

while the full scale value will decide the magnitude of each division. Apart

trom the normalGround andAnalogue Signal Input, anADC device must also

have a Reference Voltage Input, VREF.The full scale voltage must be applied

to this input. If the digital output consists of8-bits, the full scale voltage range

will be divided into 256 equal sections, and the digital output will be OOhfor

zero volt in, and FFh for an almost full scale voltage reading.

Various methods for analogue-to-digital conversions exist, of which the

successiveapproximationmethod is still the quickest economicalmethod. This

methodwilldivide the full scale voltage into two halves first. It will compare

ifthe incomingsignal falls in the top or bottomhalf. If it is within the top half,

the MSB of the output willbe set. Then the device will divide the appropriate

halve into two quarters, and compare into which quarter the signal lies. The

next digital bit will be set or cleared. The appropriate quarter will again be

divided, and so on, and so on. It will take a definite time for the device to do

Ch.13 Introduction to the Rest of thePlC Family 531

Page 250: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 250/260

 

the conversion. This time is called the conversionspeed. To start aconversion,hedevicewillnonnallyhavesomeStartConversioncontrol.AnEnd of Conversionsignalwillbe generatedwhentheconversio'lisdone.

Nonnally the incoming analogue signal must be kept steady while a conversionis in progress, and this is done by a Sample and Hold circuit. The Sample and

Hold circuit may be supplied with signals :ITomvarious sources, but only one

signal will be converted at a time. An analogue multiplexer must be used to

select one analogue signal source at a time.

The conversionmethod used for the '14000 device is to measure the time taken

for a Linear Voltage Ramp to reach the incoming analogue voltage. This

method is more accurate, but it takes longer to do the conversion.

The ADC Module of the PIC16C7x and PIC'924 Devices

The ADC in the PIC'70, '71 and '71A devices have a 4-channel multiplexer.

The incominganalogue signalsmay be applied to one of the RAOto RA3 pins.

For the 5-channelsof the '72, '73, '73A, '924, F873 andF876, an additionalpin,

RA5, is used. The three Port E pins of the '74, '74A, F874 and F877, supply

the extra connectionsfor the 8 channels.The reference voltagecan eitherbe the

chip supply, Vdd, or a smaller reference voltage, applied to pin RA3. Thespeed of the conversion is selectable between various ADC clock sources. A

flag will be set to indicate a conversion is done. It can be used to generate a

system interrupt. For power conservation while the ADC is not in operation,

all the ADC circuits may be switched off.

Three internal file registers are associated with the ADC circuits: The

ADCONO,ADCONI and the ADRES registers. 10-Bitresolution is available

for the F873/4/6/7 devices in ADRESH and ADRESL. The Interrupt Enable(ADIE) and Interrupt flags (ADIF) associatedwith the ADCmodule for the '70,

'71 and '71A devices are located in the INTCON and the ADCON registers.

For the other devices, these flags are in the Peripheral Enable (PIEI) and

Peripheral Interrupt (PIR1) Registers.

Similar to the other interrupt sources, an interrupt will vector to address 0004h.

The interrupt flag must be cleared by the softwarewhen the interruptsub-routine is executed.

532 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 251: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 251/260

 

The ADC Control Register 0, ADCONO '

o 0= OFFI=ON

Conversion Done Interrupt Flag: 1=Done

I .. GO to Start Conversion, cleared by Hardware

when DONE.

ON/OFF Control:

2

3

4 Channel Select: 000 to III

5

6Clock Source Select:

Code

00011011

Source

fo/2fo/8fo/32InternalRC

7

Reset Value: 00000000

o

)-., >

Pins 4 to 6 are not used.

2

3

7 0" Left /1 .. Right Justified In ADRESH &:L

Reset Value: OOOOOOOO

Ch.13 Introduction to the Rest of the PlC Family 533

ADON

ADIF

GOIDN

CHSO

CHSI

CHS2

ADCSO

ADCSl

Channel Selection for the 4-, 5- and 8-channel Devices

CHS2 CHSl CHSO ADC Channel Pin

o 0 0 0 RAOo 0 1 1 RAlo 1 0 2 RA2

o 1 1 3 RA3 (4-channel)I 0 0 4' RAS (S-channel)I 0 I S REOI I 0 6 REII I I 7 RE2 (8-channel)

The ADC Control RegIster 1, ADCONI

PCFGO

PCFGI

PCF02

PCFG3

-PCF03

Page 252: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 252/260

 

ADC Port A Configurations: (4-Channel devices)

A = Analogue Input D = Digital I/O

Note: For ADC inputs, a port pin must be configured as an Input.

ADC Port A Configurations: (5/8-Channel devices)

A = Analogue Input D = Digital I/O

The ADC Result Register, ADRES

The ADRES register will contain the digital result of the last completedconversion.

Conversion Speed

The conversion speed will depend on the settings of the ADCSO and ADCS 1

bits in the ADCONO register, and also the ADC clock speed. The internal RC

oscillator runs at approximately 4 MHz. For a 4 MHz oscillator, the conversion

time will be as shown in the table on the next page:

534 PlC Micro-Controller Operation and Applications - Vol. 11

PCFGI & 0 RA3 RA2 RAI RAO Vref

o 0 A A A A Vddo 1 Vref(I) A A A VRA3

1 0 D D A A Vdd

1 0 D D D D Vdd

PCFGn RE2 REI REO RA5 RA3 RA2 RAI RAO Vref

000 A A A A A A A A Vdd001 A A A A Vref A A A RA3010 D D D 'A A A A A Vdd01 I D D D A Vref A A A RA3

100 D D D D A D A A Vdd101 D D D D Vref D A A RA3I I x D D D D D D D D -

Page 253: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 253/260

 

Note: The PlC may be placed in the SLEEP mode and woken up by a Done

.Conversion interrupt, provided the independent internal RC oscillator sourcewas selected for the ADC. Conversion speeds for other system frequencies areavailable from the data sheets.

Sample and Hold Time

The Sample and Hold circuit is controlled by the GO/DONE bit in the

ADCONOregister. The circuit will be in the Sample or Trackingmode whilethe GO/DONE bit is cleared. When it is set by the software, the circuit will

capture and hold the last analogue input voltage while the conversion is in

progress. Aminimumsample timeof I0 ~sec is specified in the data sheets for

the input voltage to stabilise.

The General ADC Operating Procedure

To make an analogue to digital conversion, the following procedure may befollowed:

I. Select the appropriate port pin configuration mode of which analogue inputs

will be used,by setting the (pCFG2,) PCFGI and PCFGOpins in the ADCONI

register.

2. Set the direction of the appropriate port pins as Inputs.

3. Apply an external VREFvoltage to RA3, if required.

4. Apply the appropriate analogue signal(s) to the port pin(s).

5. Select a suitable ADC clock source by setting the ADCSI and ADCSObits in

the ADCONOregister. (See also step 11)

Ch.I3 Introduction to the Rest of the PlC Family535

ADCSl ADCSO Source Speed(4MHz) Machine Cycles

o 0 fo/2 Too fast 5 (Minimum20 sec)o I fo/8 20 sec 20

I 0 fo/32 80 sec 80

I I RC 40 Jlsec (Between20to 60 Jlsec)

Page 254: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 254/260

 

6. Select the appropriate analogue channel by setting the (CHS2,) CHSl andCHSObits in the ADCONOregister.

7. Set the ADON bit in the ADCONO register to apply power to the ADC circuits.

8. Clear the ADC Interrupt flag in the ADCONOor PIRl registers.

9. Set the ADC Interrupt Enable and the general GIE interrupt enable bits if the

systemmust generate an interrupt after the conversion.

10. After the power to the ADC circuits and the channel have been selected for at

least 10 ~sec to allow the Sample and Hold circuits to stabilise, set theGOIDONE bit in the ADCONOregister to start the conversion.

11. To maximisethe conversionaccuracy,the systemmay be placed in the SLEEP

mode directlyafter the instructionthat set the GOIDONEbit. When the system

is in the SLEEPmode, digital switching noises will be reduced to a minimum.

The internalRC oscillatormust be selected if the system is going to be placedin the SLEEP mode.

12. Once the conversion is complete, the Interrupt Flag, ADIF, will be set to

generate an interrupt, and the GOIDONE flag will be cleared by the hardware.

The ADIF flag must be cleared by the software if another interrupt will be

required later.

13. The result of the conversion will be available in the ADRES register.

14. Another input channel may be selected. The GOIDONE bit must be set to start

the next conversion afteradelay of at least 10 ~sec for the Sample and Holdcircuits to stabilise. ---------------------The ADC Module of the PIC14000

The PIC14000 has an 8-channel Linear Voltage Ramp ADC module with a

resolution of up to 16 bits. The conversion time is considerablymore but the

accuracy makes the device ideally suited for battery monitoring and

maintenance applications.---------------------------

536 PlC Micro-Control/er Operation and Applications - Vol. 11

Page 255: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 255/260

 

The Parallel Slave Port ('64, '64A, '65, '65A, '74, '74A)

Port D can be set to be a Parallel Slave £ort to an external micro-processor or

other device. This external device can write 8 parallel bits to the port, or read

8 parallel bits ITomthe port. Port E will then be used for the ChipSelect, Writeand Readhandshaking lines. When data is written to the port, an Input Buffer

Full (ffiF) flag will be set. If data has been read ITomthe port, an Output

.Buffer Full (OBF) flag is cleared. Both events can generate an interrupt. If

external data is written to the port before it has been read internally, an Input

Buffer Overflow (mOp) bit will be set The Parallel Slave Port Mode select bit

and the buffer status bits are all located in the TRISE register.

The TRIBE RegIster

o Pin 0 Direction Control: 0= Output1= Input0= Output1=Inputo=Output1-Input

Pin 1 Direction Control:

2

3

Pin 2 Direction Control:

Unused

7- InputBufferFull:

Reset Value: 0000 -111

Parallel Slave Port Mode: 0=OFF1- Selected

InputBufferOverflow: 0=EmptyI =FulI

0= Empty1- Full

o=Empty. I-Full

4

5

6 Output Buffer Full:

---------------

Ch.13 Introduction to the Rest of the PlC Family 537

TRlSE.O

TRISE.1

TRISE.2

.

PSPMODE

mOF

OBF

mF

Page 256: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 256/260

 

The Serial Ports

Three of the pins of Port D, and one from Port A, can be used for serial datatransfer between the controller and other devices. Either 314-wire or PC

protocols can be employed. The controller can also be set to be a'slave devicewith the RA5/SS pin used as a Slave Select input.

A built-m synchronous serial access to external devices, such as a serial

memory chip, can be selected for either 3/4-wire or the 2-wire PC protocols.

External communication is done through port pins RC2 to RC5.

The various modes and operation for the serial slave registers and circuits are

too long and complex to be summarise in a few pages. Direct study from the

data sheets is recommended.

----------.------

The Serial Communication Interface Module (USART)

The serial communication interface module is another one of those multi-mode

complex sections that is too long to summarise in a few pages, and should bestudied directly from the data sheets. In principle, it has the following features:

* Asynchronous serial communication, with 8 or 9 data bits.

* An adjustable Baud Rate Generator.

* Framing and Overrun error detecting.

* Synchronous Serial mode operation as either the Master or the Slave device.

----------------------------

538 PlC Micro-Controller Operation and Applications - Vol. 11

Page 257: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 257/260

 

Voltage Comparator and Reference Modules ('620, '621, '622, F627/8)

The Voltage Comparator Module consists of two analogue voltage

comparators of which the inputs and outputs can be configured to various

combinationsby software. One of the two inputs of a comparator is normally

kept steady at a fixedreference voltage, and the other input is connected to the

changing voltage that is monitored. The two input voltage levels arecontinuouslycomparedto one another, and the output voltagewill change over

from 1 to 0, or 0 to 1when the input levels cross over one another. A change

on the outputs of anyone of the comparators can generate an interrupt. The

change-overvoltage levels for the comparators are limited between a specified

maximum andminimum value that would lie between the supply voltage and

ground. Higher or lower voltages must be moved up or brought down by

resistor potential dividers to the 5 volt supply of the board or to ground. The

comparator configurations available are ~hown in the drawing below:

RAO ~FU\3~O

RAl ~ct)

~ ~OCM<2:O> = 000

RAO~FU\3V- ClOut

RAl~

~ -V- C20ut

CM<2:O> = 100

RAO

~

U\3- + ClOut

RAl -

~ + C20ut

CM<2:O> = 011

RAO ~~ ~---O

RAl~

~ -V- C20ut.CM<2:O> = 101

Ch.13 IntroductiontotheRest ofthePlC Family

RAO

~0

FU\3 (Off)

RAl . 0~ +

cM<2:O>=111

RAO

~-' + ClOut

RAl - VRBF

~ -' + C20ut

CM<2:O>"OIO

RAO

~

+ ClOut

RAl .

~ + C20utRA4CM<2:O> = 110

RAO

~-' + ClOut

RAl .

~ + C20ut

CM<2:O> = 001

539

Page 258: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 258/260

 

The internalVoltage ReferenceModule for these devices is softwareadjustable

in 16 linear steps. A built-in ground offset can be included and the range

maximwn is selectable between: 0 volt to 2/3 VDD'or 1.25VDDto 3/4 VDD'

The reference voltage canbe used in conjunctionwiththe ComparatorModules

and can also be available as an analogue output on pin RA2.

---------------------------The LCD Direct Drive Modules ofthe PIC16C923 and '924

These two 64-pin devices (68-pin for the SOIC and PLCC packages) can drive

an LCD module directly. The mode can be selected from 1 gron,nd plane and

32 segment drives to control 32 pixels, up to 4 levels of multiplexing with

4 common planes and 29 segment drives. This can control 116 pixels. The

LCD display can also be driven while the device is in the SLEEP mode.

---------------------------The Additional Battery Monitoring Features ofthe PIC14000

The PIC14000 was design to also cater for battery monitoring and maintenance

circuits. To assist in the operation of these fimctions, the device has an internalor external Thermistor Sensing circuit, Voltage Regulator control outputs and

also a Current Sensing capability. It can, for instance be set to Wake from

SLEEP from an interrupt as soon as any external current flow is detected.

---------------------------

The High Range PlC Controllers

The PIC17C4x group consists of the PIC17C42, '42A, '43 and '44 devices.

They are the High Range members of the PlC family with internal code size

variations between 2K and 8K. The basic architecture and operation are thesame as for the other members, but there are 20 additional instructions. The

processor can alsobe run in amicro-processormodewith externaladdress,data

and control busses. The controller can operate from internal code, external

code or both. It also has a build-in programming cycle.

540 PIC Micro-Controller Operation and Applications - Vol. 11

Page 259: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 259/260

 

Once a student is familiar with the lower or medium range devices of the PlC

family, it should be relatively easy to adapt and apply this lrnowledge to the

operation of the PIC17C4x devices. The operation in the micro-processor

mode with external address and data busses is too complex to summarise in a

few pages, and will be left for a possible future course or workshop.

. Conclusion

This chapter was just an introduction to the other members of the PlC family

and their various features. It can be used to get a general idea of the operationof some of these features and assist in the choice of another controller to suit

specificneeds. It is, however highlyrecommended to study the actual detail of

the other controllerand featuresdirectly fromthe applicable data sheets beforeit is implemented.

The fmer detail of some of the specialised modules are far too complex to

include in the general overview of this chapter. Some of these modules and

familymembers may be covered in future courses and workshops.

Ch.13 Introduction to the Rest of the PlC Family 541

Page 260: A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All)

5/14/2018 A Practical Course on PIC Micro-Controller Operation and Applications - Volume II(All) - slidepdf.com

http://slidepdf.com/reader/full/a-practical-course-on-pic-micro-controller-operation-and-applications-volume-iiall 260/260

 

Notes: