Beruflich Dokumente
Kultur Dokumente
PlC Micro-Controller
Operation and Applications
Volume 11
(Based on the PIC16F84)
- ..
First Published: Aug 1995 Second Edition: Jan 1996 Third Edition: Feb 1997 Fourth Edition: Jun 2002 Fith Editiqn: Jul2002 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.
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 also some 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 applied to 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
xxvi
9.
10. 11.
Power Conservation, the Watch Dog Timer and Interrupts 297 Binary Mathematics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 319 Port Expansion and External Memory Devices. . . . . . . . . 357 PIC16C84 Micro-Controller Programming in C . . . . . . . .. 387
495
12.
. . . . . . . . . . ..
543
637
LookupTables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . ..
Table a/Contents
xxvii
Notes:
xxviii
PlC Micro-Control/er
Course Description
This course intends to be the more advanced instructional and hands-on training experience in the operation and application of the PlC microcontrollers. It follows directly on the introductory course in Volume I of this series. The range covered is trom the concepts of power conservation, the Watch Dog Timer, the SLEEP mode, interrupts, binary mathematics and . special programmingtechniques, such as parameter passing to and trom subroutines. This also included indirect addressing and the use of pointers in preparation to 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 microcontrollerswas designed to be used as a reference handbook. It also includes notes, examples and exercises based on the Assembler exercises of Volume I. The other members of the PlC family are introduced, compared and some of the special features explained and sutnmarised. The exercises and 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 System is introduced and described in the final chapter. It can, with a little more effort'trom the user, do almost everything that the Basic Board system can do.
Course Description
xxix
xxx
PlC Micro-Controller
- Vol. 11
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 HourMinute Alarm Clock.
Course Description
xxxi
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 exercise on 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 on A Cash Register. Notes: Chapter 11. (p-348 to p-356)
.
Week 7: Parallel output port expansion; parallel outputs; parallel inputs; driving an external parallel memory device. Practical exercise on Adding 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
xxxii
Week 9: Practical Test 1; preparation for individual class projects; PC 2-wire protocol and serial memories. Practical assignment on Serial Memory Access. 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 programming exercises 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; introduction to 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
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 Modulation modules. 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; the PIC14000. Notes: Chapter 13. (p-531 to p-541)
Week16:
Demonstration and Evaluation of projects.
xxxiv
PIC Micro-Controller
Notes:
Course Description
xxxv
Notes:
xxxvi
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
302
The Three Reset Sources of the PIC16F84 Processor. . . . . . . . . . . .. The Power Down or Sleep Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . ..
InterruptsandInterruptSub-Routines. . . . . . . . . . . . . . . . . . . . . . . ..
......................
300'6
"t
311
3)Z!/
. . . . . . . . . . . . .. 313
315
31-61 S"
.. . ...
... 317
3 17
297
Notes:
298
PlC Micro-Controller
- Vol. II
The various reset sources of a PlC processor are covered. A power saving SLEEP 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 behaviour of the processor when waking up 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 ----------------
299
Notes:
300
PlC Micro-Control/er
Power Conservation
A micro-controllermay often 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 batteries need to be recharged and maintained on a regular basis. One would therefore try to design a circuit that would dissipate the least amount of 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 as possible. The PlC 16F84 can work from and upper limit of 4 or 10 MHz, down to almost DC. 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 10 times that of the consumption at 4 MHz. The lowest frequency that can be used, will depend on the execution time of the program and how often a specific measurement 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 power than one running on the standard 5 volt supply. A limit may be imposed by the specific hardware 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.
301
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 a transistor that should rather be kept OFF for most of the time, and will switch ON only when it is used for a brief period. Most CMOS devices use virtually no current when they are in a static state, and only consumepower while they are switched. It may even be worth the extra initial expense to iIiclude a 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 circuits may be supplied by an unw::ed port 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 one of 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 Watch Dog Timer reset is used to regain control when a system may 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 own on-board RC oscillator. The standard overflow time ITomthis timer is approximately 18 mini-seconds. When this happens during normal execution, the system will reset and start to execute the program ITomcode address OOOOh. o prevent a reset during the normal program flow, the Watch Dog T Timer must be reset before the overflow occurs by the Clear Watch Dog Timer instruction: CLRWDT. When the system is in the SLEEP mode, 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
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 000 001 010 o 1 100 101 1 1 1 1 0 Watch Dog Timer 1: 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
0 1
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. (The prescaler is actually connected as a postscaler, but that does not make any difference to the operation of the WDT system.)
The last two reset types can either be 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 System Reset, the Program Counter will be set to OOOOh, the special function registers to their nonnal reset values. and
Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts
303
* 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:
MCLR PO-!
TOO
I
PD-! TO-!
PO! TO!
poo TO-!
PC - OOOOh(Reset)
WDT Overflow
. CLRWDT[TO!
POll!]
II bit change
- bit unaltered
304
PlC Micro-Controller
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. Examples were a 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 continuously to 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 instructions will 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, because the 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 example of the minute-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 path every 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 location in a program. The CALL must also be included every time it is 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:
305
Interrupt Sources for the PIC16F84: * A positive or a negative transition on RBO (External Interrupt) * A Roll-over from the Timer
* A Done Programming from the EEPROM data memory
* A Change of any level on pins RB4 to RB7 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 interrupt was enabled or not. These bits are also in the INTCON register, 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)
on Change Flag: 0= NO Intenupt I = Interrupt o = NO Interrupt
RBIF INTF
RB4-7 Intenupt
Flag:
I = Intenupt
Timer 0 Rollover Intenupt Flag: 0= NO Interrupt 1 = Intenupt
2 3 4 5 6 7
0= Disabled I =Enabled
0- Disabled
EEPROM
Intenupt
Boable:
Global Interrupt
306
PlC Micro-Controller
- Vol. 11
When any intel11lpt occurs and it is enabled, the processor will store the current Program Counter in the stack, and jump to the intel11lpt routine starting address at 0004h. The process and timing are the same as for a normal sub-routine call. In the intel11lpt sub-routine the software must test the intel11lpt flags of each of the possible sources, and give each activated interrupt the attention it requires. The intel11lpt flag 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 intel11lpt occurs. 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 restored before the execution returns to the original program. See the data book for examples to store and retrieve the W and gT ATUS registers, using the SW APF instruction, that does not alter the STATUS flags.
In program sections where 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 brings one to the problem of what will happen if another intel11lpt appens h while the processor is busy servicing one intel11lpt,or the same intel11lptsource gives another interrupt before the current sub-routine is done. It will require careful 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. This will prevent 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 an Interrupt 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
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 flag by software every time the specific interrupt is being serviced. If the same interrupt occurs while the interrupt routine is being executed, then the interrupt flag will be set again. The :;econd interrupt will then occur and be serviced after the RETFIE instruction has set the GIE bit. Take an,exampleof a complex timer that keeps track of 1/1OOOths f a second, o up to hours, days, months and years. The timer gives an interrupt every 1/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 instructions may take more than 1/1000ths of a second to execute, so the next interrupt from the same source may happen before the current interrupt sub-routine is finished. ID,his case, the t interrupt bit must be cleared soon after entering the interrupt sub-routine. The second interrupt may then set this bit before the end of the interrupt sub-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 time will be lost. If the set of roll-over tests in the previous example takes more than two 1/1000thsof a second, the second interrupt will 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/1000 digit by one with HOroll-overs. When the 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 while updating the rest of the digit values.
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, or on the risingedge,whenINTEDG= 1. For an
308
PIC Micro-Controller Operation and Applications - Vol. 11
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 INTCON register must be set. The INTF flag in the INTCON register must be cleared as well. A service sub-routineto test if the INTF flag was set must be placed at address 0004h. This service sub-routine must either clear the interrupt flag to allow a similar interrupt again, or the enable flag must 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, by setting the INTF flag while 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 directionInterrupt Edge 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 TOIE bits 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
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 is written to the EEPROM data memory, 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 12 milli-seconds before continuing. Another option is to test the EEIF flag continuouslyuntil it is set. That will indicate the EEPROM write 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 and EEIE flags in the INTCON register must be set, and the EEIF flag in the EECONI register must be cleared. A Similar test and service routine, such as used for the other inteJTUpt ources s must be included. The EEIF flag must also be cleared if another interrupt must be detected later. The following sequence of instructions should be executed to set a Done Writing Interrupt 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 and Applications - Vol.Il
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 latched value, the TBIF flag will be set. An interrupt trom this source will be "generatedif the GIE and RBIE bits in the INTCON register are set. Before the RBIF flag is cleared, the pin values must first be read to make the latched values the same as the port 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.
First, the priorities of the interrupts must be decided. The most important or critical interrupt must be serviced first. One must also look at the time between interrupts trom the same source, and also the shortest and the longest time the servicing of an interrupt in the sub-routine may take. Some important factors to keep in mind when composing an interrupt service sub-routine, are emphasised onthe next page:
Ch. 9. Power Conservation, the Watch Dog Timer and Interrupts
31/
* 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 i program. * If the inten-upt can happen from anywhere in the main program, the Work Register 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-upt service routine. * If the exact timing of an external inten-upt is important, the timer value must be
* All the inten-uptsused may not always be enabled during the entire execution of the main program. Some of the inten-uptsmay be disabled during some parts of the program. Then the Enable flag of an inten-upt must also be tested in the inten-upt sub-routine, before a specific inten-upt is serviced. From within the interrupt 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-uptmust be 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
".
- Vol. 11
* 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. One would in effect allow an interrupt sub-routine call from within itself. Hopefully, the second interrupt sub-routine execution will 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 continuously call the same interrupt sub-routine directly after it returns with the RETFIE instruction that clears the GIE bit.
313
* 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 can be 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 interrupts as usual. After the interrupt sub-routine, the program will continue with the second instruction after the SLEEP instruction.
PC
PC
- OOOOh(Reset)
= 0004h
(Interrupt)
Onlv if GIE = I
RETFIE Execute
j
SLEEP[TO I'POOj
I st Instruction
2nd Instruction
Wake up from 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.
314
315
To indicate that the Interval1;imer, Lp.o. the Frequency Meter is in operation, the left hand side digit can be used for the units. Six ranges, from .100msec up to 99 seconds can be included, with a seventh range as an external event counter. The ranges, display digits and unit symbols can be as follows: Range
Period
1 Ils - 999 Ils lOllS - 9.99 ms 100 Ils - 99.9 ms
Symbol, Dot & Display u m m m t t 999 9.99 99.9 999 9.9 9 9 9.9
o 1. 2 3 4 5 6
1 ms- 999ms
10 ms - 9.99 sec 100 ms - 99.9 sec
- 999counts
c c c c
The hold time must 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:
Start
Intput: Intput:
End
Measuring
Input:
Period Interval
Inverse Interval
Inverse Period
Input:
Intput:
Intput:
Input:. t
Input:
These selectionsmust be made 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 between Frequency Meter Mode or Interval Timer Mode. The PD bit in the status register allows one to toggle between the Frequency and Timer 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 instrument will be a Frequency 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 Frequency Meter again. An external Phase Lock Loop can be used to dynamically multiply a low incoming frequency to get it bigger count value for a shorter gate period.
316
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 it has 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 specific time. To drive the IC, one need 8 data lines, six address lines, and also as some control 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 the previous paragraph, the 13 port 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 addressing and address pointers to be able jo write flexible general purpose subroutines with parameter passing to and from these sub-routines. Some methods to conserve memory and re-use variable addresses will be discussed.
317
-.
Notes:
318
PlC Micro-Control/er
Page
Chapter Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
321
The SETDirective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
329
BinaryMultiplication.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
The Multiple Add Method of Multiplication
""""""""""
337
338
339
Binary Subtraction and Negative Binary Numbers. . . . . . . . . . . . . . .. 344 Subtracting 2's Complement Binary Numbers. . . . . . . . . . . . . . . . . ..
Subtract W from Register or Literal Values, SUBWF and SUBLW
346
.. 347
319
Multi-ByteComparisons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Program 15: A Cash Register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Micro-Processor Division Algorithms. . . . . . . . . . . . . . . . . . . . . . . .. 353 The Multiple Subtract Method for Division. . . . . . . . . . . . . . . . . . . ..
Conclusion.
354
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 355 -------------------
320
-------------------
321
Notes:
322
PlC Micro-C011troller
Operation
and Applications
- Vol.
11
Binary Addition To do decimal system addition by 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, 10 will be subtracted from the 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 carried over 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 one must subtract2 from 3 to leave 1, and take a carry over to the next significant
Carries:
Total:
j
0
IjOjljljO0 0
0 0 1
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.
323
Byte Addition The instructions for addition used in micro-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 two most significant bits, it will set the Carry flag of the Status register to 1. If there is no carry, the C bit will be cleared. If the size of the original two numbers can be 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 numbers were two or more 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 numbers must be made equal, filling the higher byte!;with zero's, and the answer byte size must be one byte more than the size ofthe numbers. .
The procedure or algorithm to add two 2-bytes numbers together, is the same as 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 addition must be written so that the size ofthe two initial numbers may be any value ftom the smallest, up to the biggest possible values. It must also take care of any possible carries. rtere are two instructions 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
Examples are:
;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 flag will be 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 Status Register will 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.
Say the one byte is saved in the variable NUMA (LSByte) and NUMA+ 1. The other number is saved in NUMB and NUMB+ 1, and the answer must be stored in SUM, SUM+ 1 and SUM+2. The two-byte addition algorithm will be as shown below:
Two-Byte Addition Algorithm: 1. Clear the answer bytes of any previous answers.
325
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 generate a carry. The subsequent addition of even the largest t 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 carry will 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 during assembly time and place the correct address in the instructions. 'Thenormal convention for placing multi-byte numbers in memory, is to place the least significant byte first, followed by the rest of bytes in order of ascending significance and address values. Assume the base addresses, the bytes containing the original numbers, and also the base address of the answer bytes has been defined beforehand. The conversion into assembler instructions ofthe above algorithm will generate a sub-routine shown on the next page:
326
PlC Micro-Control/er Operation and Applications. Vol. Il
;Two Byte Addition Sub-Routine (ADD.ASM) ADD CLRF SUM CLRF SUM+ I CLRF SUM+2 MOVF NUMA,w ADDWF NUMB,w MOVWF 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 the higher byte 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 the address 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
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 counter will also be needed. It will be used to initially clear all the answer bytes, and then to count out the number of bytes that must be added in a loop. Only one register, the FSR, is'available for indirect addressing. One will need at least three indirect address registers, two for the initial numbers, and one for the answer bytes. To solve the problem, the address references must 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 length and stored at any place in memory. 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
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. Global variables, on the other hand, are variables that will be used in two 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.
Variables must be defined to be between file addresses OCand 4F (68 RAM bytes available for the PlC I6F84), 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 variables even 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 beginning of each sub-routine, the local variables are then allocated to the local variable space using the SET directive to tie the name of the first local variable to LOCALl, the second to LOCAL2, etc. The same locations can then be used by redefining the new local variables with the SET directive at the beginning ofthe other modules or'sections.
Ch.lO Binary Mathematics
329
Any address may have more than one Symbol. The Symbols will be replaced by the address values during 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 EQU directive as follows:
LOCAL I LOCAL2
LOCAL3
EQU EQU
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 LOCAL I LOCAL2
OC OD OE
4D 4E 4F
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 for variables flexibleto move the global and local variables around in 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
10 11 12
NUMA
18 (e.g)
NUMB
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 the Work Register when the sub-routine is called. The multi-byte addition algorithm may be as shown on the next page:
331
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 from W. 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-over during ADD) 17. Increment the sum byte indirectly, Le. increment INDF.
332
PlC Micro-Controller Operation and Applications - Vol. II
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 sum byte 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 may be placed in a sub-sub-routine. Examples of the assembler calling routine and the two sub-routines can therefore be as shown on the next pages:
333
;F:
VALA VALB N
;C:Defined the actual numbers here ;C: for easy change while testing. Will be the answer for checking ;C:Three bytes long
; Load the initial numbers in.RAM START MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF MOVLW MOVWF low VALA NUMA lowVALAlOxl00 NUMA+I high VALAlOxlOO NUMA+2 10wVALB NUMB low VALB/Oxl00 NUMB+l high VALB/Oxl00 NUMB+2 ;Store LOW byte of A ; into RAM (C7h) ;Store MIDDLE byte of A ; into RAM (I8h) ;Store HIGH byte C'fA ; into RAM (02h) ;Store LOW byte ofB ; into RAM (EEh) ;Store MIDDLE byte ofB ; into RAM (81h) ;Store HIGH byte ofB ; into RAM (06h)
334
PlC Micro-Controller
;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-Byte Addition 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 LOCAL 1 ;F:
MULADD
MOVWF COUNT MOVF PTRS,w MOVWF FSR MOVF COUNT,w INCF COUNT,f . CLRF INDF INCF FSR,f DECFSZ COUNT,f GOTO CLRLOOP
;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.
CLRLOOP
335
- I
MOVWF COUNT ADDLOOP MOVF PTRA,w CALL AD2SUM MOVF PTRB,w CALL AD2SUM INCF PTRA,f INCF PTRB,f INCF P1'RS,f DECFSZ COUNT,f GOTO 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.
;Exit sub-routine
;Add 1 Byte to Sum byte and increment Sum+1 for Carries. ;Enter: Address pointer of byte in W. ;Local Variables: TEMPW ;Corrupt: W, FSR, C, DC, Z. Stack: 1 level. TEMP AD2SUM SET LOCAL2 MOVWF MOVF MOVWF MOVF MOVWF MOVF ADDWF INCF BTFSC INCF RETURN END
336
PlC Micro-Controller Operation and Applications - Vol. II
;F:
FSR ;Place byte pointer in FSR INDF,w ;Read byte indirectly TEMPW ;Store byte in temporary store PTRS,w ;Get sum byte pointer FSR ;Place in FSR TEMPW,w ;Recover byte from storage INDF,f ;Add and store back in sum byte FSR,f ;Point to higher sum byte STATUS,C ;Skip if no carry was generated INDF,f ;Increment higher sum byte
;Exit
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-byte number in the hexadecimal system, or a digit value in the decimal system can be isolated by the use these operators. These operators are used by the assembler program 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, or to 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 is written. To let the assembler convert and isolate the 3rd hexadecimal byte out of the decimal number D'7654321', use: D'765432I' % OxlOOOOOO
(D'765432I ' % Oxl000000) / 10000
Note again that these calculations will 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 nothing more than multiple addition. The binary equivalent for the decimalmultiplicationof the numbers: 4 x 5 = 4 + 4 + 4 + 4 + 4 = 20, or in binary: (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 is which: 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 the product.
Ch.iO Binary Mathematics
337
.
The maximum byte space required for the product of two numbers is the sum of the number of bytes of each of the two numbers, e.g: 1 byte x 1 byte = 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 initially of 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' ;=D'91' MOVWF NUMA MOVLW B'OOOIOIOO' ;=D'20' MOVWF NUMB CALL MULADD SLEEP
338
; I Byte x I Byte Multiplication Sub-routine MULADD CLRF ANSW CLRF ANSW+I MOVF NUMA,w
CycleTiming 1 2 3
;Add NUMA to answer 4 ;Skip for no carry 5 ;Add carry to high answ. 6 7[&8] . 8&9 , 10 11 12 13&14
LOOPM
ADDWF ANSW,f BTFSC STATUS,C INCF ANSW+I,f DECFSZ NUMB,f GOTO LOOPM
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 1 and 2. The resultant fonnula is: Cycles = 4 + (NUMB x 6) = 4 + (20 x 6)
= 124 cycles
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 decimal equivalent for this method is found in the way one would do the multiplicationof large decimalnwnbers on paper. Each digit of the multiplier is multiplied individually with the multiplicand and the answers added. The higher digit answersare shifted before they are added to the answer. Say one need to multiply 257 by 312, the procedure will be as shown on the next page:
339
x
TotalO +(lxl10lO1) Totall +(1x110101xlO) Total2 +(Oxl10101x100) Total 3 +(1x110101x1000) Total
--------------0000000000 110101 LSB of Multiplier x Multiplicand --------------0000110101 0001101010 (Sub-answer is shifted 1 digit left) --------------0010011111 0000000000 (Sub-answer shifted 2 digits ieft) --------------0010011111 0110101000 (Sub-answer shifted 3 digits left) --------------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
CfJ-i
NUMB+l
NUMB
RLF NUMB,f
RLF NUMB+l,f
.
The multiplicationof one digit of the multiplier can only result in one times the multiplicand or in zero. One must therefore either add the shifted multiplicand to the answer if the multiplier digit 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 every bit of the multiplier. To test the multiplier digit at the same bit position for every loop, the multiplier can be shifted RIGHT and the Carry bit tested to decide whether to add or to skip.
NUMA
~
(Tested In C)
The Sequence of Events and assembler program for a shift-and-add I-byte by I-byte multiplication problem, may therefore be as shown below:
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 Binary Mathematics
341
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.
Software Listing: I-Byte x I-Byte Shift-and-Add Multiplication ; The Calling Routine INCLUDE <\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
; General Purpose I-Byte x I-Byte Multiplication Sub-Routine Cycle count 1 SHFADD CLRF ANSW 2 CLRF ANSW+ 1 3 CLRF NUMB+ 1 4 MOVLW 8 5 MOVWF COUNT 'LOOPM 6 21 RRF NUMA,f ;Multiplier 7 22 BTFSS STATUS,C ;Skip if carry SET GOTO CLRC ; else jump over adding 8 23 9 24 MOVF NUMB,w ADDWF ANSW,f \Adtllower Multiplicand 10 25 11 26 BTFSC STATUS,C 12 27 ;Adjust for carry INCF ANSW+ l,f 13 28 MOVF NUMB+l,w ADDWF ANSW+l,f \Add higher Multiplicand 14 29 BCF STATUS,C ;Prepare for byte shift 15 30 RLF NUMB,f ;Shift bit from lower byte 16 31 RLF NUMB+l,f ; into the higher byte 17 32 18[&19] 33&34 DECFSZ COUNT,f 19&20 GOTO LOOPM RETURN [20&21] 35&36
CLRC
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
1+ 5 = 9
It is obvious that when the smaller number is subtracted ITomthe bigger one, the answerwill be positive. If the numbers are equal, the answer will 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 negative numbers 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 000000 II past the zero point, the result will be as follows:
00000011 = 3 00000010 = 2 00000001 = 1 00000000 = 0 11111111 =-1 11111110=-2 11111101 =-3 11111100=-4
(Negative, ( ( (
344
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 be converted to decimal as follows: Original Complement: 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)
-(
4)
The 2's complementformat for binary numbers must be considered a different numbering system than the normal positive binary system. The user must decide beforehand which numbering system will 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 also called 2's complement numbers. They may look the same as
the normal binary numbers, because the MSB is zero, but are treated differently.
345
The maximwn nwnber that can be represented by an 8-bit 2's complement nwnber is + 127, or 01111111, and the minimum or most negative number, is -128, or 10000000, in total, also 256 different nwnbers, including the zero.
Subtract:
24253 (Decimal)
-12432 11821
- 001010010(Bottomnwnber) 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 00 1010010) 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 cOlTectly the available bits. The numbers and the in 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:
-20 = - 00010100
10 00001010
30 =
00011110
20
00010100
= -D'lO'
346
PlC Micro-Control/er
For PlC micro-controllers that operate in byte units, there are two Byte Oriented 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
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-byte subtraction.arethe same as 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.
347
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 least significantbytes are subtracte,dand the answer stored in (or added to ) the least significant answer byte, If a borrow was generated, Le.the Carry was cleared, this borrpw must be 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 borrow will be discarded. The next two bytes are then subtracted. Any possible borrow must again be subtracted from the higher bytes. Some of these bytes may already be FF, and another 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.
348
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, 10 I0 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 carry will be set. Thenl010 must be subtracted from the sum value. This operation was done already and the answer is in the Work Register. 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 was
negative, then the carry will be cleared (C
= 0).
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.
349
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.
To add packed BCD numbers, Le. two BCD numbers per byte, the bytes should be 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 than the 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
Program 15: A Cash Register Use the Basic Board and the Keyboard and 7-Segment Display to design a Cash Register to operate as follows: * On Reset, the displaysmust be blank and only the decimal dot of the third digit from the left must be on. The device must 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 stay where 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, together with 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 closest cent. * 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 is pressed, 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 tendered amount.
351
Notes: The nwnbers entered and the total may be stored in the BCD format using one byte per digit. When two digits have been added together, the swn must be tested if it is more or equal to 10. If it is, a 10 must 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 significantdigits must be discarded to dividethe total by 100 again. -------------
-------------
352
PIC Micro-Controller
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/10ths of a unit, then 1/100ths,etc. In binary, the first digit 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 left past the decimal point (multiplied by 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 shifted right past the decimal point (divided by 2) by the total number of shifts used to make 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 Subtract method is much faster in cycle time than the Multiple Subtractmethod. It is also much more 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:
353
The Multiple Subtract Method for Division The multiple subtract method is the inverse of the Multiple Add 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 (the remainder) is smaller than the dividend. Micro-controllers operate in bytes, and the same calculations can be made, using bytes. Provision must also be made 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 1 byte long. If the dividend is three bytes long, and the divider to two bytes long, the answer may be up to three bytes long (for division by 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 Division algorithm 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
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 subtraction can be done before the remainder goes negative, can be done with the Smaller Than comparison tests between the divider and the remainder of the 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 done by rather building in scale factors, offsets, etc. in the input hardware. This should then result in values that can be used directly 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.
355
Notes:
356
Page ChapterSummary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
.Parallel Output Port Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
359
361
Expanding to more Sets of Parallel Output Data Lines. . . . . . . . . . .. 362 Parallel Input Port Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
363
A Small8 x 8-BitExternalMemoryBlo~k
Driving of an External Parallel Memory Device from the PIC16F84
366
. 366
368 369
SerialInputExpansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. SerialOutputExpansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
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. The 16-Bit Organisation and Other 3/4-Wire . . . . . . . . . . . . . .. 378
.. .. 378
(Continued )
The 85C82EEPROMSerialMemoryDevice
380
385
---------------------
358
PlC Micro-Control/er
- Vol. 11
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 industrystandard PC 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. ----------------
359
Notes:
360
PIC Micro-Control/er
- Vol. 11
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 include more output devices. Either the 74HC573 (Octal Latch) or the 74HC574 (Octal D-Flip-Flop) may be used. The essential data sheets for these two devices can be found in the CMOS Data Book from National Semiconductor or other suppliers. These 20-pin devices have 8 parallel latches or D-flip-flops, each with a separate input 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
361
~
r
Input:
Latch:
Out: ~InPut
L
datal~
Clock:
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.
Using this method, up to 5 latches, or (5 x 8) = 40 independentl()utputpins can be available. They have 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 of Port 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 way more latches can be added and controlled. The 74HC138 3-to-8 line decoder, and the 74HC154 4-to-16 line decoder will be discussed. These decoders use three or four input Select pins to make only one of the outputs low at a time. All the other pins stay high. Each device also has two or more control pins that will deselect all the output pins simultaneously. Then none will be selected.
362
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 (MSDLSD)
Enable o 0 1
Selcct (MSDLSD)
Enable o 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. When not selected or not Enabled, the output will go HIGH again. The data must be captured in the output latches on the LOW-to-HIGH transition. The D-Flip-floptype must therefore be used. The Enable inputs into the decoders can be used to deselect all the outputs. Then the Port B pins may be used for somethingelse. This Enable pin can be defined as a general WRITE Control. A total of up to 8 x 8 = 64 or 16 x 8 = 128 output 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 few machine cycles per output latch.
Ch.]]
363
A single input pin expansion device will 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 of the buffers will be implemented. The 74HC540 buffer will work equallywell, except that the buffers will invert the data levels. This can be corrected by the software.
Inputs
Inputs
Ch.ii
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, the high-impedance output controls of the latches can be used instead. They have exactly 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 externally in each latch. The data is read 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 RAM memory chip. There are 8 data pins, used for bi-directional data. The three Select Lines are the Address Lines. They will select the address of one of the eight 8-bit latches. The WRITE and the READ controlsto the decoders,have the same function as 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. When neither the WRITE or READ controls 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 or 16 address lines to select between 32K or 64K byte addresses of8 data bits each, is now the norm.
366
PIC Micro-Controller
- Vol. 11
To store or WRITE 8 data bits in parallel to the RAM, the address must be selected by 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 in the specified address until new data is writtento 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 multiple of connection lines required for the external RAM 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 connected directly 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 1 port pin spare! The Chip Select pin, CS, of the RAM can be enabled permanently.
RAO
RA!
RB7
PICl6F84 ..
RBO
RAJ RA2
~
-
cs
...D7
-~
)0 . ..
AO
:, DO A!4
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
Serial Out
Only three port pins are required to connect the chip to a PlC processor to read the data: The Shift/Load control, the Clock, and the Serial-Out pin 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 continuously available on the Serial-Outpin. It can be 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
ShiftILoaeJ:
J
. . . . A
:
Clock:
SerialOutput: H:
SI
The parallel input data will be latched-into the internal latches when the Shift/Loadcontrol is made 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 SerialIn pin before the clock signal went positive the first time, will be available on the 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 ShiWLoadand Clock 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 the processor can clock the data out of the shift register train. Another factor is how fast the input data can be processed and stored thinkin termsofthe RRF instruction and loops.
74HCl64
Clock
74HCS9S
RiDDle Clock
369
The main 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 continuously appear on the output pins, 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 data will be hidden inside the chip. It will only appear on the outputs when a Ripple Clock control is activated by making it HIGH. That will latch the shifted data into the output latches where it will be stable. A Serial-Out pin is also available trom the internal shift register. The outputs trom a system must 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. This device 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 from the 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 have been 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:
Scr.In:
'165: (pin A) Ripple Clock: '595: PrcviousData
~
x A
370
PIC Micro-Control/er
- Vol. 11
by the PlC.
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
Data InIOut
PlC Clock SIL& RCLK SI ABCDEFGH
~~lJ
CIK:
-_._-_.__._. D8!a0ut: -------IWRI D IWRI BD iwRl B . . . . . 1061 1071 D8!aln: IDO1 IDJI 1021 IDJI 1D41 IDSI I IDOl IDJI ID21 IDJI 1D41 IDSI 1061
Ch.ll Port Expansion and External Memory Devices
.
loll loll loll . . . . . .
loll 10I . . . .
I
1071
371
The Data-In and Data-Out pins can be connected through a resistor to make the 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
vcc Supply
Ground ORG Input Test (NC) pin
- Power
Organisation of the bits in the chip -Not Used, and connected to Vcc or Ground.
- the common
to the chip ground connection to the system hardware connection to select the internal
The 2K storage bits 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 Add 00 bbbbbbbb 01 b b b b b b b b 02 b b b b b b b b 03 bbbbbbbb Bits: Add 00 m ~ FED C B A 9 8 7 6 S 4 3 2 1 0 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 b b b b b b b b b b b b b b b b
. . . . . . . .
FE FP
. .. . .. . .
7E 7F
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
b-Oorl
bbbbbbbb 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 b b b b b b b b
* After that a two bit instructions code is sent to the chip. Instructions include operations such as Write, Read, Erase All, etc. These will be covered in detail. * 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 the memory 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
* 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 instruction code and the address bits. The 8-bit organisation will be done in detail first. Then the difference for a 16-bit organisation will be pointed out. The Read Instruction
Notes:
The don't care address bit before A7, shown as x, allows the same hardware 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, conflict may 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
3-Wire
Connection Diagram
Sequential Access Reading It is possible to continue reading the data nom the next address directly after a normal random access cycle. Here the Chip Select control must NOT be taken low. The next data byte train can then be clocked out immediately. It will follow directly with the Most Significant Bit first.
These two instructions do not require any address or data bits. Some of the address bits are used for additional instruction decoding. The data trains for these instructions are:
Erase/Write Enable: 1 0 0 1 1x x x x x x x (CS goesLOW) Start Inst. (Codein Addressbits) Erase/Write Disable: 1 0 0 0 0 x x x x x x x (CS goesLOW) Start Inst. (Codein Addressbits)
Each instruction only requires 12 clock cycles.
Ch.11 Port Expansion and External Memory Devices
375
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 instruction does not require data bits, but the address must be specified.
376
Address
I..Write...
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.
Start I Instl...Code in Addressbits 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 15 milli-seconds. The Write All Instruction The Write All instruction will write the data byte in the instruction train into all the bytes of the memory.
Start IInst Code also in Add Data I..Write ... Data-In: 1 00 01 x x x x x x x D7 D6 D5 D4 D3 D2 Dl DO (20 cycles) Data-Out: (HighImpedance) 0 (Busy)
1
377
Practical Assignment 5:
EEPROM 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 chip will use 1 less significantbit in the address field, and 16 bits in the data field. A summary of the instructions for the 8-bit and 16-bit organisaJions of the 93C56 (2K bits) and the 93C66 (4K bits) serial EEPROM memory chips are included in the appendix. A selection guide for other 3/4-wiw EEPROM serial memory chips is also included. It is recommended that the specified data setup and hold times be studied carefully, before a device is used. ---------------
* Normal Data codes and addresses will only be valid if the data line stays STABLE while the Clock goes HIGH and LOW again, Data may therefore only change while 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 signal is 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.
::r: a ~
~
n. Clock n - Data
PC Timing Protocol
Clock Data: BusAvailable! Startbit
:
: AddorDatabit: ,
! Stop bIt!
'
379
(A8 to Vcc or Gnd) (A9 to Vcc or Gnd) (AIO to Vcc or Gnd) System Ground
The Chip Select lines AO,Al and A2, are connected by hardware to select a specific three bit Chip Select Code that would represent lof 8 possible devices. The internal storage bits are arranged in 256 bytes of 8-bits each. The byte addresses are :lTom OOhto FFh:
Bits: 7 6 5
Add 00 01 02 03 b b b b b b b b b b b b
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
I 2
b b b b b b b b 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 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
* 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 to receive an address or data written by the master for storage. * After receiving a byte, a device must give an Acknowledge bit, a 0, until the clock 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 line can be pulled LOW by any of the devices connected in a wired-AND configuration. The Select Byte Timing Diagram:
Clock:
Master Out: I0
SlaveOut:
I I I I I
ChipCode-~ RJWiAck.:
I I I
When the Read/Write byte is 0, it will inform the slave device that it must be ready to receive the address byte. If the RJW bit is 1, the slave must transmit the data at its current address.
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 address of the device will be read.
38/
Clock:
Master Out:
SlaveOut:
8
I I
~-I I
jACk.1
AddressByte
Ack. j
* The master device must give a START bit, followed by a Select byte. The Select byte must end with a Writetofollow bit, O. On the 9th clock pulse the master must receive the Acknowledge from the device. * Then follows a byte to set the current address in the slave device. Again it must receive the Acknowledge from the device.
* Then the master must give a ST ART 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 master may also send an Acknowledgeto 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 the master knows the current address of the memory device, then it is only required 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
Slave Out:
I I I ,
iRead iAck. ~
Data Byte
~Stop
Master: St I 0 I 0 AlO A9 A8 0 r A7 A6 AS 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 Add IW IAck I< Address > lAck.
(Continued... )
Master: ..St I 0 I 0 AIOA2 Al I r r r r r r r r r Stop Slave: .. r r r r r r r r A D7 D6 DS D4 D3 D2 DI DO r R Ack I< Data >I StartI Code IChip Add I I
To read 2 bytes, the master will give an Acknowledge in place of a Stop bit in 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 receive the data. The slave must generate an Acknowledge after every byte.
The 85C82 has a two-byte write buffer. That means it can receive two write bytes before it must 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 must be released by a STOP bit after the first data byte Acknowledge ITomthe
slave.
Ch.}} Port Expansion and External Memory Devices
383
While the device is busy with the internal write cycle, the slave will not respond to give an Aclmowledgeafter a select byte. This can be med as a test to fmd out if the internal write is still busy. Only the select byte need to be sent. If the Aclmowledge is 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 1 byte is approximately 1 milli-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 write buffer will be overwritten.
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<
(Continued.. .)
Address
> lAck..
To write two bytes, the second data byte must follow directly after the Aclmowledge from the slave, in place of the Stop command. The Stop command is then given after the Aclmowledge from the slave, when the fIrst 8 data bits have been received. While the memory chip is busy with the internal write cycle, the master can address another chip 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 will not generate an Aclmowledgeand interfere with 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
- Vol. 11
385
Conclusion Most of the properties and direct applications of the PlC l6F84 have now been covered to a greater or lesser extend. One more tool program to enable the programming of the PIC16F84 in the high level computer language C is left 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 16F84 micro-controller is covered in the next chapter. ------Notes:
386
PlC Micro-Control/er
4. Identifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
5. The Use of Capital and Small Letters, Spaces and New Lines. . . . . .. 397 6. The use of Comments in a program. . . . . . . . . . . . . . . . . . . . . . . . . ..
397
8. Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9. Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
10. The Structure of a C-Program
399 399
400
403
11.DataTypes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
12. The Declaration of Variables 13. Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
406
409
. ..
412
17. The While Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 18. The Do-While Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 19. The For Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
20. Program Labels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
21. Nested Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 22. The GOTO Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 23. The Use of Pointers 24. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
25. Strings.
423 423
424
425
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 426
30. The Declaratic;m and Use of Procedures and Functions. 31. The Use of Pointers to Pass Parameters to a Function.
. . . . . . . . . .. 431 . . . . . . . . . . .. 435
388
Page
437
The #ifdef and #ifndef Directives. . . . . . . . . . . . . . . . . . . .. The #pragma Directive. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. The #includeDirective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
33. Listing of the 16C84A.h Include File. 34. Assembler Instruction Equivalents in C 35. The Use of an Interrupt Sub-Routine in C
449 450
EEI4.H...
:.. .
. ... .. 450
450 453
38. The MPLABC14.LIB and Other Libraries. . . . . . . . . . . . . . . . . . . . .. 39. Exercises, Tutorials and Examples. . . . . . . . . . . . . . . . . . . . . . . . . . ..
Exercise 1: Setting the LEDs
. . . . . . . . . . . . . . . . . . . . . . . . . . . 459
465
4(jg'f{ v' 47iP.. 47;fb 48111 485 493
2: A 10 milli-second Delay Routine. . . . . . . . . . . . . . 3: A 4-Bit Binary Counter. . . . . . . . . . . . . . . . . . . . . 4: An 8-Bit Binary Stopwatch. . . . . . . . . . . . . . . . . . . 5: An 8-Bit BCD Up/Down Counter. . . . . . . . . . . . . . 6: BCD Up/Down Counter using the Internal Timer. 7: Disco Light Chaser. . . . . . . . . . . . . . . . . . . . . . . . 8: Potting the Ducks. . . . . . . . . . . . . . . . . . . . . . . . . .
--------------------
389
Notes:
390
Chapter Summary
This chapter describes the structure and application of the MPLABC Ccompiler for the PICl6F84 micro-controller specifically. Some of the advantages and limitationsof using C in place of the Assembler language are pointed out in the introduction. The fmer detail of some functions in the Clanguage are quite complex and it may take considerable time, practice and ~ffortto become fully acquainted with. A general strategyto study and apply the 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 Development Environment, to make it available to m9re users. MPLAB contains a Text Editor, an Assembler, a C-compiler and a Simulator interface. A student can also run the DOS environment system in Windows, by using the same method 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, the pp Window can be made active, the new Hex file loaded, and be used to program the Basic Board. After programming, the Board can be tested with the 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 be used 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.
391
Notes:
392
PlC Micro-Controller
1. Introduction
By writing source programs in the C-Programming Language for PlC Microcontrollers,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 variables used by a program, or which GOTO jump instruction to place below a Bit Test and Skip if Set/Clear instruction for the correct path to be followed, will be done automatically by the compiler program. A program in C is also much more structured than an assembler program. 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 system still operates on the principle oflogic levels read from the input ports, and based on these values, certain decisians are made and specific logic levels to output ports 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 data inside 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 syntax of 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 into the program and to select the correct options for the most efficient operation.
Ch.12 PIC16F84 Micro-Controller Programming in C
393
The implementationof a C-program is similar to that of assembler programs. 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 through the 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 into the Programmer Driver to program the 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 Cprogram, 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 sections will start with a brief summary of the section, the standard format and syntax of the function, and simple examples. Then a more detailed summarywill followwith a more complex format and more advanced examples. 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 function does, to be able to use the function. As his knowledge increases, the more advanced format can be studied and 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
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 is recommendedfor a first time user to read through the notes up to section 14 on Operators,before the first example and exercise are attempted. This will supply the user with some background on the general structure and building blocks 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 the code generated.
Ch.I2 PICI6F84
Micro-Controller
Programming
in C
395
The 28 key words are included below. The six reserved words are printed in italics 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.
Key words: bits break case char const continue default do Reserved: auto double
switch main union return short signed while struct sizeo! static
There are also some Reserved words for the compiler directives, but they are normally preceded by a # marker. These directives and pre-processor statements will be covered in detail in a later section.
396
PlC Micro-Control/er
- Vol. 11
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 start with a letter, and it may containno internal spaces. The rest of the identifier may consist of any combination of alpha-numerical char&cters. It can also contain some .punctuation or 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, numbers and operators defined in a single macro name. It will be replaced by the original defined contents during compilation time. The number of spaces or new lines used in a C-program have no significance, and may be included at will. Where it will play a roll, is when it is placed in the middle of 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 new lines will count!"
397
A comment may be inserted anywhere in a program where a space may be placed, except between quotation marks. It may be a few words long, or cover several lines. A comment must start with a 1*,and end with a *1. It will inform the compiler to ignore everything after the first 1*,up to where the fIrst *1is encountered. These markers can also be used to block out some statements in a program temporary. Comments may not be nested: Le. another comment must not be placed within the comment markers. The compiler will start to interpret.the statements immediatelyafter the first end-of-commentmarker was reached. 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. The new line at the end of the line is used as the end-of-comment marker.
-the
PIC'84. Before a procedure or a function can be used, it must fIrst be declared or defmed outside and before the calling routine. The correct method and syntax will be discussed in a later section under The Declaration and Use of Procedures and Functions.
398
PIC Micro-Controller Operation and Applications - Vol. II
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 semicolon. 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.
399
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;
400
PlC Micro-Controller
type function_name(vars..);
II Declaration only. Defmition not included. II The definition must be included elsewhere
void main( ) { local variable declarations; 1st statement; etc. etc..; key_word - startinlL a_loop { II Starting brace for loop statements 1st loop statement; 2nd loop statement; } II Closing 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
Then follows the main program. It is always called 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 the
variables that will be used and are only valid in the main moduli. This
declaration 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 the program. A macro definition follows. 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 used by 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
The next function declaration does not include the defmition part. ~tual definitionis included later, after the main module. In this case, the declaration line ends in a semi-colon, in place of the opening brace. The format for the top line of the actual definition after the main module, must be similar to the declaration line used before the calling routine, but without the semi-colon. It is just placed at a different position. This option allows the user to place his main module at the beginning of the-program, -with all the fuDction and procedure defillftionsafFerwards. - 9nly ~e d~claration l~es n~~cL b~ tQ.. included before the mam routine.-The main routine follows. It also contains a basic loop structure. The loop structure will start with a key word, such as for example, the DO key word. It is followed directly by an opening brace for the loop statements. A semi-colon is NOT included. This brace and the programming statements of the loop are normally 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. No END statement is included in the program. The compiler will count the number of opening and closing braces, and ends offwhen they are equal and no more keI words are ~~c<:un.!.er~<!..
A more detailed list of data types and data type modifiers, and also the maximum value limits, are shown on the next page:
403
o to 255 o to 255
-128 to +127 (two's complement)
o to 255
oto 255
-128 to + 127 (two's complement) -128 to + 127 (two's complement)
signedint
short int (also short) long int (also long) unsigned long int signed long int near pointer (e.g: near *p) far pointer (e.g:far *p)
o to 65535 o to 65535
-32768 to +32767 (two's complement) o to 3Fh (Internal Registers and RAM) 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 this way, the maximum size of1.hedata and memory space required are known beforehand and the compiler does not have to provide sufficient space just in case the values are bigger.
404
PIC Micro-Controller
- Vol. 11
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 positive numbers 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-byte number 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 'empty bytes will be unnecessary. If it is further known that the sum will not be bigger than one byte, 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,conversions mustbe 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 operation that will result in the bigger size data. If a byte value is going to be added 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 zero high bytes, before it is added. The compiler will then generate the 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: signed int a; sighed long b;
b
= b + (long)a;
405
-.
.~
The mor.ecomplex format i~: [modifier] data_type variable_name [= init value [@ add]] [,var2,
II Initial value specified. II More 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 in memory that can change during the execution of
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 local variable is declared in the beginning of a module and can only be used in that module. If another procedure is called from within that module, that same variable cannot be used in the other module. The value muSteither betransferred 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!.er ethod m of transferring values between-m_odules to s~J~ use g~bal ~ariables. is
406
PlC Micro-Control/er Operation and Applications - Vol. Il
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 is not taken for memory management. Global variables are declared at the beginning before 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:
// Declaration
// Clears only bit 2 of flags // Sets only bit 5 of flags // C musthavebeen definedbefore.
(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 procedures are declared in the top declaration line of the function between the parenthesis. The variable declaration 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. It must start with a letter, followed by any combination of alphanumeric, allowable punctuation or undersc<:!~echaracters. The name may not contain any spaces. If more variables of the sametype required, the rest of the variable names may follow, separated by are commas. Spaces are not reguired, but can be used for clarity.
Ch.i2
PlCi6F84
Micro-Controller
Programming
in C
407
An initial value may be allocated to a variable by adding an equal sign and the value immediately after the variable. Spa~s a.!:-e J1Q!I~<I!!ir~ but can be included. The initial value will be loaded into the variable before any of the instructions of the module are executed.
".,
~~
A specific address location for the variable may be-- - -- usiug.the @ sigJ1 forced by --~--
after the variable name (and initial value), followed by a valid address. The ad_dress ~pecificationmay also be referred toas the address of another variable,. by using the & sign directly before the other variable, for example, &charvar1. -If the location ISnot specified, the compiler will select varIable-locatIOns at 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 the section 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, and therefore 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 to memory locations at will, when the program is started. At the beginning of each module, local variables must be 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
The local declaration will 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.
13. Constants
The --the -- fonnats for - declaration of constants are shown below:
const data_type identifier
= value;
const char eof= 26; const int vat = 14; const signed int scale
409
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 a statement can also be enhanced for future inspection. It will remind the user what was done in a specific statement. Take the example where the value read IToma sensor must be multiplied with a specific scale 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 CO followed lIst, 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 follows an equal sigh and then the value. Ifthere are more constants of the same type to be declared, these can follow after a comma with the value of each identifier specified. The declaration must end with a semicolon.
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; II Decimal 49 (default radix decimal) const char one = Ox31; II Hexadecimal (preceded by Ox..) const char one = 071; II Octal (preceded by the number 0) const char one = 'I'; II ASCII char 49 (in single quotes) const char string[] = "Help"; II Stringconstantin doublequotes. const char eof= 26; II End-of-file character const char newline = '\n'; II New Line escape sequence (OAh) constchar array[3]= { OxCC,Ox66,Ox33};II Stored in code EEPROM
410
PlC Micro-Controller Operation and Applications - Vol. 11
often used:
(alann) character
\a \b \f \n \r \t \v \\ \? \'
\It
Bell
Backspace character
Form feed character New Line character Carriage return character Horizontal Tab character Vertical Tab character Backslash Question mark character Single quote character Double Quote character
07h 08h OCh OAb ODh 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.
411
14. Operators
r
The format for the use of operators in a statement is: variable- n~e --
A unary operator operates on one operand (to the left or to the right). A binary operator operates on two operands (both sides) A bitwise operator operates on the corresponding bits of operands.
Summary or Operators and their Precedence: Precedence Operators highest Type unary unary iillary binary binary binary binary binary bitwise bitwise bitwise binary binary (Special) = Assignments Separator/Delimiter
()[]-t.
& (type)
I
&&
11
?: =+=-= lowest
*= /= %= &= "= 1= =
The precedence 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
Parenthesis, Brackets and Pointers: ( ) [ ] Parenthesis, (...), group together sections of an expression that must be evaluated first. They may 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 index may 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. negate value, e.g: if a = 16 then -a = -16. 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
++a
--a
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. 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.
Ch.!2 PIC!6F84
Micro-Controller
Programming
in C
4/3
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.
Relational Operators: (Lower precedence than Arithmetic Operators) 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.
!=
414
PlC Micro-Controller
Logical AND for true and/a/se results: a> b && c = = d. Logi~1 OR for true and/a/se res1!lts:a> b 11 = c
d.
--
One's complement: alii's become- O's and all O's become I's. --
Assignment Operators:
=
+=
-*=
Shortformfor x = x - 2 is x - = 2.
Short form for x = x * 2 is x *= 2.
4/5
-J
/=
is x = 2. is x = 2.
Short fonn for t= t & f is t &= f. (t and f are true or false operators.) Short fonn for t = t
1\
f is t
1\=
f.
1=
1=
f.
Conditional Expressions: ? :
.
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. The rest of the content and a more thorough study of the previous sections can be done as it is required.)
416
PlC Micro-Controller
- Vol. 11
2. if (condition) { statement_I; statement_2; statement_3; } next_statement; 3. if (condition) statement_I; else statement- 2; next_statement;
/* A nested if */ /* Associated with ifwithin braces */ /* End block /* Associated with 1st if */ */
else statement;
next_statement;
*/
(See the switcll in the next section to replace multiple else if statements.)
417
/* key word plus some expression that would result in a value. */ /* A constant_expression will always result in the same value. Note the colon, :, after the line. */
statement; /* Break out of switch */ 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: /* Can be left out */ statement; } 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 fOWld after 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
If match is found, it will 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 line will capture any value and these statements will be executed. If the default or any of the following case matches must 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. -----------------..-
Programming
in C
419
Format: wbile (condition) statement; /* A true or false condition */ /* Up to end of single statement*/ /* No semi-colon */
Use break to jump out of the loop. Use continue to jump back immediately and do the condition test again.
Example: To simulate an Idle State while the micro-controllerwaits for a timer roll-over: bits INTCON;
420
PlC Micro-Controller
Use break to jump out of the loop. Use continue to jump forward to test the condition immediately.
-----------
Programmin~
in C
421
*/
Example: int ij = I;
for (i = 0 ; i < 9 ; i++) j++; Use break to jwnp out ofthe loop. Use continue to jwnp back, increment, and do the condition test. /* declare variables i andj */
422
PlC Micro-Controller
GOTO end;
,
end:
,
Programming
in C
423
The two pointer operators are & and *. They are unary, and operate on the operand immediatelyto their.right, without a 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
*p+= 2; i = 2 * *p;
/* *p = *p + 2 /* 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
424
PlC Micro-Controller
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. The number 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...
...then the statement p = &a[O); will point the pointer to the first element of the array.
After x = *(p + 2); x will contain the value of the third element of array a[ ). --------------------------------
425
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 maximum allowed for. To indicate the end of the significant characters, a '\0' is used.
As an example, one may allow say 10 characters for the name of something,but the name is only 6 characters long. The \0 in the 7th element will 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 string with initial values, use:
char str[7] = {'W','i','I','I','e','m','\O'};
II Will place the \0 in the 7th element. II Will adjust to size 7 automatically.
26. Structures
A Structure is a user-defined~et of data that can contain different 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; data_type membem; } variable_name;
1* The user-defined data-type name *1 1* Type and name of flfSt member *1 1* Type and name of 2nd member *1
Once defmed, additional variables of the same type can be defmed as: struct structure_name variable(s);
426
PIC Micro-Controller Operation and Applications - Vol. II
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 II User data-type name is record { long date; long time; int toptemp; int bottomtemp; II User variable name is reading } 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 reading.time
= getdate(
);
= gettime();
The data is stored together in 6 bytes of memory as follows: 2 bytes for date, 2 bytes for time, 1 byte for toptemp and 1 for bottomtemp.
427
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 another method of memory economy. The fonnat of the declaration of a Union, is as follows:
union union_type_name *1 {
data_type member 1; data_type member2;
1* The user-defined
data-type name
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 data stored.
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
i
a[O] --1--hi b
1--1
a[l]
1 10 b
1
1
a[2]
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]
area2.b
= 23; = 45678;
-----------------------
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
Examples:
enum ledstate {on,off};
enum month {JAN=l,FEB,MAR,APR,MA Y,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 allocated by "= constant",the numbering will continue from 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};
Port.3 = on; II Declaration ofPortB as bits data type
--..---------------------------
430
PlC Micro-Con.troller
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
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;
- name(
);
*1
432
PlC Micro-Controller
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);
/* Defme Processor and Register names */ /* declaration before calling module */ /* Calling module */
/* No ; here.
*/
/* No return value
*/
Notes: If the whole setportb( ) procedure was placed before the main( ) module, the declaration-only statement of setportb( ) wilI not be required. The procedure setportb( ) was defmed as a void return data type, and the procedure does not need a return statement at the end.
Programming
in C
433
*/
Function Declaration Format if placed before the Calling Module data_type function_name(); /* Note the use of the ; here */ data_type functn- name(data_type variable- name,data_type var_name);
/* No passing parameters
*/
statement;
statement;
z
= function_name(x,y);
statement;
434
PlC Micro-Controller
- Vol. 11
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); main( ) { int a,b,c; a=2; b=3; c = sum(a,b); /* function declaration only */
}
int sum(int d,e) { int f; f= d + e; return f; } // return d + e; is also valid, without using f
In such a case one does not need a return value as before, 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 any difference between 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
Example: #include <16C84A.h> void sum(int *d,int *e); main( ) { inta,b,c; a=2; b=3; c = sum(&a,&b); }
436
PIC Micro-Controller Operation and Applications - Vol. 11
/* Calling module */
/* Definition of function */
32. Pre-Processor
Directives
Pre-processordirectivesdo not generate any code. They are used to instruct the compilerhow to interpret the program. These directives follow after a # sign, and are normallyplaced at the beginning of the program against the left margin. 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
Ch.12 PICI6F84
Micro-Controller
Programming
in C
437
For more than one assembler instruction,the first instructioncan follow directly below 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); #asm MOVLW OF5 MOVWF temp TOP DECFSZ temp,f GOTO TOP
II Single instruction. Note the space.
II Default radix is hex. II temp may be a C-variable II Label against the margin II TIemonics at least one space away from margin
#endasm
Note: These directives will allow one to re-use some existing assembler modules by including them between the assembler start and end directives. One must be careful with variable defmitions to fixed addresses, that may be used in existing assembler modules. They may interfere with the compiler's allocation of variables and overwrite some C variable values.
438
PlC Micro-Control/er
- Vol. 11
The NAME 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 is required, 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
Macros with variables can also be created by the #defme directive. It is done by placing the variable symbols in parenthesis directly behind the name, followed by an expression where these variables are used: #defme MAX(A,B) A(B)?(A):(B))
A statement
When the macro MAX(a,b) is used, it will return the bigger value of a or b.
---------------------
Programming
in C
439
#else
another set of source code or #error "Error message"
#endif
#defme ELEMENTSIZE j
#if MAX- COUNT * ELEMENT- SIZE> 256 #error "Data size too big!" #else #defme DATA_SIZE MAX_COUNT * ELEMENT_SI~ #endif
II Will stop compiler & return message
440
PlC Micro-Controller
#else
other source code
#endif
Only one of the pragma options can be of some general use. It is the
Suppress/Allowthe listingfrom here on. It can be used to prevent, for example, the contents oflong include files to appear in the listing as well. The standard header and library files have been modified sightly to suppress the listing of all information, except the actual code or programming statements in the listing files. 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" ;" II Allow listing from here on.
Programming
in C
441
"delay.h"
- OxlO
*1
#define 16C84A H
11 Hardware Defmition ----------------------------------------------#pragma processor PlC 16C84A;
-Ox05] @ Ox05;
442
// 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
---------------------------------------@ OxOO; @ OxO 1; @ Ox02; @ Ox03; @ Ox04; @ Ox05; @ Ox06; @ Ox08;. @ Ox09; @ OxOA; @ OxOB;
#pragma portrw INDF #pragma portrw TMRO #pragma portrw PCL #pragrnaportrw STATUS #pragma portrw FSR #pragma portrw PORTA #pragma portrw PORTB #pragma portrw EEDATA #pragma portrw EEADR #pragma portrw PCLATH #pragma portrw INTCON #pragma portrw OPTION #pragma portrw TRISA #pragma portrw TRISB #pragma portrw EECONl #pragma portrw EECON2 registerw WREG;
// STATUS Bits
-------------------------------------------------------
Micro-Controller
Programming
in C
443
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 TO lE 5 #defme EEIE 6 7 #deftne GlE
// 0 PTI 0 N B its
------------------------------------------------------0 1 2 3 4 5 6 7 7
#defme PSO #defme PS 1 #defme PS2 #defme PSA #defme TOSE #defme TOCS #defme INTEDG #deftne NOT RBPU #defme RBPU
EECON1 Bits ------------------------------------------------------#detine RD 0 #defme WR 1 #defme WREN 2 #defme WRERR 3 #defme EEIF 4
//
444
PlC Micro-Controller
C-Syntax
Operation
CLRWDT(); Clear Watch Dog Timer NOP( ); No Operation SLEEP( ); Go into SLEEP mode SWAPF( f); Swapnibblesof Registerto
445
II if any
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.
446
PIC Micro-Control/er
There are two general generic function libraries, CMATH.H and CTYPE.H, and five 14-bit core include files: MATH.H, DELAY14.H, EE14.H, AD7l.H or AD74.H and SER14.H. The AD7x.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. They will 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.
447
Ch.I2 PlCI6F84
Micro-Controller
Programming
in C
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 an ASCII 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 if parameter is a printable character; otherwise, returns a logical FALSE. A printable character is defined as a value between0x20 and Ox7E. 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
isxdigit( parameter) Returns a logical TRUE if parameter is a hexadecimal digit; otherwise, returns a logical FALSE. tolower( parameter) Returns the lowercase version of parameter. Ifparameter is not a letter, . it is returned unchanged. toupper( parameter) Returns the uppercase version of parameter. Ifparameter is not a letter, it is returned unchanged.
MATH.H
This file must be included if multiplication, division, or modulus operations are used.
void __MUL16xI6(void); Internal library routine for performing 16 by 16-bit multiplication. char __MUL8x8(void); Internal library routine 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);
.
449
DELA Y14.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.
450
PlC Micro-Controller
Notes:
Programming
in C
451
Notes:
452
PlC Micro-Controller
Setting up the DOS Environment The minimum specification to run tlie MPLABC compiler in a DOS environmentis 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 DELAY 14.H EE14.H MPLABC14.LIB DELAY14.LIB EE14.LIB
11Useful Optional files
II ASCII format text editor (ver. 2.0) II Compiler Program (ver. 1.1) II Overlay file for MPLABC II Simulator to test the logic (ver. 4.0) II Device Programmer Driver (ver. 5.0) II Include header files
II Library files
II Batch.file to load files and run the tools II Command Line '84 Programmer Driver II Command Line '84 Program Verifier II Command Line '84 Device Reader II Command Line '84 Device Eraser
Programming in C
453
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 instructionsin DOS, the system path must 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 path setting 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 input parameter when the batch file is run. The batch file will 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.COM may be left in the main DOS directory. It requires a help file in the same or default directory: echo off ifEMPTYTEST%I==EMPTYTEST :START cls echo PROJECT Name: %1 echo. echo Project Files: dir %1.* /b /p echo. echo Select Tool Program to run:
goto HELP
echo.
echo echo echo echo echo echo echo. T C L S P E
Text Editor for source file C-Compliler View Listing File Simulator Progranuner Exit
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 parameter echo. echo Format: [d:][path]IDE [d:][path]proLname (No extension) echo. echo Example:" C:\PIC> c:\pic\ide c:\pic\p3\bcd " echo. :EXIT
Programming
in C
455
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 inspecting errors in the listing file, and correcting them in the source file. 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 is included at the end of Volume I, and also in the appendix to Chapter 14 of Volume II. 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 for Assembler languageprograms in VolumeI of these notes. They can be programmed and tested on the PIC84 Basic Board. -----------------------------------
The MPLAB IDE Environment It will be assumed that the MPLAB IDE system,and also the MPLABC.EXE program for windows, have been installed and all the header and library files are available. Before MPLAB is run, Windows Explorer can be 'used to open separate sub-folders for each exercise. It can be done by selectingthe MPLAB folder, and using the File, New, and Folder options. The new folders can then, 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 times refuses 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 new project is created. By clicking on the Options selection on the main menu bar, a pull down menu will appear. Here the Development Mode must be selected. The diamond next 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
- Vol. 1I
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 the main menu bar, the Install language tool must 'be selected. The Language must be MicroChip, the Tool name, MPLABC vl.IO, and the Executable, MPLABC.EXE. Still under the Project option, the New Project must be 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 is pressed, the Edit Project window will appear. It the window does 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 Properties box, 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 edit window will appear. This is where the source program will be written in C. The source program, 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.
457
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 fIrst exercise can now be attempted. ------------------------------Notes:
458
PlC Micro-Controller
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
= 0; = 0;
Programming
in C
459
The first two instructions will set the ports as outputs. It is not required to select Page 1 first. The compiler will select the page automaticallybefore these registers are accessed. The required data is then placed on the ports. It is specified directly in the equation 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 the device is in the SLEEP mode.
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 then be 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 left margin. The limited display 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 the text 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 saving the file, the path and name are 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 '
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 .were any errors or warnings. If there were, the listing file must 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 is pressed. The.C extension and output Hex file type, INHX8M, are added by the batch file automatically. The generated listing file can then be loaded by pressing the L-key, to view any errors. One may also be 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 tests the 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 and generated assembler instructions will be 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 codes were generated for each C statement. Labels are not normally used in C-programs, so the C statementsmay be used by the user to trace where he is in the original C-program. The next assembler instruction to be executed, will be highlighted.
The !DE.BAT file will specify the path and project name as an input parameter to the PS 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.
461
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 programmed before, it can be set in the programmer, and programmed into the Basic 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 menu must be 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 file will be compiled and a report window will show if 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
Simulation on MPLAB-SIM To monitor the execution ofthe 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 and port 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-programwindow will be 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 program PP.EXE can be created in Windows Explorer. The PP.EXE program in any folder must be selected with a single click. Through the File menu and 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 (see Windows Help). The PP program 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 or Config.sys programs on startup of the PC. From withinthe PP.EXE program, the hex file can be loaded and programmed into the 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. ------------------------------........-------
463
Notes:
464
PIC Micro-Controller
Vol. 11
A Simulated 10 milli-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 of milli-seconds, specified in the parenthesis of 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. The function is declared in the DELA Y14.H header file, and exists in the DELAY14.Lm file. The compiler will load the existing code from these files automatically. All that is required is the directive #include <DELA Y14.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 statement are 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 C
465
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:. It will be used to defme a breakpoint in the simulator at this code address. The time taken to.execute the delay routine will be tested on the Simulator.
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 fIrst assembler instructionafter the 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 addresses at the left margin, 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 menu selections. 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 the Help 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
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 down to show the Speed Bar in the Infonnation window. The Left and 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 new project can be called delay.pjt and placed in another folder, say C2. Follow the same procedure to specify the environment settings and Project files as before. 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 selectingthe Debug and Break Settings from the 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 the list. A break point can also be selected (or disabled) by placing the cursor on the line and clicking the right button. On the small menu, break point must be selected. The Stopwatch window must 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 Fast mode of simulation, called the quiet mode can be selected through the Debug, Run and Run menu options. This mode can also be selected by clicking the Green Traffic Robot icon, or by pressing the F9 key. The colour of the bottom line of the screen will turn yellow when the program is running. After about 20 seconds, the execution will 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 executingeach instruction. This mode can be selected through the Debug, Run and Animate menu options, or pressing the Cntrl+F9 keys. The 10 milliseconds will take approximately 7Y2 minutes to be simulated. Notes:
Ch.12 PlC16F84 Micro-Controller Programming in C
467
Notes:
468
PlC Micro-Con/roller
Program Example 1*Exercise 3 CNT4.C A 1 second 4-Bit Binary Counter #include <16C84A.h> #include <DELAY14.h> void main( ) { int i; #asm(Cnt SET i ;F:); II Define variable symbol for the PS Simulator *1
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:); II Define 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 the block will be executed at least once before the WHILE condition is tested.
Ch.I2 PlCI6F84 Micro-Controller Programming in G
469
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 specification must 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 in the loop for timing tests on.the simulator. Initially, the FOR loop count can be 2, and the delay function can be 1 milli-seconds, a total of2 milli-secondsper loop. To simulate a delay takes considerably longer than the real time. With these reduced values, the logic of the operation can be tested within reasonable time. The 1 second delay of the final program will take approximately2 minutesin the Quiet mode, and 5 minutes in the Visual mode for the PS.EXE program to simulate. For MPLAB-SIM, it would take approximately 33 minutes in the quiet mode and 12Yz hours in the Animate mode to simulate 1 second real time!
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 system variables, 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 contents of this variable can be displayed by opening a User RAM 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 symbol name will automaticallybe loaded when the F: marker was included as the first characters in the comment line of the assembler instruction. The window can then be placed in a corner, out of the way, not to interfere with 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
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 delay procedure 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, without spendinghours stepping though the 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, in the 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 the i 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 selected and Added to the Watch window.
Programming
in C
471
The Delay_Ms- 4MHz will still take a long time to complete. One may consider 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
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()'s PORTA++; if (PORTA > 15) { PORTA = 0; PORTB++; } if(pORTB.STOP == 0) while(pORTB.START = 1); = }
Programming
in C
473
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 pushbuttons and the Port B internal pull-up resistors are enabled on the OPTION register. The continuous loop contains the delay, the increment,and the 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 program will 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.
The editing of a Pin Name Line for Port B can be done through the Options window 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 own defmition line 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, together with the related Port B pins and function keys, are shown below: B>:lstartl
RB7 F1 RB6 F2
- I - IStop - I - I - I - I Unfo I
RBS F3 RB4 F4 RB3 FS RB2 F6 RB1 F7
line)
474
PIC Micro-Controller
- Vol. II
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 pin names will be shown in normal colours. Port A names have 10 characters for each pin name.
.old one.
The <Enter> key will store the new line, and the <Escape> key will keep the
When the simulator runs in one of the fast modes, the Port B line will 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 the backgroundcolour. 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 also the 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 recompiled, 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. Twelve buttons are available. They must be defined to place specific logic levels on specific pins, by placing the cursor on a button, and pressing the Right-hand mouse button. From the sub-menu the Assign Pin option can be selected. A list of the available pins will appear, and the appropriate pin can be selected by a double click.
Ch.J2 PICJ6F84 Micro-Con/roller Programming in C
475
The first button can be used for RB? and the second for RB4. 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 executed before the action is recorded. The reset value for Port B is OOh,and must be set to B'lOOlOOOO' before the pin test instructions are done the fIrst time. The del!iymust be reduced to a smaller value, say 1 milli-second, or replaced by a few NOP( ) instructions. Then the program can run in the Animate mode. The Port A increment, and also the action ofthe push buttons can be monitored. 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 through and 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 100 milli-sfconds and the program can be tested on the Basic Board. -----------Notes:
476
PlC Micro-Controller
*1
} } /I Continued....
477
void dec( ) a--', { if (a < 0) { a=9; b--', if (b < 0) b = 9; } } void idle() II Use 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 control button 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
- Vol. II
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 second loop will be executed while the button is released. The third loop will be executed while the button is pressed and kept down the second time. Only after 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 Simulationand testing 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. ---------------------------------
479
Notes:
480
PlC Micro-Control/er
.Recommended Reading: Passing of Parameters to Procedures (30, p-431). Program Example 1*Exercise 6 BCDT.C 8-Bit BCD Up/Down Counter (Timer) #include <16C84A.h>
const char RUN = 7;
*1
constcharDIR= 4;
II.Direction control
;//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 #am(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:);
TRISA = 0; TRISB = OxFO; II High nibble as Inputs II Pull-ups, Prescaler: 256 OPTION = Ox07; while(1) { delay(195); 1150000 + 256 = 195 delay(195); 112x 50000 Ils = 0.1 sec if (PORTB.DIR = = 0) updn '"'= 1; II XOR 01
Ch.I2 PlCI6F84 Micro-Controller Programming in C
481
} } 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:); //Symbol name for local variable in delay() TMRO = 256 - d;
INTCON.TOIF = 0; while (INTCON.TOIF = = 0);
}
Discussion
Here a function is declared and a parameter passed by the calling routine. It is the same as for the Delay_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
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 divide by value of2, (OPTION = OxO and the parameter for the delay 1), calls 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.
--------
483
Notes:
484
PlC Micro-Controller
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 speed must be stored in EEPROM to retain these values when power is switched off. When the power is restored, the system 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:
Recommended Reading: Read the sections on Constants (Section 13, p-409) on Arrays (Section 24, p-425), on Header files (Section 37, p-447).
Programming
in C
485
#incIude <16C84A.h> #includ~ <ee14.h> #incIude <math.h> #incIude <delay14.h> const char eespeed = Ox3E; // EEPROM Address for Speed const char eeset = Ox3F; // EERPOM Address for Set #asm(ESpeed SET eespeed ;E:); #asm(ESet SET eeset ;E:); const char FAST = 7; const char SLOW = 6; const char UP = 5; const char DOWN = 4;
;/lPinsB:B>:1 Run I
// Buttonon RB7
// // // do. RB6 do. RB5 do. RB4
- I -IDownI -
I- I- I- I
unsigned int speed; unsigned int set; unsigned int cnt; // Ring counter for sequence unsigned int disp; 11Store for lookup value #asm(Speed SET speed ;F: ); #asm(Set SET set ;F: ); #asm(Cnt SET cnt ;F: ); #asm(Disp SET disp ;F: ); const char a[32] = { // Lookup Table Ox81,Ox42,0x24,Ox18,0x24,Ox42,Ox81,OxOO, Ox81,OxC3,OxE7,OxFF,OxE7,OxC3,Ox81,OxOO, OxC3,Ox66,Ox3C,Oxl 8,Ox3C,Ox66,OxC3,Ox81, OxCC,Ox66,Ox33,Ox99 ,OxCC,Ox66,Ox33,Ox99};
void delay(unsigned int d);
486
PlC Micro-Controller
void main( ) { TRISA = 0; // Initial Setup 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);
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 in C
487
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); II Use Delay_lOxUs- 4MHz(33) or smaller } II for the Simulator. } void loadee( ) II Configuration Byte and EEDATA { #pragrna memory ROM [Ox0140]@ 0x2000; #asm ORG 0x2007 IIConfiguration Byte DW Ox3FFI ORG 0x213E DW 5 DW 0 #endasm #pragrna memory ROM [MA{CROM -loadee) @ loadee; }
488
PIC Micro-Controller
- Vol. II
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 a constant value or a calculation. The index numbers of the an-ayrange ftom 0 to 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 CUITent number, set, varies between 0 and 3. The element calculation can set 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 look up table an-ayand displayed on 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.)
.
Write_EEProm(EE_address,data);
To read ftom the EEPROM, use function: x = Read_EEProm(EE_address); To write to the EEPROM, use procedure:
In the real situation,the minimum delay of 100 milli-seconds is longer than the 10 milli-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-SIM writes to the EEPROM data immediatelyand does not simulate the 10 milli-secondswaiting time to complete the programming of the EEPROM data. It does however require the 55, AA writing sequence to EECON2, before a write would take place. PS.EXE simulates both, and a eITor message will be given when a user attemps to access the EEPROM while a write cycle is in progress. The EETimer can be cleared to reduce the waiting time.
489
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 be includeq 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 compiled and code will be generated. The #pragma memory s.tatementsare included to set the code address to the required program memory values, and to reset it again for 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 Watch Dog Timer, the WDT will be enabled automatically in the PS.EXE simulator.
Simulation and Testing in the DOS Environment The global and local variable symbols, and also the EEPROM byte symbolswill be loaded into the Simulator a,utomatically,provided they were defined by the assembler SET directives with the special symbol allocation markers. 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 PS Simulator. The exact format and use of the various automatic information transfer markers and lines are explained in detail. ----------------------------------
490
PlC Micro-Controller
Simulation on MPLAB To view the 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 toggled to 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 adding the ports to the Watch window. 1'his can be done by clicking the cursor on the left top corner of the Watch window to enable a sub-menu. On this submenu, the Add Watch option must be selected, PORT A and PORTB Added, and through the Properties option selected to be displayed as 8-bit binary numbers.
Programming
in C
491
Notes:
492
PlC Micro-Control/er
- Vol. 11
493
Notes:
494
PlC Micro-Con'troller
Page
Chapter Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
497
The Lower RangeMembers of the PlC Family. . . . . . . . . . . . . . . . .. 499 The Mid-Range of the PlC Family. . . . . . . . . . . . . . . . . . . . . . . . . . ..
501
Code Memory Core Width and Size. . . . . . . . . . . . . . . . . . . . . . . . . .. Special Function Registers and User RAM
Device Pin and Port Comparisons. Configuration Bits. . . . . . . . . . . . . . . . . . . . . . . . . . ..
504
506
511 513
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
518
519
520 521
522
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
. . . . . . . . . . . . . . . . ..
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
522
495
526
527
.. . . . . . . . . . . . . . . . . . . . . . . . ..
536
537
538
The Serial Communication Interface Module (USART) Voltage Comparator and Reference Modules. . . . . . . . . . . . . . . . . ..
538
539
The LCD Direct Drive Modules of the PICI6C923 and '924 The Additional Battery Monitoring Features of the PIC14000 The High Range PlC Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
540 540
540
541
---------------------
496
PlC Micro-Controller
Vol. 11
Some devices contain quite a sophisticated built-in Serial Port and USART. An the various modes for the Serial Ports, the settings, registers and the operation are too long and complex to summarise in a few pages. Only a brief overview is included. It is left to the student for self study directly trom the appropriate data sheets. Finally,the higher range of PlC 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
497
Notes:
498
PlC Micro-Controller
- Vol. 11
The Lower Range Members of the PlC Family The lower range members 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 of micro-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 have a 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 device and general Input/Output pins of the lower range vary from 8-pins with 6 I/O pins, 18-pins with 12 I/O pins, and 28-pins with 19 generalpurpose I/O pins. The 28-pin devices have and additional Port C. Apart from the 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 Programmable and EPROM based code memory chips. Smaller differences in the software and hardware are summarised as follows: Hardware differences 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. The Page 1 registers, such as the OPTION and TRISn registers are accessed by the OPTION and TRIS instructions. They have the same effect as the MOVWF OPT and MOVWF 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
The program memory core size is only 12 bits wide. Therefore. the CALL and GOTO instructions cannot 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 influence where sub-routines mayor may not be located in a 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 complete Program'Counter value. This means that although there 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 normal RETURN 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 ADDWF and 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
- Vol. 11
The Mid-Range of the PlC Family The mid-range members of the PlC family that will be compared in these notes 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 comparisonswill be made between both 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- WidthModulators, Analogue-to-Digital Modules, etc.
The finer detail of these features, and also the exact operation of the special functions should be 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 common Reset and Interrupt Vector addresses for all the devices are OOOOh 0004h. and .
501
Data
PiDs
1::
FLASH(F) 12C508 512 E 12C50BA 512 E 12C509. lK E 12C509A lK E 12C671 IK E 2K E 12C672 14000 4K E 16C554 512 E 16C554A 512 E 16C556A lK E
!
j '"
1ii/o
:1
5 5 5 5 5 5
22
13 13 13 13 13 22 22. 22
22 22
. . . .
1 1 1 1 I 1
0 0 0 0 4 4 11 3 3
1 1 1 1 I 1 2 I 1 1
IS ':;j ::: A 8
5 5 5 5 14 14 6 12 12
.. 0
:El
4 4 I 8 2
3
3 3 3 7 7 7 10 10
8
I
1 I 1 3 3 3 3 3
3
12
12 12 5 6 13 13 13 13
6
16C558 2KE
16C55BA 16C61 16C62 16C62A 16C62B 16C63 16C63B 16C64
16C64A
128
128 36 128 128 128 192 192 128
128
18 13
2KE lK E 2KE 2K E 2K E 4K E 4K E 2K E
2KE
I 1 I 1 1 I I
1 1
I 1 I 5 2 2
1
Y Y Y Y Y Y Y
Y
33
33
4K E 4K E 4K E
BKE
40 33 40 33 40 33
28 18 22 13
8 11 11
11
3 1 1 I 3 1 1 I 2 3 1 I I 2
3 3 I 1 1 I 2
13 6 13
13
10
11
3 I 1 I 1 1 1 1 I 1 1 1 1 3 I 3 1
I
1
2
1 2
Y
Y
13
13
16C67
16C620
8K E
512 E
368
80
40 33 18 18 18 18 18 28 28 40 40 18 28 28 13 13 13 13 13 22
22
16C62OA 16C621 16C621A 16C622 16C622A 16C641 16C642 16C661 16C662 16C71 16C72 16C72A
33 33 13
22
22
4 4 4 4 4 4 4 4 5 5 4 8 7
1 I 4 I 5 I 5
Y Y Y Y Y Y Y Y Y Y Y Y
2 2 2 2 2 2 2 2 2 2
13 13 13 13 13 13 14 14 14 14 5 13 13
502
Device BPROM(E)RAM
FLASH(F)
Code
Data 192
192 192 192
PIns 28 22
28 22 28 22 40 33
2i
16C73
16C73A 16C73B 16C74 16C74B .16C76
4K E
4K E 4K E 4K E 4K E BKE
Jj J i '" ;:J
p.
11 II II
3 3 3 3 3 3 I
I I I I I I
I I I I I I
2 5 2 5 2'5 1 2 8 I 2 8
6g
Y Y Y Y Y
:I . :s
6 13 13
16C74A 4K E
192
192 368
40 33
40 33 28 22
12
12 12 12 4
3 I I I 2 8
6
13 13
16C77
16C710 16C711
8K E
512 E lK E
368
36 68
40 33
18 13 18 13
- 11
.
4
4 8 9 4
3 I I
I
2 5
2 8 4
Y
Y Y
13
13 14
I
I 3 3 I I I I I
4
4 5
Y
Y
14
14 Y 12 Y 12 14
16C715
16C923 16C924 16F83 16C84
2KE
4K E 4K E 512 F IK F
128
176 176 36t64E 33ffi4E
18 13
64 25 27 64 25 27 18 13 18 13
IK F lK F IK F
2KF 2K F
. .
. . . . .
4 4 4
10 10
I I I
3 3 3 3 3 3 3 3 I I I I I I I I I I I I I 2 2 2 Y Y 2 Y Y
5 14 14
13 13
11
II 10 13 14 13 14
3. I
1 5
1 8 2 5 2 5 I 1 I 2 8 I 2 5 I I 2 8
Y Y Y
Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y
13
13 13 13 13 13 13
16F871
16F872 16F873 16F874 16F876 16F877
2KF
2KF 4KF 2KF 8K F BKF
128ffi4E 40 33
128ffi4E 28 22 192+128E 28 22 192+128E 40 33 368+256E 28 22 368+256E 40 33
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 Programmablewithout the 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 Time Programmable (OTP) varieties of the above devices are also available. All the above devices also contain some bytes of EEPROM user memory in addition to the normal volatile user RAM. All the other PlC devices that are reprogrammable uses EPROM technology. These ceramicwindowed versions can only be erased by exposure to 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 is much cheaper.
Ch.13 Introduction to the Rest of the PlC Family .
503
Devices
Addresses
PC width 9 bits
9 bits 10 bits II bits
'52
'12C508, '54, '54A, '55 12C509, '56, '57 '58
000-17Fh
000-1 FFh 000-3FFh 000-7FFh
* 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 bit will 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 Counter value. Sub-routinesmay therefore be called from anywhere in the program, although their placement is restricted. The 12-coredevices can only be programmed in the parallel mode. Only the 8-pin 12C508 and 12C509 devices, are serially programmable. The Reset addresses of all the lower-range devices are located at the end of the available code memory map. After executingthis instruction,the Program Counter will roll-over to address OOOOh.
504
PlC Micro-Controller
14-Bit Core Width: (12C67x,14000,'C52x,'C6xx,'C7x,'C8x,'F8xand'C92x) These devices constitutethe Medium 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 PCL instructions are summarised in the table below:
Code Size Devices Addresses PC widt b 9 bits GOTO and* CALL Inst. Modify PCL* Instructions
512
'554, '620, '70, 'C83, 'F&3 12C67l, '556, '621, '61, '621, '71, 7lA" 'C&4A, 'F&4,F627 12C672, '55&, '62, '62A, '64, '64A, '622, '72,F62& 14000, '63, '65, '65A, '73, '73A, '74, 74A, '923, '924,F&73,F&76 F874,F&77
OOO-IFFh
9 instruction
pclath+8 in w
lK
000-3FFh
10 bits
10 instruction
pclath+& in w
2K
000- 7FFh
11 bits
11 instruction
pclath+8 in w
4K
OOO-FFFh
12
bits
pclath+& in w
&k
0000-lFFF
13
2 pclath.4,3 + 11 instruct.'"
pclatch+& in w
* 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 PCLATH Register bit 3 by software before the instructions are used. Sub-routines and Look-up tables can be placed anywhere in the available code memory map. 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 addresses OOOOh and0004h. Afterexecuting lastinstruction the availablefor
a device, the Program Counter will roll-over to address OOOOh.
Ch.13 Introduction to the Rest of the PlC Family
505
506
PlC Micro-Controller
- Vol. 11
o
80h SFR
- -
OOh
STATUS.5:
41 User RAM Bytes: (12C509)
Ui8.- v
.........Ft'-
2Fh 30h
IFh
3Fh
FSR.5:
507
(Same as Page 0)
4Fh
CFh
STATUS.5:
-40h
...-,...60h'
...-Jiio.'w-
(Same as Page 0) 46h 47h (Same as Page 0) 4Fh SOh 16 User RAM bytes
(Same as Page 0) 66h 67h (Same as Page 0) 6Fh 70h 16 User RAM bytes 7Fh
FSR <6:5>: 00 01 10 11 *The '57A device has only 18 pins and no Port C. This address is available as an additional 1 RAM byte.
508
PIC Micro-Control/er Operation and Applications - Vol. 11
p
-
--
.
(Not used) CFh
STATUS.5:
128 User RAM Bytes: (12C67x, '62, '62A, '64, '64A, '72, '558, '622 ) p- - o OOh SFR IFh 20h 32 User RAMbytes 3Fh 40h
64 User RAM bytes 7Fh FFh
COh
(Not used)
STATUS.5:
o
509
..."'"'
.l.u.I:.,",J
OOh SFR IFh 20h 80 User RAM bytes 6Fh 70h 16 User RAM bytes 7Fh STATUS <6:5>: 00
80h SFR 9Fh AOh 80 User RAM bytes DFh FOh (Same as Page 0) FFh
100h SFR 11Fh 120h (Not used) 16Fh 170h (Same as Page 0) 17Fh
180h SFR 190h lAOh (Not used) lDFh IFOh (Same as Page 0) IFFh
01
10
11
192 User RAM Bytes: (14000, '63, '65, '65A, '73A, '74A, F873,F874)
...."';"" v
STATUS.5:
...a):.,-,... 80h SFR 9Fh AOh 11Fh 80 User RAM bytes DFh FOh (Same as Page 0) FFh 01
PlC Micro-Controller
....\1,"",k
.La!:!.,,",..1
OOh
100h SFR
16 bytes(876/7)
IFh 20h 80 User RAM bytes 6Fh 70h 16 User RAM bytes 7Fh
STATUS <6:5>: 00
510
I Port
5 1/0 pins
1I Inputpin.
J8-Pin Devices:
Devices: '52, '54, '54A, '56, '58A Port A Port B Devices: 5 pins 8 pins 4 1/0 pins 8 1/0 pins Ilnput pin
'554, '556, '558, '61, '620, '621, '622, '70, '71, '71A, 'C83, 'C84, 'C84A, 'P83, F84,(F627,F628) 5(8) pins 8 pins 5(7) 1/0 pins (I Input) 8 1/0 pins, (USART, CCPI)
Port A Port B
28-Pin Devices:
Devices: '55, '57 Port A Port B Port C 5 pins 8 pins 8 pins 4 1/0 pins 8 1/0 pins 8 1/0 pins Ilnput pin.
Devices: '62, '62A, '63, 72, '73, 73A, F873, F876 Port A Port B Port C 5 pins 8 pins 8 pins 5 1/0 or Analogue inputs or external Timer Clock. 8 1/0 pins. 8 1/0 Ext. Oscillator, CCPI, Serial and USART
Note: The PIC16C5x low range devices do not have internal pull-ups on Pori B. The 12C5OX devices have pull-ups on port pins GPO,GPl and GP3.
51/
-.........---
-. ---... \.--
--...---....
Devices: 14000 Port A Port C Port D. 4 pins 8 pins 8 pins 2 pins 4 I/O or Analogue inputs. 8 I/O or Serial Ports 8 I/O or Analogue inputs, Voltage Comparators or Serial Ports A Voltage Regulator control and an external capacitor charge 'SUM' output
-
-'
Outputs
--
-. --- - ..
Devices: '64, '64A, '65, '65A, '74, '74A, F874, F877 Port A Port B Port C Port D Port E ". ....5 pins 8 pins 8 pins 8 pins 3 pins
-.---...... ,--..,...
5 I/O or Analogue inputs or external Timer Clock 8 I/O pins. 8 I/O Ext. Oscillator, CCPI, Serial and Usart. 8 I/O or Parallel Slave. 3 I/O or Parallel Slave Control.
....---...-..........
--,
Devices: '923, '924: Port A Port B Port C Port D Port E Port F 512 5 pins 8 pins 8 pins 8 pins 8 pins 8 pins 5 I/O or Analogue inputs or ext. Timer Clock 8 I/O pins. 8 I/O Ext. Oscillator, CCPI, Serial Port. 8 I/O or LCD Common/Segment Drivers. 8 LCD Segment Drivers. 8 LCD Segment Drivers.
PIC Micro-Control/er
Configuration Bits
FOSCl
FOSCO
o = Enable 1= Disable
4-Bits: ('54, '54A, '55, '56, '57, '58A)
FOSCl I FOSCO WDTE Watch Dog Oscillator Selection o = Enable o = Disable 00 = HS Oscillator 1 = Enable 01 = XT Oscillator 1= Disable 10 = LP Oscillator 11 = RC Oscillator 5-Bits: (12C508, 12C509) CP
I
Code Protection
I,
MCLRE
CP Code
WDTE
FOSCl
FOSCO
Selection
Reset Input
Watch Dog
Oscillator
PWRTE
WDTE
FOSCl
FOSCO
Power-up
Watch Dog
Selection
Protection Reset Timer Timer 0= Disable 0 = Disable 0'= Disable 1= Enable 1 = Enable 1= Enable
Ch.13 Introduction
[2!
Selection
CPO
PWRTE
WDTE
FOSCl
FOSCO
Code
Power-up
Watch Dog
Oscillator
Reset Timer Timer Protection 00 = Full code o = Disable 0 = Disable 1 = Enable 1 = Enable 01 = Top 3/4 10 = Top 1/2 11 = Disabled
6-Bits: (14000)
I
CPC
Calibration User Code Program Protection Protection Protection o = Enable 0 = Enable O=Enable I = Disable I = Disable I=Disable
[;]
CPU
cCP
PWRTE I WDTE FOSC I Power-up Watch Oscillator Reset Timer Dog Selection O=Enable O=Disable O=HSOsc. I=Disable I=Enable I=Intemal RC Osc.
13
I
12
I
11
CPl
I I
10
CPO
I
9
CPl
I
8
CPO
I
7 x
I
....
0
CPl
CPO
...6
5
Code
4
CPO
I
3
PWRTE
I
2
WDTE
I
I
POSCl
I
posco I
Oscillator
Power-up
Watch Dog
Selection Protection Reset Timer Timer 00 = Full code o = Enable o = Disable I = Disable 1 = Enable 01 = Top 3/4 10 = Top 1/2 11 = Disabled
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-Bits: ('62A, '63, '64A, '65A, '620, '621, '622, '72, '73A, '74A) 13
I
12
~, G; ~ Brown-out
... .6
CPl
11
10
I
9
CPI
I
8
CPO
I
7
x
I
3
I PWRTE
I
210
WDTE
I
BODEN
POSCI
POSCO
Code*
Selection Protection ResetTimer Timer Reset O=Disable00 = Full code 0 = Enable o = Disable 00 = HS Oscillator 1=Enable 01 = Top3/4 1 = Disable 1 = Enable 01 = XT Oscillator 10 = LP 10 = Top 1/2 Oscillator
11 = Disabled
Power-up
Watch Dog
Oscillator
11 = RC Oscillator
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
The Brown-Out Reset: A Brown-out is a short drop in the power supply to the 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-up Reset 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 14 bits:...)
Ch.i3 introduction to the Rest of the PiC Family
5i5
12
I
II
I
10
I
9
I
8
I
7
I
....
0
FOSCO
I
epo
....6
I
epo 5
epo 4.
epo
3
epo
epo 2
I
CPO
I
FOSCl
L
I
epo
CPO I PWRTE
WDTE
Code Power-up Watch Dog Oscillator Selection Protection Reset Timer Timer 0 = Fullcode 0 = Enable 0 = Disable 00 = HS Oscillator I = Disable I = Disable I = Enable 0I = XT Oscillator 10 = LP Oscillator II = RC Oscillator
Note: All the upper configuration bits must co-inside with the selected code protection to have any effect.
Icpolcpo~
6
I
~
I
10
t
9
CPO
I
7 .......
BODEN
Brown-out Code* Power-up Watch Dog Oscillator Selection Protection Reset Timer Timer Reset O=Disable o = Full code 0 = Enable 0 = Disable 00 = HS Oscillator I=Enable I = Disable I = Disable I = Enable 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.
3
PWR~
epo Icpol
I
I
I
0
FOSCO
I
WDTE
FOSCI
516
PlC Micro-Controller
- Vol. 11
G;
654
J CPI
13
12
I
11
I
cpa
CPI
~
I
10
I
9
CPI
I
7 .......
I
cpa
MCLRE
3
I
cpa
PWRTE
WDTE
F~
Code Protect* Power-up Watch Dog 00 = Full code 0 = Enable 0 = Disable 01 = 200 -7FF 1 = Disable 1 = Enable
Oscillator Selection 000 = LP Oscillator 001 = XT Oscillator 010 = HS Oscillator 011 = Invalid 100 = IntRC Oscillator 101 = IntRC (Clock on OSC2) 110 = ExtRC Oscillator 111 = ExtRC(Clock on OSC2)
FOSCII Fosca
Notes:
For Oscillator modes 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 Voltage Programming, In-circuit-debugging, separate EEDATA protection, MCLR pin can be used as an output, and an Internal RC Oscillator selection. The specific settings of the Configuration Bits is too complex to include here, and should rather be studied from the Data Sheets of the devices. -------------------------------
5/7
Not available:
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 the same 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 CLRWDT instruction will have no effect.
-------...--...---...-------------
518
PIC Micro-Controller
- Vol. II
For the lower range devices, the system will 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 system will only reset to the starting address if a Watch Dig Timer time-out occurred while the system was in the normal Running mode. If the time-out occurs while 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.
-------------
5i9
Devices: ('62A, '63, '64A, '65A, '620, '621, '622, '70, '71A, '72, '73A, '74A) PCON: 2 1 0
I I I paR I BaR Power On Flag Brown-Out Reset O=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
I
paR LVD I Power On Flag Low Voltage Detect O=Poweron reset O=Lowvoltage detected I=No power on reset 1=No low voltage det.
Note: Once a Power-On reset or a Low Voltage Condition was detected, the bits must be set by software.
520
PIC Micro-Controller Operation and Applications - Vol. If
* TimerI * Timer2
* The Capture Modules * The Compare Modules * Pulse- Width-Modulator Modules
* The Analogue-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 sensing modules of the 14000.
-----------
521
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/counter with a 3-bit prescaler. It can also be driven by an external oscillator on pins RCOand RCI, even while the device is in the SLEEP mode. 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 PulseWidth-Modulation (or CCP) circuitry. Timer 1 Timer I is a two-byte or 16-bit Register. 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 following Modes:
* 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 RC 1. * 16-Bit External Event counter through pin RCO
* As part of the Capture/Compare/PulseWidth-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 .
TICON ON/OFF:
o
2
3
Timer/Counter
0= OFF I=ON
o = Internal
Timer Clock Source: Timer Source Synchronisation: Timer External Osc. Enable:
I =External
4 5 6 7
Unused Unused
o I
1:4 I :8
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 external low ftequency crystal can be connected to pins RCOand RC 1 for accurate 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:
PIC16C64 RCO I RCI 32768Hz
I
33
,0,
--------------------
I 33pF
523
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 Period Register, 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. through to 1:16. The output of the post-scaler can be used to generate an interrupt.
+1, +2, +4, +8
o
2 3 4 5
6 7
}~Sdod'
Timer ON/OFF: 0
o 1 x
= OFF
Code 0000 0001 0010 0011 0100 0101 0110 0111 Ratio 1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 Code 1000 1001 1010 1011 1100 1101 1110 1111 Ratio 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16
1 =ON
TOUTPS2 TOUTPS3
I Unused
---------------------
524
The Capture Module The Capturemodule is triggered from port pin RC2. It will capture the 16-bit value of Timer I in a two-byte Capture Register. When the capture circuit is triggered, it will also set the appropriate interrupt flag. Timer I can either be driven by 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. CCPIIF Interropt
CCPRlH CCPRIL
Pin RC2
TMRlH TMRlH
+1, +2, +4, +8
CCP1MO
Prescaler
CaDture
x x x x x x x x x x x x x x x x x x x x
000
Module OFF Trigger Trigger Trigger Trigger on Negative on Positive every 4th Positive every 16th Positive
o 1 0 0 o 1 0 1 o 1 1 0
0 1 1 1
525
The Compare Module The Compare module will continuously compare the 16.bit value of Timer 1 to a 16.bit Compare Register. 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. CCP1IF Interrupt CCPR1H
CCPR1L
Pin RC2
TMR1H
TMR1L
1
CCP1M2
CCP1CON
x x x x 0 0 0 0 x x x x 1 0 0 0 x x x x 1 0 0 1 x x x x 1 0 1 0 x x x x 1 0 1 1
-------------
526
PlC Micro-Control/er
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 Slave Buffer and two bits from the Control Register. When a match is found, the output pin 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 Value must be smaller than the Period time, else the output will stay at high.
CCPRIL
CCPICON.5.4 CCPIX CCPIY
CCPRIH
lo-Bit
Comparator
fose
Pulse-Width-Modulator Circuit Diagram The CCPICON Register Settings for the PWM Mode 54321
CCP1CON:
- - XY
o 0 0 0
1 1 x x
= =
Module OFF
PWMMode
Ch.i3
introduction
527
~
,
Period
I
~:,
I
, ,
Period
Resolution
:.. DutyCycle -..: A Typical PWM Wave Form Period Calculations: The Period is given by the formula: Period
For 10 MHz crystal, toscwill be 100 nano-seconds. PR2 can be any value between OOhand FFh, while the Timer 2 Prescaler value can be lx, 2x, 4x or 8x. Iffor example,the prescaleris setto lx, andPR2 = 249d:
Period
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:
Prescaler Ix Ix 2x 4x 8x f(osc) 10 MHz 10 MHz 10 MHz 10 MHz 10 MHz PR2 0 249 249 249 249 Period 400 ns 100 f.Ls 200 f.Ls 400 f.Ls 800 f.LS Frequency
Resolution
528
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 CCP IX and CCP IY in the CCP Control register, CCPICON. For 10 MHz crystal, tescwill be 100nano-seconds. CCPRIL can be any value between OOh FFh, while the Timer 2 Prescaler value can be Ix, 2x, 4x or and 8x. If for example, X and Y are cleared, the prescaler set to Ix, and the CCPRIL value is 200d: Duty Cycle = (4 x 200 + 0 + 0) x 100 ns x I = 80 flsec The output wave form will 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 made bigger 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: Prescaler Ix Ix 2x 4x 8x C(osc) CCPRIL 10 MHz 10 MHz 10MHz 10 MHz 10 MHz 0 200 200 200 200 XY 0 0 0 0 0 I 0 0 0 0 Duty Cycle 100 ns 80 fls 160 fls 320 fls 640 fls Resolution 100 nsec 100 nsec 200 nsec 400 Ilsec 800 flsec
Note that the Duty Cycle resolution will not change if the PR2 register value is changed. The 10-bit resolution allows 1024 increments only for the full PR2 value of255.
------------
529
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 RC I. The inteJJ1lpt lags are CCP1IE and CCP1IF in the PIE2 and PIR2 registers. f * Timer 2 is also used for the 2nd Compare module, and pin RC1 is then the output. This output can also start the ADC module in addition to the reset of
Timer 1.
'14000, '61, '62, '62A, '64, '64A, '72, '923, '924, F627, F628.
Devices containing the Timers and Two CCP Modules are: '63, '73, '73A, '74, '74A, F873, F874, F876, F877. ----------------------
530
PlC Micro-Control/er
Analogue-to-Digital Conversion in General An analogue-to-digital converter is in principle a type of voltmeter. It will measure the 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
2
I. I. . . I
c::
3 [ Needle
4
1.....
I. . . .
. ..
5 volt
I
(3.4 volt)
Scale and Needle type Analogue Voltmeter In an Analogue-to-Digital Converter, the full scale voltage range will be divided into a number of equal parts. The converter will return a binary coded representation of the applied voltage as a ftaction of the full scale value. The number of bits used will decide the number of equal divisions (the resolution), while the full scale value will decide the magnitude of each division. Apart trom the normal Ground and Analogue Signal Input, an ADC device must also have a Reference Voltage Input, VREF. he full scale voltage must be applied T 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 successive approximationmethod is still the quickest economical method. This method will divide the full scale voltage into two halves first. It will compare if the incoming signal falls in the top or bottom half. If it is within the top half, the MSB of the output will be 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 the PlC Family
531
the conversion. This time is called the conversionspeed. To start a conversion,he devicewillnonnallyhavesomeStart Conversion t control. An End of Conversionsignalwill be generatedwhenthe conversio'lis done.
Nonnally the incoming analogue signal must be kept steady while a conversion is 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 incoming analogue signals may be applied to one of the RAOto RA3 pins. For the 5-channels of the '72, '73, '73A, '924, F873 and F876, an additionalpin, RA5, is used. The three Port E pins of the '74, '74A, F874 and F877, supply the extra connections for the 8 channels. The reference voltage can either be the chip supply, Vdd, or a smaller reference voltage, applied to pin RA3. The speed 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-Bit resolution is available for the F873/4/6/7 devices in ADRESH and ADRESL. The Interrupt Enable (ADIE) and Interrupt flags (ADIF) associated with the ADC module 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 software when the interrupt
sub-routine is executed.
532
PlC Micro-Control/er
'
o
2 3 4 5 6 7
ON/OFF Conversion
0= OFF I=ON
1
=Done
I .. GO to Start Conversion, cleared by Hardware when DONE. Channel Select: 000 to III
ADCSl
Reset Value: 00000000
Code 00 01 10 11
Channel Selection for the 4-, 5- and 8-channel Devices CHS2 CHSl CHSO ADC Channel Pin
o o o o
I I I I
0 0 1 1 0 0 I I
0 1 0 1 0 I 0 I
1, ADCONI
0 1 2 3 4' S 6 7
RAO RAl RA2 RA3 (4-channel) RAS (S-channel) REO REI RE2 (8-channel)
o
2 3
7
Reset
) -.,
Pins 4 to 6 are not used.
>
PCF03
Value:
533
RA2 A A D D
RAO A A A D
o o
1 1
0 1 0 0
(5/8-Channel devices)
RE2 A A D D D D D
REI A A D D D D D
A D D D
A A A A D D D
A A A A A A D
A = Analogue Input
D = Digital I/O
The ADC Result Register, ADRES The ADRES register will contain the digital result of the last completed conversion.
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
- Vol. 11
ADCSl
ADCSO
Source
o o
I I
0 I 0 I
Note: The PlC may be placed in the SLEEP mode and woken up by a Done
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 Tracking mode while the 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. A minimum sample time of 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 be followed: I. Select the appropriate port pin configuration mode of which analogue inputs will be used, by setting the (pCFG2,) PCFGI and PCFGOpins in the ADCON I
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 Family
535
6. Select the appropriate analogue channel by setting the (CHS2,) CHSl and CHSObits 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 system must 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 the GOIDONE bit in the ADCONOregister to start the conversion. 11. To maximisethe conversion accuracy, the system may be placed in the SLEEP mode directly after the instructionthat set the GOIDONE bit. When the system is in the SLEEP mode, digital switching noises will be reduced to a minimum. The internal RC oscillator must be selected if the system is going to be placed in 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 after delay of at least 10 ~sec for the Sample and Hold circuits 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 considerably more but the accuracy makes the device ideally suited for battery monitoring and maintenance applications. ---------------------------
536
PlC Micro-Control/er
- Vol. 11
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 Chip Select, Write and 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
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.
o
2 3
Unused
Parallel Slave Port Mode:
4 PSPMODE 5 mOF
6
7
Input BufferOverflow:
Output Buffer Full:
OBF mF
Reset Value: 0000
-111
Input BufferFull:
. I-Full
o =Empty
---------------
537
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.
----------.------
* 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
- Vol. 11
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 fixed reference voltage, and the other input is connected to the changing voltage that is monitored. The two input voltage levels are continuouslycompared to one another, and the output voltage will 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 and minimum 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
~
~O
= 000
RAO
FU\3
RAl
CM<2:O>
~
+
0 0
(Off)
.
+
FU\3 -
CM<2:O>
~ -V-
CM<2:O>
~ ~ ~ ~
ClOut
~-'
-'
+
-
ClOut
RAl
~
VRBF
C20ut
C20ut
CM<2:O>
= 100
CM<2:O>"OIO
RAO
+ +
ClOut
ClOut
RAl
.
+
C20ut
C20ut
= 011
RA4 RAO
RAl
CM<2:O>
= 110
~-'
ClOut
C20ut. ~
C20ut
101
CM<2:O> = 001
539
The internal Voltage Reference Module for these devices is software adjustable 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.25 VDDto 3/4 VDD' The reference voltage can be used in conjunctionwith the ComparatorModules and can also be available as an analogue output on pin RA2. ---------------------------
---------------------------
---------------------------
540
PIC Micro-Controller
- Vol. 11
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 operation of some of these features and assist in the choice of another controller to suit specific needs. It is, however highly recommended to study the actual detail of the other controllerand features directly from the applicable data sheets before it 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 family members may be covered in future courses and workshops.
541
Notes:
542
PIC Micro-Controller