(FREE PDF Sample) Microcontrollers High Performance Systems and Programming 1st Edition Julio Sanchez Ebooks
(FREE PDF Sample) Microcontrollers High Performance Systems and Programming 1st Edition Julio Sanchez Ebooks
(FREE PDF Sample) Microcontrollers High Performance Systems and Programming 1st Edition Julio Sanchez Ebooks
com
https://ebookgate.com/product/microcontrollers-
high-performance-systems-and-programming-1st-
edition-julio-sanchez/
https://ebookgate.com/product/microcontroller-programming-the-
microchip-pic-1st-edition-julio-sanchez/
https://ebookgate.com/product/scala-high-performance-
programming-1st-edition-theron/
https://ebookgate.com/product/julia-high-performance-programming-
ivo-balbaert/
https://ebookgate.com/product/android-high-performance-
programming-1st-edition-enrique-lopez-manas/
High Performance Computing Programming and Applications
Chapman Hall CRC Computational Science 1st Edition John
Levesque
https://ebookgate.com/product/high-performance-computing-
programming-and-applications-chapman-hall-crc-computational-
science-1st-edition-john-levesque/
https://ebookgate.com/product/phase-locking-in-high-performance-
systems-from-devices-to-architectures-1st-edition-behzad-razavi/
https://ebookgate.com/product/bioinformatics-high-performance-
parallel-computer-architectures-embedded-multi-core-systems-1st-
edition-bertil-schmidt/
https://ebookgate.com/product/wind-energy-in-electricity-markets-
with-high-wind-penetration-1st-edition-julio-usaola/
https://ebookgate.com/product/high-performance-and-hardware-
aware-computing-rainer-buchty/
Electrical Engineering Sanchez
Canton
Microcontrollers
HIGH-PERFORMANCE SYSTEMS
AND PROGRAMMING
Microcontrollers
Microcontrollers
Microcontrollers: High-Performance Systems and Programming
discusses the practical factors that make the high-performance PIC
series a better choice than their mid-range predecessors for most
systems. However, one consideration in favor of the mid-range
devices is the abundance of published application circuits and code
samples. This book fills that gap:
• Provides downloadable software, including tools, resources,
supplementary materials, and code listings
HIGH-PERFORMANCE SYSTEMS
• Includes sample circuits with their corresponding programs,
as well as tested PCB files
AND PROGRAMMING
• Focuses on the popular embedded systems with PIC18
series microcontrollers
• Contains an appendix with a C language tutorial, PIC18
instruction set, links to useful tools and software
• Supplies sample circuits that are not copyrighted or patented, so
readers can freely use them in their own applications
• Covers selected topics and examples that provide solutions to
Julio Sanchez
problems that practicing engineers may encounter and are not
readily found in the literature Maria P. Canton
Designed to be functional and hands-on, this book provides sample
circuits with their corresponding programs. It clearly depicts and
labels the circuits, in a way that is easy to follow and reuse. The
book matches sample programs to the individual circuits and
discusses general programming techniques.
K16291
Microcontrollers
HIGH-PERFORMANCE SYSTEMS
AND PROGRAMMING
Julio Sanchez
Eastern Florida State College
Maria P. Canton
Brevard Public Schools
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been
made to publish reliable data and information, but the author and publisher cannot assume responsibility for the valid-
ity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti-
lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy-
ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://
www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For
organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
Table of Contents
Preface xx
v
vi Table of Contents
Index 671
Preface
Like our preced ing titles in this field, the book is intended as a ref erence and re -
source for en gineers, scientists, and electronics enthusiasts. The book focuses on
the needs of the working professional in the fields of electrical, electronic, com-
xxi
xxii Preface
puter, and software en gineering. In developing the material for this book, we have
adopted the following rules:
1. The use of standard or off-the-shelf components such as input/output devices, in-
tegrated circuits, motors, and programmable microcontrollers, which readers
can easily duplicate in their own circuits.
2. The use of inexpensive or freely available development tools for the design and
prototyping of embedded systems, such as electronic design programs, program-
ming languages and environments, and software utilities for creating printed cir-
cuit boards.
3. Our sample circuits and programs are not copyrighted or patented so that readers
can freely use them in their own applications.
Our book is designed to be func tional and hands-on. The resources furnished to
the reader include sample circuits with their corresponding programs. The circuits
are depicted and labeled clearly, in a way that is easy to follow and reuse. Each cir-
cuit includes a parts list of the resources and components required for its fabrica -
tion. For the most important circuits, we also provide tested PCB files. The sample
programs are matched to the individual circuits but general programming tech-
niques are also discussed in the text. There are appendices with useful information
and the book's online software contains a listing of all the sample programs devel-
oped in the text.
Julio Sanchez
Maria P. Canton
Chapter 1
A microcontroller or DSP usually includes a cen tral processor, input and out put
ports, memory for program and data stor age, an in ternal clock, and one or more pe -
ripheral devices such as timers, counters, analog-to-digital converters, serial com-
munica tion facilities, and watch dog circuits. More than two dozen companies in the
United States and abroad manufac ture and mar ket microcontrollers. Mostly they
range from 8- to 32-bit devices. Those at the low end are intended for very simple
circuits and provide limited functions and program space, while the ones at the high
end have many of the fea tures associated with microprocessors. The most popular
microcontrollers include several from Intel (such as the 8051), from Zilog (deriva-
tives of their famous Z-80 microprocessor) from Motorola (such as the 68HC05),
from Atmel (the AVR), the Parallax (the BASIC Stamp), and many from Microchip.
Some of the high-end Microchip microcontrollers and DSPs are the topic of this
book.
1
2 Chapter 1
The original PIC was built to complement a Gen eral Instruments 16-bit CPU des-
ignated the CP-1600. The first 8-bit PIC was developed in 1975 to improve the per-
formance of the CP-1600 by offloading I/O tasks from the CPU. In 1985, General
Instrument spun off its microelectronics division. At that time, the PIC was re-de-
signed with inter nal EPROM to produce a programmable controller. Today, hun-
dreds of ver sions and vari a tions of PIC microcontrollers are avail able from
Microchip. Typical on-board peripherals include input and output ports, serial com-
munication modules, UARTs, and motor control devices. Program memory ranges
from 256 words to 64k words and more. The word size varies from 12 to 14 or 16
bits, depending on the specific PIC family.
It is often mentioned that one of the reasons for the success of the PIC is the sup-
port provided by Microchip. This support includes development software, such as a
professional-quality development environment called MPLAB, which can be down-
loaded free from the company's website (www.microchip.com). The MPLAB pack-
age includes an assembler, a linker, a debugger, and a simulator. Microchip also sells
an in-circuit debugger called MPLAB ICD 2. Other development products intended
for the professional market are also available from Microchip.
Many other programmers are available on the market. Microchip offers several
high-end models with in-circuit serial programming (ICSP) and low-voltage pro -
gramming (LVP) capabilities. These devices allow the PIC to be programmed in the
target circuit. Some PICs can write to their own program memory. This makes possi-
ble the use of so-called bootloaders, which are small resident programs that allow
loading user software over the RS-232 or USB lines. Programmer/debugger combi-
nations are also offered by Microchip and other vendors.
4 Chapter 1
Development Boards
A development board is a demonstration circuit that usually contains an array of con -
nected and connectable com ponents. Their main purpose is as a learning and experi-
ment tool. Like programmers, PIC development boards come in a wide range of prices
and levels of complexity. Most boards target a specific PIC microcontroller or a PIC
family of related devices. Lacking a development board, the other op tion is to build
the circuits oneself, a time-consuming but valuable experience. Figure 1.2 shows the
LAB-X1 development board for the 16F87x PIC family.
The LAX-X1 board, as well as sev eral other mod els, are prod ucts of
microEngineering Labs, Inc. Development boards from Microchip and other ven -
dors are also available.
Within each of the groups the PIC are classified based on the first two digits of
the PIC's family type. However, the sub-classification is not very strict, as there is
some overlap. In fact, we find PICs with 16X designations that belong to the base -
line family and others that be long to the mid-range group. In the fol lowing sub-sec-
tions we describe the basic charac teristics of the var ious sub-groups of the three
major PIC families with 8-bit architectures.Table 1.1 shows the principal hardware
characteristics of each of the four 8-bit PIC families
Table 1.1
8-bit PIC Architec tures Compar ison Chart
BASELINE MID-RANGE ENHANCED PIC18
battery-operated applications because they have low power requirements. The typi-
cal member of the base line group has a low pin count, flash program memory, and low
power requirements. The following types are in the Baseline group:
• PIC10 devices
• PIC12 devices
• PIC14 devices
• Some PIC16 devices
We present a short summary of the func tionality and hardware types of the base-
line PICs in the sec tions that follow, although these de vices are not cov ered in this
book.
PIC10 devices
The PIC10 devices are low-cost, 8-bit, flash-based CMOS microcontrollers. They use
33 single-word, single-cycle instructions (except for program branches, which take
two cycles. The instructions are 12-bits wide. The PIC10 devices feature power-on re-
set, an internal oscillator mode which saves hav ing to use ports for an external oscilla-
tor. They have a power-saving SLEEP mode, A Watch dog Timer, and optional code
protection.
The recommended applications of the PIC10 family range from personal care ap-
pliances and security systems to low-power remote transmitters and receivers. The
PICs of this family have a small footprint and are manufac tured in formats suitable
for both through hole or surface mount technologies. Table 1.2 lists the charac teris-
tics of the PIC10F devices.
Table 1.2
PIC10F Devices
10F200 10F202 10F204 10F206
Clock:
Max i mum Fre quency
of Op era tion (MHz) 4 4 4 4
Mem ory:
Flash Program
Mem ory 256 512 256 512
Data Mem ory (bytes) 16 24 16 24
Pe riph er als:
Timer Mod ule(s) TMR0 TMR0 TMR0 TMR0
Wake-up from Sleep Yes Yes Yes Yes
Com para tors 0 0 1 1
Fea tures:
I/O Pins 3 3 3 3
In put Only Pins 1 1 1 1
In ter nal Pull-ups es Yes Yes Yes
In-Cir cuit Se rial
Pro gram ming Yes Yes Yes Yes
In struc tions 33 33 33 33
Pack ages: --------------------------------- 6-pin SOT-23 -------------------------------
----------------------------------- 8-pin PDIP --------------------------------
Microcontrollers for Embedded Systems 7
Two other PICs of this series are the 10F220 and the 10F222. These versions in-
clude four I/O pins and two analog-to-digital converter channels. Program memory
is 256 words on the 10F220 and 512 in the 10F222. Data memory is 16 bytes on the
F220 and 23 in the F222.
PIC12 Devices
The PIC12C5XX fam ily are 8-bit, fully static, EEPROM/EPROM/ROM-based CMOS
microcontrollers. The devices use RISC architecture and have 33 single-word, sin-
gle-cycle instructions (except for program branches that take two cycles). Like the
PIC10 family, the PIC12C5XX chips have power-on reset , device reset, and an internal
timer. Four oscillator options can be selected, including a port-saving internal oscilla-
tor and a low-power oscillator. These devices can also operate in SLEEP mode and
have watchdog timer and code pro tec tion features.
The PIC12C5XX devices are recommended for applications ranging from per-
sonal care appliances, security systems, and low-power remote transmitters and re-
ceivers. The internal EEPROM memory makes possible the storage of user-defined
codes and passwords as well as appliance setting and receiver frequencies. The var-
ious packages allow through-hole or surface mount ing tech nologies. Table 1.3 lists
the characteristics of some selected members of this PIC family.
Table 1.3
PIC 12CXXX and 12CEXXX Devices
Table 1.3
PIC 12CXXX and 12CEXXX Devices (continued)
Two other members of the PIC12 family are the 12F510 and the 16F506. In most
respects these devices are similar to the ones previously described, except that the
12F510 and 16F506 both have flash program memory. Table 1.4 lists the most impor-
tant features of these two PICs.
Table 1.4
PIC12F510 and 12F675
12F629 12F675
Clock:
Maximum Frequency of Operation (MHz) 20 20
Memory:
Flash Program Memory 1024 1024
Data Memory (SRAM bytes) 64 64
Peripherals:
Timers 8/16 bits 1/1 1/1
Wake-up from Sleep on Pin Change Yes Yes
Features:
I/O Pins 6 6
Analog comparator module Yes Yes
Analog-to-digital converter No 10-bit
In-Circuit Serial Programming Yes Yes
Enhanced Timer1 module Yes Yes
Interrupt capability Yes Yes
Number of Instructions 35 35
Relative addressing Yes Yes
Packages 8-pin PDIP, 8-pin PDIP
SOIC, SOIC,
DFN-S DFN-S
Two other members of the PIC12F are the 12F629 and 12F675. The only differ-
ence between these two devices is that the 12F675 has a 10-bit analog-to-digital con-
verter while the 629 has not A/D converter. Table 1.5 lists some important features
of both PICs.
Microcontrollers for Embedded Systems 9
Table 1.5
PIC12F629 and 12F675
12F629 12F675
Clock:
Maximum Frequency of Operation (MHz) 20 20
Memory:
Flash Program Memory 1024 1024
Data Mem ory (SRAM bytes) 64 64
Peripherals:
Tim ers 8/16 bits 1/1 1/1
Wake-up from Sleep on Pin Change Yes Yes
Features:
I/O pins 6 6
Analog comparator module Yes Yes
Analog-to-digital converter No 10-bit
In-cir cuit serial programming Yes Yes
Enhanced Timer1 mod ule Yes Yes
Inter rupt capability Yes Yes
Number of instructions 35 35
Relative addressing Yes Yes
Packages 8-pin PDIP 8-pin PDIP
SOIC SOIC
DFN-S DFN-S
Several members of the PIC12 family, 12F635, 12F636, 12F639, and 12F683, are
equipped with special power-management features (called nanowatt technology by
Microchip). These devices were especially designed for systems that require ex-
tended battery life.
PIC14 Devices
The single member of this family is the PIC14000, which is built with CMOS tech nol-
ogy. This makes the PIUC14000 fully static and gives it industrial temperature range.
The 14000 is recommended for battery chargers, power supply controllers, power
management system controllers, HVAC controllers, and for sensing and data acquisi-
tion applications.1.3.2
PIC16 Devices
This is by far the largest mid–range PIC group. Currently over 80 versions of the PIC16
are listed in production by Microchip. Although we do not cover the mid-range devices
10 Chapter 1
in this book, we have selected a few of its most prominent members of the PIC16 fam-
ily to list their most important fea tures. These are found in Table 1.6.
Table 1.6
PIC16 Devices
16C432 16C58 16C770 16F54 16F84A 16F946
Clock:
Memory:
Program memory type OTP OTP OTP Flash Flash Flash
K-bytes 3.5 3 3.5 0.75 1.75 14
K-words 2 2 2 0.5 1 8
Data EEPROM 0 0 0 0 64 256
Peripherals:
I/O channels 12 12 16 12 13 53
ADC channels 0 0 6 0 0 8
Comparators 0 0 0 0 0 2
Timers 1/8-bit 1/8-bit 2/8-bit 1/8-bit 1/8-bit 2/8-bit
1/16-bit 1/16-bit
Watchdog timer Yes Yes Yes Yes Yes Yes
Features:
ICSP Yes No Yes No Yes Yes
ICD No No No No 0 1
Pin count 20 18 20 18 18 64
Communications - - MPC/SPI - - AUSART
Packages 20/CERDIP, 18/CERDIP 20/CERDIP 18/PDIP 18/PDIp 64/TQFP
20/SSOP 18/PDIP 20/PDIP 18/SOIC 18/SOIC
208mil 18/SOIC 20/SOIC 300mil 300mil
300mil 300mil
tion. These devices are furnished in 18 to 80 pin packages. Microchip describes the
PICs in this family as high-performance with integrated A/D converters.
Digital Signal Processor
The notion of digital signal processing starts with the conversion of analog signal in-
formation such as voice, image, temperature, or pressure primitive data to digital val-
ues that can be stored and manipulated by a com puting device. Convert ing the data
from its primitive analog form to a digital format makes it much easier to analyze, dis-
play, store, process, or convert the data to another format. Digital signal processing is
based on the fact that com puting and data pro cessing operations are easier to perform
on digital data than on raw analog signals.
digitizer and
transmitter
sensor
optical
system
scanning
mirror
image data
processing
scan line
scanning
direction
receiving image
station
processes this data and formats it into an image. In this scheme, digital signal pro-
cessing can take place as the image data is sensed by the instrument and tempo-
rarily stored on board the satellite, or when the raw data received by the Earth
station is con verted into an image that can be manipulated, viewed, stored, or
re-processed.
Analog-to-Digital
Conversion from analog-to-digital form and vice versa are not formally operations of a
DSP. However, these conversions are so often required during signal processing that
most DSP devices include the analog-to-digital and digital-to-analog conversion hard-
ware.
sampling periods
1 2 3 4 5 6 7 8 9 10 11 12 13
80
voltage of analog signal
70
60
50
40
30
20 analog signal
10
0
15 20 28 37 12 14 35 78 69 63 85 57 28
sampled digital values
In Figure 1.5 we see that the sampled values are actually an approximation of the
analog curve, as the variations between each interval are lost in the conversion pro-
cess. Therefore, the more sampling periods, the more accurate the approximation.
On the other hand, too small a sampling rate tends to re duce the sig nificance of the
data by producing repeated values in the digital record.
Chapter 2
PIC18 Architecture
13
14 Chapter 2
Although the PIC16 series has been very successful in the microcontroller mar-
ketplace, it also suffers from limitations and constraints. Perhaps the most signifi-
cant limitation is that the devices of the PIC16 family can only be programmed in
Assembly language. Other limitations result from the device's RISC design. For ex-
ample, the absence of certain types of opcodes, such as the Branch instruction,
make it nec essary to combine a skip opcode followed by a goto op eration in order
to provide a con ditional, targeted jump. Other limitations relate to the hard ware it-
self: small stack and a single interrupt vector. As the complexity, memory size, and
the number of pe ripheral modules increased, the limitations of the PIC16 series
became more evident.
In the PIC18 series, Microchip reconsidered its PIC16 de sign rules and produced
a completely new style microcontroller, with a much more complex core, while lim-
iting the changes to the pe ripheral modules. The degree of change can be deduced
from the ex pansion of the instruction set from 35 14-bit to 83 16-bit operation codes.
Memory has gone from 14 to 128 KB; the stack from 8 levels to 32 levels. These
changes made it possible to optimize the PIC18 series for C language programming.
1 40
MCLR/VPP RB7/PGD
2 39
RAO/ANO RB6/PGC
3 38
RA1/AN1 RB5/PGM
4 37
RA2/AN2A/REF- RB4
5 36
RA3/AN3A/REF+ RB3/CCP2*
6 35
RA4/TOCKI RB2/INT2
7 34
RA5/AN4/SS/LVDIN RB1/INT1
8 33
RE0/RD/AN5 RBO/INTO
9
18F442 32
RE1/WR/AN6 Vdd
10 31
RE2/CS/AN7 Vss
11 30
Vdd 18F452 RD7/PSP7
12 29
Vss RD6/PSP6
13 28
OSC1/CLKI RD5/PSP5
14 27
OSC2/CLKO/RA6 RD4/PSP4
15 26
RCO/T1OSO/TICK1 RC7/RX/DT
16 25
RC1/T1OSI/CCP2 RC6/TX/CK
17 24
RC2/CCP1 RC5/SDO
18 23
RC3/SCK/SCL RC4/SDI/SDA
19 22
RDO/PSPO RD3/PSP3
20 21
RD1/PSP1 RD2/PSP2
For learning and experimentation the devices in DIP packages are more conve-
nient because they can be easily inserted in the ZIF (zero insertion force) sockets
found in most programming devices, development boards, and bread boards. The de-
vices in Figure 1.1 and Figure 1.2 are so equipped. A PLCC (plastic leaded chip car-
rier) package with 44 pins is also available for 18F442 and 18F452 devices. We do
not cover this option.
From Table 2.1 the following general features of the PIC18FXX2 devices can be
deduced:
1. Operating frequency is 40 MHz for all devices. They all have a 75 opcode instruc-
tion set.
2. Program memory ranges from 16K (8,192 instructions) in the PIC18F2X2 devices
to 32K (16,384 instructions) in the PIC18F4X2 devices.
3. Data memory ranges for 768 to 1,536 bytes.
4. Data EEPROM is 256 bytes in all devices.
5. The PIC18F2X2 devices have three I/O poerts (A, B, and C) and the PIC18F4X2 de-
vices have five ports (A, B, C, D, and E).
6. All devices have four timers, two Capture/Compare/PWM modules, MSSP and
adressable USART for serial communications and 10-bit analog-to-digital mod-
ules.
7. Only PIC18F4X2 devices have a parallel port.
CPU
oscillators
ports
internal modules
bits: 7 6 5 4 3 2 1 0
- - - N OV Z DC C
The 21-bit wide Program Counter register specifies the address of the next instruction
to be ex ecuted. The reg ister mapping of the Program Counter register is shown in Fig-
ure 2.5.
18 Chapter 2
Bits 20 15 7 0
As shown in Figure 2.5, the low byte of the ad dress is stored in the PCL register,
which is readable and writeable. The high byte is stored in the PCH register. The up-
per byte is in the PCU register, which contains bits <20:16>. The PCH and PCU regis-
ters are not di rectly read able or writeable. Up dates to the PCH reg is ter are
performed through the PCLATH register. Updates to the PCU register are performed
through the PCLATU register.
The Program Counter addresses byte units in program memory. In order to pre -
vent the Pro gram Counter from becoming misaligned with word instructions, the
LSB of PCL is fixed to a value of '0' (see Figure 2.5). The Program Counter incre -
ments by 2 to the ad dress of the next se quen tial in struc tions in the program
memory.
The CALL, RCALL, GOTO, and program branch instructions write to the Program
Counter directly. In these instructions, the contents of PCLATH and PCLATU are not
transferred to the pro gram counter. The contents of PCLATH and PCLATU are trans-
ferred to the Pro gram Counter by an operation that writes PCL. Similarly, the upper
2 bytes of the Program Counter will be transferred to PCLATH and PCLATU by an
operation that reads PCL.
Hardware Multiplier
All PIC18FXX2 devices contain an 8 x 8 hardware multiplier in the CPU. Because mul-
tiplication is a hardware operation it completes in a single instruction cycle. Hard-
ware multiplica tion is unsigned and produces a 16-bit re sult that is stored in a 16-bit
product reg ister pair labeled PRODH (high byte) and PRODL (low byte).
Interrupts
PIC18FXX2 devices support multiple interrupt sources and an interrupt priority
mechanism that allows each interrupt source to be as signed a high or low priority
level. The high-prior ity interrupt vector is at OOOOO8H and the low-priority interrupt
vector is at 000018H. High-priority interrupts override any low-priority interrupts that
may be in progress. Ten registers are related to interrupt operation:
PIC18 Architec ture 19
• RCON
• INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
Interrupt priority is enabled by setting the IPEN bit {mapped to the RCON<7>
bit}. When interrupt priority is enabled, there are 2 bits that enable interrupts glob-
ally. Setting the GIEH bit (1NTCON<7>) enables all interrupts that have the priority
bit set. Setting the GIEL bit (INTCON<6>) enables all interrupts that have the prior-
ity bit cleared. When the interrupt flag, the en able bit, and the ap propriate global in-
ter rupt en able bit are set, the in ter rupt will vec tor to ad dress OOOOO8h or
000018H, de pending on the priority level. Individual in ter rupts can be dis abled
through their corresponding enable bits.
When the IPEN bit is cleared (default state), the interrupt priority feature is dis-
abled and the interrupt mechanism is compatible with PIC mid-range devices. In
this compatibility mode, the interrupt priority bits for each source have no effect
and all interrupts branch to address OOOOO8H.
When an interrupt is handled, the Global Interrupt Enable bit is cleared to disable
further interrupts. The return address is pushed onto the stack and the Pro gram
Counter is loaded with the interrupt vec tor address, which can be OOOOO8H or
000018H. In the Interrupt Service Routine, the source or sources of the interrupt can
be de termined by testing the interrupt flag bits. To avoid recursive interrupts, these
bits must be cleared in software be fore re-enabling interrupts. The “return from in-
terrupt“ instruction, RETFIE, exits the interrupt routine and sets the GIE bit {GIEH
or GIEL if priority levels are used), which re-enables interrupts.
Sev eral ex ter nal in ter rupts are also sup ported, such as the INT pins or the
PORTB input change interrupt. In these cases, the interrupt latency will be three to
four instruction cycles. Interrupts and interrupt programming are the subject of
Chapter 8.
These special features are re lated to the fol lowing functions and components:
• SLEEP mode
• Code protection
• ID locations
• In-circuit serial programming
• SLEEP mode
SLEEP mode is designed to offer a very low current mode during which the de-
vice is in a power-down state. The ap plica tion can wakeup from SLEEP through the
following mechanisms:
1. External RESET
2. Watchdog Timer Wake-up
3. An interrupt
The Watch dog Timer is a free running on-chip RC oscillator, that does not re quire
any external components. This RC oscillator is separate from the RC oscillator of
the OSC1/CLKI pin. That means that the WDT will run, even if the clock on the
OSC1/CLKI and OSC2/CLKO/ RA6 pins of the device has been stopped, for example,
by ex ecution of a SLEEP instruction.
Watchdog Timer
A Watchdog Timer time-out (WDT) generates a device RESET. If the device is in
SLEEP mode, a WDT causes the de vice to wakeup and continue in normal operation
(Watchdog Timer Wake-up). If the WDT is enabled, software ex ecution may not dis-
able this function. When the WDTEN configuration bit is cleared, the SWDTEN bit en-
ables/disables the operation of the WDT. Values for the WDT postscaler may be
assigned using the configuration bits.
The CLRWDT and SLEEP instructions clear the WDT and the postscaler (if as-
signed to the WDT) and prevent it from timing out and generating a device RESET
condition. When a CLRWDT instruction is executed and the postscaler is assigned
to the WDT, the postscaler count will be cleared, but the postscaler assignment is
not changed.
The WDT has a postscaler field that can extend the WDT Reset pe riod. The
postscaler is selected by the value written to 3 bits in the CONFIG2H register during
device programming.
PIC18 Architec ture 21
Wake-Up by Interrupt
When global interrupts are disabled (the GIE bit cleared) and any interrupt source has
both its interrupt enable bit and interrupt flag bit set, then one of the following will oc-
cur:
When an interrupt occurs before the ex ecution of a SLEEP instruction, then the
SLEEP instruction becomes a NOP. In this case, the WDT and WDT postscaler will
not be cleared, the TO bit will not be set, and PD bits will not be cleared.
If the interrupt condition occurs during or after the ex ecution of a SLEEP instruc-
tion, then the de vice will immediately wakeup from SLEEP. In this case, the SLEEP
instruction will be completely executed be fore the wake-up. Therefore, the WDT
and WDT postscaler will be cleared, the TO bit will be set, and the PD bit will be
cleared.
Even if the flag bits were checked before executing a SLEEP instruction, it may
be possible for these bits to set be fore the SLEEP instruction completes. Code can
test the PD bit in order to de termine whether a SLEEP instruction executed. If the
PD bit is set, the SLEEP instruction was executed as a NOP. To ensure that the WDT
is cleared, a CLRWDT instruction should be executed be fore a SLEEP instruction.
For many applications it is desirable to be able to detect a drop in device voltage below
a certain limit. In this case, the application can define a low voltage window in which it
can per form housekeep ing tasks before the volt age drops be low its defined operating
range. The Low Voltage Detect feature of the PIC18FXX2 devices can be used for this
purpose. For example, a voltage trip point for the de vice can be spec ified so that when
this point is reached, an interrupt flag is set. The program will then branch to the inter-
rupt's vector address and the interrupt handler software can take the cor responding
action. Because the Low Voltage Detect circuitry is completely under software con-
trol, it can be “turned off” at any time, thus saving power.
Implementing Low Voltage Detect requires setting up a comparator that reads the
reference voltage and compares it against the preset trip-point. This trip-point volt-
age is software programmable to any one of sixteen values by means of the 4 bits la-
beled LVDL3:LVDLO. When the device voltage becomes lower than the preselected
trip-point, the LVDIF bit is set and an interrupt is generated.
Device Configuration
High Priority Interrupt Vector 0008H High Priority Interrupt Vector 0008H
Low Priority Interrupt Vector 0018H Low Priority Interrupt Vector 0018H
On-Chip On-Chip
Program Memory Program Memory
3FFFH
4000H
7FFFH
8000H
Read '0'
Read '0'
1FFFFFH 1FFFFFH
200000H 200000H
PIC18F442/242 PIC18F452/252
Figure 2.6 Program memory map for the PIC18FXX2 family.
PIC18 Architec ture 23
The stack consists of a 31-word deep and 21-bit wide RAM structure. The current
stack position is stored in a 5-bit Stack Pointer reg ister labeled STKPTR. This regis-
ter is in itialized to OOOOOB af ter all RESETS. There is no RAM memory cell associ-
ated with Stack Pointer value of OOOOOB. When a CALL type instruction executes
(PUSH op er a tion), the stack pointer is first incre mented and the RAM loca tion
pointed to by STKPTR is written with the con tents of the PC. Dur ing a RETURN type
in struc tion (POP op er a tion), the con tents of the RAM lo ca tion pointed to by
STKPTR are transferred to the PC and then the stack pointer is decremented.
The stack space is a unique mem ory structure and is not part of either the pro -
gram or the data space in the PIC18FXX2 devices. The STKPTR register is readable
and writeable, and the ad dress on the top of the stack is also readable and writeable
through SFR registers. Data can also be pushed to or popped from the stack using
the top-of-stack SFRs. Status bits indicate if the stack pointer is at, or beyond the 31
levels provided.
Stack Operations
Figure 2.7 shows the bit struc ture of the STKPTR register. The STKPTR reg ister con-
tains the stack pointer value, as well as a stack full and stack underflow) status bits.
The STKPTR reg ister can be read and written by the user. This feature allows operat-
ing system software to perform stack maintenance op erations. The 5-bit value in the
stack pointer register ranges from 0 through 31, which correspond to the available
stack loca tions. The stack pointer is incremented by push op erations and decrement-
ed when val ues are popped off the stack. At RESET, the stack pointer value is set to 0.
bits: 7 6 5 4 3 2 1 0
STKOVF STKUNF SP4 SP3 SP2 SP1 SP0
bit 7 STKOVF:
1 = Stack became full or overflowed
0 = Stack has not overflowed
bit 6 STKUNF:
1 = Stack underflow occurred
0 = No stack underflow occurred
bit 5 Unimplemented: Read as 0
bit 4-0 SP4:SP0: Stack Pointer location
The STKOVF bit is set after the pro gram counter is pushed onto the stack 31
times without popping any value off the stack. No tice that some Microchip docu-
mentation refers to a STKFUL bit, which appears to be a syn onym for the STKOVF
bit. To avoid confusion, we only use the STKOVF designation in this book.
The STKOVF bit can only be cleared in software or by a Power-On Re set (POR)
operation. The action that takes place when the stack be comes full depends on the
state of the STVREN (Stack Overflow Reset Enable) configuration bit. The STVREN
bit is bit 0 of the CONFIG4L register. If the STVREN bit is set, a stack full or stack
overflow con dition will cause a de vice RESET. Other wise, the RESET ac tion will
not take place. When the stack pointer has a value of 0 and the stack is popped, a
value of zero is entered to the Pro gram Counter and the STKUNF bit is set. In this
case, the stack pointer remains at 0. The STKUNF bit will remain set until cleared in
software or a POR occurs. Returning a value of zero to the Pro gram Counter on an
underflow condition has the ef fect of vectoring the pro gram to the RESET vector.
User code can provide logic at the RESET vector to verify the stack condition and
take the appropriate actions.
Three reg isters, labeled TOSU, TOSH and TOSL, hold the contents of the stack lo-
ca tion pointed to by the STKPTR register. The address mapping of these registers is
shown in Figure 2.8.
Bits 20 15 7 0
Users can implement a software stack by manipulating the contents of the TOSU,
TOSH, and TOSL reg isters. After a CALL, RCALL, or interrupt, user software can
read the value in the stack by reading the TOSU, TOSH, and TOSL. These values can
then be placed on a user-defined software stack. At return time, user software can
replace the TOSU, TOSH, and TOSL with the stored val ues. At this time, global inter-
rupts should have been disabled in order to pre vent inadvertent stack changes.
A fast return from interrupts is available in the PIC18FXX2 devices. This action is
based on a Fast Register Stack that saves the STATUS, WREG, and BSR registers. The
fast ver sion of the stack is not readable or writable and is loaded with the current
value of the three registers when an interrupt takes place. The FAST RETURN instruc-
tion is then used to restore the working registers and ter minate the in terrupt.
PIC18 Architec ture 25
The fast reg ister stack op tion can also be used to store and re store the STATUS,
WREG, and BSR registers during a subroutine call. In this case, a fast call and fast
return instruction are executed. This is only possible if no interrupts are used.
Instructions in Memory
Program memory is structured in byte-size units but instructions are stored as two
bytes or four bytes. The Least Significant Byte of an instruction word is always stored
in a program memory location with an even address, as shown in Figure 2.5. Figure 2.9
shows three low-level instructions as they are en coded and stored in program memory
The CALL and GOTO instructions have an ab solute program memory address em-
bedded in the instruction. Because instructions are always stored on word bound-
aries, the data contained in the instruction is a word address. This word address is
written to Program Counter bits <20:1>, which accesses the desired byte address.
Notice in Figure 2.9 that the instruction
GOTO 000006H
is encoded by stor ing the number of single-word instructions that must be added to
the Program Counter (03H). All program branch instructions are encoded in this man-
ner.
GPR Bank 3
GPR Bank 4
Bank 6
Unused to
(read 00H) Bank 14
Unused Unused
080H Bank 15 080H Bank 15
FFFH SFR FFFH SFR
PIC18F442/242 PIC18F452/252
In Figure 2.10, GPRs start at the first location of Bank 0 and grow to higher mem-
ory addresses. Memory is divided into 255-byte units called banks. Seven banks are
implemented in the PIC18F452/252 devices and four banks in the PIC18F442/242 de-
vices. A read operation to a loca tion in an unimplemented mem ory bank always
returns zeros.
The entire data memory may be accessed directly or indirectly. Direct addressing
requires the use of the BSR register. Indirect addressing requires the use of a File
Select Register (FSRn) and a corresponding Indirect File Operand (INDFn). Ad-
dress ing op er a tions are dis cussed in Chap ter 11 in the cont ext of LCD
programming.
Each FSR holds a 12-bit address value that can be used to access any location in
the Data Memory map without banking. The SFRs start at address F80H in Bank 15
and extend to address 0FFFH in either device. This means that 128 bytes are as-
signed to the SFR area although not all loca tions are implemented. The individual
SFRs are discussed in the context of their spe cific functionality. Figure 2.11 shows
the names and addresses of the Special Function Registers.
PIC18 Architec ture 27
Schack, Lit. y art. dram. en Esp., I, pág. 258: "El principal obstáculo
que hasta entonces (los Rey. Catól.) se opuso al desarrollo del teatro
fué el insondable abismo que separaba á la poesía popular de la
erudita. Una vez allanado, los poetas más instruidos no creyeron
degradarse acudiendo á los elementos populares y agradando al
mismo tiempo al pueblo y á las clases más ilustradas; y así, pues,
recorrieron la única senda que podía llevar el drama á su perfección,
libre del exclusivismo que lo embargara hasta entonces". "En el año
de 1492, dice el Catálogo Real de España, de Rodrigo Méndez Silva
(Madrid, 1656), comenzaron en Castilla las compañías á representar
públicamente comedias por Juan del Encina, poeta de gran donaire,
graciosidad y entretenimiento". Otro tanto viene á decir Agustín de
Rojas, Viaje entret.: "Y donde mas ha subido | de quilates la
comedia | ha sido donde mas tarde | se ha alcanzado el uso de ella,
| que es nuestra madre España, | porque en la dichosa era | de
aquellos gloriosos reyes | dignos de memoria eterna, | don Fernando
é Isabel | que ya con los santos reynan, | ...se le dio á nuestra
comedia (principio) | Juan de la Encina el primero...". Del año 1515
es el Compendio de Retórica, de Nebrija, donde habla del teatro:
"De prueba sirven hasta los actores escenicos, que añaden tanta
gracia a las mejores obras poéticas, que nos deleitan mucho mas
recitadas que leidas; y aun con cosas vulgarísimas nos agradan y
fuerzan á atenderlas, de suerte que se oiga con frecuencia en los
teatros lo que nunca puede figurar en una biblioteca". Huberto
Thomas de Lüttich en sus Anales de vita et rebus gestis Friderici II,
Francof., 1624, habla de dramas en Barcelona y Perpiñán el año
1501: "Erigiose un cielo artificial, en el cual se veia tambien el
infierno, muy horrible y pavoroso. Representaronse allí muchas
historias, que duraron cerca de cuatro horas...".
Alude á los maderos largos, como los que se traían y se traen del
Norte, de Gales, y ocurriósele al Arcipreste lo de Gaula, por la voz
tabla, lo que indica que tenía la imaginación en la Tabla Redonda y
en el Amadís de Gaula, y por eso mete á Paula, por una dama
cualquiera. El Arcipreste compuso su libro el año 1343, como vimos,
de modo que ya para entonces era conocidísimo en España el
Amadís, no menos que el Tristán, del que habla en la copla 1703.
Pero ya en la corte de Alfonso X estaban de moda los "cantares de
Cornualla", y en el Amadís se ve la inspiración y aun la imitación de
las novelas del ciclo bretón, sobre todo del Tristán y de Lanzarote.
Bristoya es Bristol, Vindilisora es Windsor, aunque se dude de que
Bangil sea Bangor y Gravisanda, Gavesend. El asunto son los amores
de Amadís, hijo natural de Perión y de Elisena, con Oriana, hija de
Lisuarte, rey de Bretaña. Estos amoríos no son de cepa castellana, ni
mucho menos los encantamientos, apariciones, hadas, enanos,
gigantes, endriagos y batallas estupendas. La escena de hablarse
por la ventana viene del Lancelot francés. Sólo es castellano el
respeto á los reyes, las moralidades y cierto realismo de ejecución,
que templa el idealismo y maravillosismo, elementos nada
castellanos, y que son el alma de la novela caballeresca. La
delicadeza de los amores de Amadís y Oriana es lo mejor del libro.