Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Nicholas Amadori
21 dicembre 2004
Indice
2 Interfacing PICs 57
2.1 LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.2 Switch de-bounce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.3 Relais and Solenoids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
INDICE II
2.4 Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.5 RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3 Programmazione 64
3.1 Linguaggio Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.1.1 Direttive di compilazione . . . . . . . . . . . . . . . . . . . . . . . . 65
3.2 Linguaggio C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3.3 Application Maestro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.4 FilterLab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.5 MPLAB IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.5.1 Programmare e compilare . . . . . . . . . . . . . . . . . . . . . . . . 68
3.5.2 Simulare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.6 Programmare con l’ICD 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.7 Debug con l’ICD2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4 Esempi 72
4.1 Lampeggio LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.2 Generazione PWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.3 Controllore per motori stepper . . . . . . . . . . . . . . . . . . . . . . . . . 78
C Instruction sets 88
C.1 PIC16F84A e PIC16F87x . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
C.2 PIC18F45x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
D Glossary 94
Questo articolo vuole essere una introduzione al mondo dei microcontrollori PICmicro,
prodotti dalla Microchip a partire dagli anni ’80.
Oggi i microcontrollori sono presenti praticamente in ogni oggetto elettronico, dalle
radiosveglie ai forni a microonde. Negli ultimi anni si è assistito ad una sempre maggior
integrazione di funzioni all’interno di questi chip, fino ad arrivare a minuscole schede di
poche decine di cm2 con numerose porte di comunicazione seriali, decine di I/O digitali e
analogici e persino ethernet e stack TCP/IP integrato.
Nel variegato mondo dei microcontrollori i PICmicro si evidenziano per il grande nu-
mero di applicazioni industriali e domestiche in cui sono impiegati, per la mole di docu-
mentazione e codice sorgente che si può trovare su Internet, e per il basso costo per unità
che ne favorisce l’utilizzo per aplicazioni di larga scala. Oggi sono disponibili sul mercato
un gran numero di microcontrollori anche più potenti dei PICmicro1 , ma essendo soluzioni
più nuove sono spesso sistemi più “chiusi”, utilizzabili solamente con i sistemi di sviluppo
proprietari della casa, meno conosciuti e più costosi.
I microcontrollori, ed in particolar modo i PICmicro, si rivelano alleati formidabili
per gli studenti di informatica ed elettronica interessati a realizzare piccole applicazioni.
La loro versatilità permette di sostituire chip dedicati non sempre facilmente reperibili o
circuiti analogici, che in mancanza di esperienza possono dare non pochi grattaccapi, con
linee di codice sicuramente più familiari. Inoltre, grazie alle loro ridotte dimensioni e bassi
consumi, si rivelano preziosi nelle applicazioni di robotica mobile.
I capitoli di questa relazione che descrivono l’architettura e l’interfacciamento dei PIC-
micro sono stati scritti in inglese. Poichè tali parti si rifanno alla documentazione originale
della Microchip, si è scelto di evitare una traduzione che, per quanto corretta, avrebbe
reso meno immediata la descrizione rompendo la corrispondenza tra i nomi delle funzioni
ed i loro acronimi.
Il capitolo 1 (in inglese) dopo un introduzione sull’architettura dei PICmicro e le
famiglie di prodotti, descrive le funzioni del nucleo e delle periferiche. Nel capitolo 2 sono
presentati alcuni esempi di interfacciamento.
Il capitolo 3 descrive il processo di programmazione delle unità, a partire dalla stesura
del programma in linguaggio Assembly o C, alla simulazione, la programmazione fisica e
1
Per citarne alcuni: Atmel AVR, STMicroelectronics ST6 e ST9, Rabbit, Parallax BasicStamp, National
Semiconductor COP8, Zilog eZ80, Cyan technology eCOG1. Un confronto risalente al 1997 ma sempre
valido è presente sul sito della Microchip, application note AN520
ELENCO DELLE TABELLE 3
Questa relazione non sarebbe mai stata scritta senza l’aiuto di alcuni amici.
Grazie a Valerio, la cui passione e la voglia di fare (e il garage ;-) ) ci hanno fatto
muovere insieme i primi passi nel mondo dei microcontrollori.
Grazie a Riccardo e Giuseppe, che hanno reso piacevoli le ore trascorse insieme in
laboratorio, e hanno creduto in me fino ad utilizzare i PICmicro per le loro tesi di laurea.
Grazie al prof. Luca Zaccarian che mi ha permesso di impiegare questa mia passione
in ambito universitario, aprendo una nuova strada nel laboratorio di robotica.
Nicholas
Capitolo 1
1.1 Generalities
You don’t need to fully understand this section to use PICs, but having an overview of it’s
architecture can help in writing better software.
Architecture of PICMicro devices can be thought as a processor, storage
memory, data memory and peripherals all embedded in a single chip.
The high performance of the PICmicro devices can be attributed to a number of
architectural features commonly found in RISC microprocessors. These include:
• Harvard architecture
• Instruction Pipelining
Harvard Architecture
Harvard architecture has the program memory and data memory as separate memories
which are accessed from separate buses. This improves bandwidth over traditional von
Neumann architecture in which program and data are fetched from the same memory
1.1. GENERALITIES 6
PORTF
RF0
RF1
RF2
Synchronous RF3
CCPs Comparators USARTs
Serial Port RF4
RF5
RF6
RF7
Other Parallel
Modules Slave Port LCD Drivers
PORTG
RG0
RG1
RG2
RG3
RG4
Data EEPROM
Voltage up to RG5
Reference 256 x 8 RG6
RG7
Note 1: The high order bits of the Direct Address for the RAM are from the STATUS register.
2: Not all devices have this feature, please refer to device data sheet.
3: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions.
The multiplexing combinations are device dependent.
Harvard (PICmicro)
Von Neumann
8 Program
CPU and data
memory
using the same bus. To execute an instruction, a von Neumann machine must make one
or more (generally more) accesses across the 8-bit bus to fetch the instruction. Then data
may need to be fetched, operated on and possibly written. As can be seen from this
description, the bus can become extremely congested.
With a Harvard architecture, the instruction is fetched in a single instruction cycle
(all 12/16 bits). While the program memory is being accessed, the data memory is on an
independent bus and can be read and written. These separated busses allow one instruction
to execute, while the next instruction is fetched.
Long word instructions have a wider (more bits) instruction bus than the 8-bit data
memory bus. This is possible because the two buses are separate. This allows instructions
to be sized differently than the 8-bit wide data word and allows a more efficient use of
the program memory, since the program memory width is optimized to the architectural
requirements.
Typically in the von Neumann architecture, most instructions are multi-byte. In general,
a device with 4 KBytes of program memory would allow approximately 2K of instructions.
1.1. GENERALITIES 8
This 2:1 ratio is generalized and dependent on the application code. Since each instruction
may take multiple bytes, there is no assurance that each location is a valid instruction.
Single word instruction opcodes are 12/14/16-bits wide1 making it possible to have all
but a few instructions be single word instructions. A 16-bit wide program memory access
bus fetches a 16-bit instruction in a single cycle.With single word instructions, the number
of words of program memory locations equals the number of instructions for the device.
This means that all locations are valid instructions.
Some operations require more information then can be stored in the 16 bits of a program
memory location. These operations require a double word instruction, and are therefore
32-bits wide. The first word indicates to the CPU that the next program memory location
is the additional information for this instruction and not an instruction. If the CPU tries to
execute the second word of an instruction (due to a software modified PC pointing to that
location as an instruction), the fetched data is executed as a NOP. Double word instruction
execution is not split between the two TCY cycles by an interrupt request. That is, when an
interrupt request occurs during the execution of a double word instruction, the execution
of the instruction is completed before the processor vectors to the interrupt address. The
interrupt latency is preserved.
Instruction Pipeline
The instruction pipeline is a two-stage pipeline that overlaps the fetch and execution of
instructions. The fetch of the instruction takes one TCY, while the execution takes another
TCY. However, due to the overlap of the fetch of current instruction and execution of
previous instruction, an instruction is fetched and another instruction is executed every
TCY.
All instructions are single cycle, except for any program branches. These take two cycles since the fetch instruction
is “flushed” from the pipeline while the new instruction is being fetched and then executed.
1
see section 1.2.2
1.2. PIC FAMILIES 9
With the program memory bus being 12/14/16-bits wide, the entire instruction is fetched
in a single machine cycle (TCY), except for double word instructions which require two
cycles to execute. The instruction contains all the information required and is executed in
a single cycle. There may be a one cycle delay in execution if the result of the instruction
modified the contents of the program counter. This requires the pipeline to be flushed
and a new instruction to be fetched.
When an instruction set is well designed and highly orthogonal (symmetric), fewer in-
structions are required to perform all needed tasks. With fewer instructions, the whole
set can be more rapidly learned.
The register files/data memory can be directly or indirectly addressed. All special function
registers, including the program counter, are mapped in the data memory.
Orthogonal instructions make it possible to carry out any operation on any register using
any addressing mode. This symmetrical nature and lack of “special instructions” make
programming simple yet efficient. In addition, the learning curve is reduced significantly.
The Enhanced MCU instruction set uses only three non-register oriented instructions,
which are used for two of the cores features. One is the SLEEP instruction, which places
the device into the lowest power use mode. The second is the CLRWDT instruction, which
verifies the chip is operating properly by preventing the on-chip Watchdog Timer (WDT)
from overflowing and resetting the device. The third is the RESET instruction, which resets
the device.
Memory technology has no effect on the logical operation of a device. When discussing the
functionality of the device, the memory technology and the voltage range do not matter.
Microchip offers three program memory types. The memory type is designated in the part
number by the first letter(s) after the family affiliation designators.
ROM Devices
ROM devices have their program memory fixed at the time of the silicon manufacture.
Since the program memory cannot be changed, the device is usually housed in the low cost
plastic package. Microchip offers a masked Read Only Memory (ROM) version of several
of the highest volume parts, thus giving customers a lower cost option for high volume,
mature products.
EPROM Devices
EPROM devices can be erased and reprogrammed with an UV light source. These devices
are easily recognizable because of their ceramic package with a small quartz window that
exposes the internal silicon.
The amount of time required to completely erase a UV erasable device with a suitable
eraser is usually 10 to 20 minutes. Fluorescent lights and sunlight both emit ultraviolet
light at the erasure wavelength. Leaving a UV erasable device’s window uncovered could
cause, over time, the devices memory cells to become erased. The erasure time for a
fluorescent light is about three years, while sunlight requires only about one week. To
prevent the memory cells from losing data, an opaque label should be placed over the
erasure window.
These devices are electrically erasable, and are offered in a low cost plastic package. Being
electrically erasable, these devices can be both erased and reprogrammed without removal
from the circuit. A device will have the same specifications whether it is used for prototype
development, pilot programs, or production. These are the best for development, because
can be erased and reprogrammed in few seconds, allowing extensive test and debug of the
software. Such devices have a tipical life of 100.000 erase/write cycles.
PICmicro devices are grouped by the size of their Instruction Word. The three current
PICmicro families are:
The PIC12 family packs Microchip’s powerful RISC-based PICmicro architecture into 8-
pin DIP and SOIC packages. These products are available with either a 12-bit or 14-bit
wide instruction set, a low operating voltage of 2.5V, small package footprints, interrupt
handling, a deeper hardware stack, multiple A/D channels and EEPROM data memory.
These are the best when space or weight are priorities. Because of the low cost they can
be used to substitute discrete digital circuits with software logic.
The PIC16C5x is the well-established base-line family that offers the most cost-effective
solution. These PIC16C5x products have a 12-bit wide instruction set and are currently
offered in 14-, 18-, 20- and 28-pin packages. Low-voltage operation, down to 2.0V for
OTP MCUs, makes this family ideal for battery-operated applications. Additionally, the
PIC16HV5xx can operate up to 15 volts for use directly with a battery.
The PIC16xxxx family, the most used and most known, offers a wide-range of options,
from 18- to 68-pin packages as well as low to highest levels of peripheral integration, from
12 bit A/D converters to PWM, from USART to USB. This family has a 14-bit wide
instruction set, interrupt handling capability and a deep, 8-level hardware stack.
The PIC17Cxxx family extends the PICmicro MCU’s high-performance RISC architecture
with a 16-bit instruction word; enhanced instruction set and powerful vectored interrupt-
handling capabilities. A powerful array of precise on-chip peripheral features provides the
performance for the most demand in applications.
The PIC18xxxx is a family of high performance, CMOS, fully static MCUs with integra-
ted analog-to-digital (A/D) converter. It has enhanced core features, 32 level-deep stack,
and multiple internal and external interrupts sources. A total of 77 instructions (reduced
instruction set) are available. Additionally, a large register set gives some of the archi-
tectural innovations used to achieve a very high performance of 10 MIPS for an MCU.
The PIC18xxxx family has special features to reduce external components, thus redu-
cing cost, enhancing system reliability and reducing power consumption. These include
programmable Low Voltage Detect (LVD) and programmable Brown-Out Detect (BOD).
1.2. PIC FAMILIES 12
1.2.3 Packages
PICmicro devices are available in diferent packages. See figure 1.4 and 1.5
PDIP (Plastic Dual In-Line) is the most common package used in hand-made circuits.
Can be used on a breadbord, with a socket o soldered in place. Available from 8 to
64 pin.
CERDIP JW (Ceramic Dual In-Line) is a ceramic package with a quartz window used
for EPROM devices. It has the same pinout (size and spacing) of the PDIP package.
PLCC (Plastic Leaded Chip Carrer) is a square plastic package with smaller and narrower
pin than DIP. Can be soldered on a printed board or used with a suitable socket.
Available from 32 to 84 pins.
CERQUAD (Ceramic Chip Carrier), same as PLCC but in a ceramic windowed package.
SOIC, SSOP, QFP, TQFP, TSSOP Are different kind of surface mount packages.
These removes the necessity of drilling holes through the printed circuit board, but
can be soldered only with special tools, and can’t be used with sockets.
Microchip’s RISC-based PICmicro MCUs are designed for applications requiring high
performance and low cost. The PICmicro MCU portfolio is comprised of more than 140
products and features a variety of memory configurations, low voltage and power, small
footprint and ease-of-use. There is a great deal of “smarts” packed into a tiny space in
our minimal footprint MCUs.
As your designs grow in complexity, the code you write can be easily transitioned to
larger Microchip MCUs with more peripheral resources. A seamless product migration
path between PICmicro MCU families provides for complete upward compatibility in
embedded control designs.
To choose your MCU write down an outline of your project and see what are your
I/O needs. Then grab the latest Product Line Card from the microchip web site and find
what’s the most suitable. Because for a single unit price is not a factor of choice, my
suggestions are:
• if you need a compact device for simple tasks, choose the best PIC12C (PIC12C672
as 2002);
• if you need a generic middle-range device go for the universal PIC16F84A, or aim
at the PIC16F876A / PIC16F877A for plenty of memory and all sort of peripherals;
• if you have specific requirements you can look at PIC16C745 / 765 for USB,
PIC16C92x for LCD module, PIC16C77x for 12-bit ADC etc.;
• if you are looking for speed and features with no compromises, pick one from the
PIC18Fxxx family;
CERAMIC DUAL IN-LINE PLASTIC DUAL IN-LINE PLASTIC LEADED
CERDIP PDIP CHIP CARRIER
PLCC
1.2. PIC FAMILIES
8-LEAD PDIP
18-LEAD CERDIP “P” OR “PA”
“JW” 32-LEAD PLCC
28-LEAD PDIP “L”
“P” OR “PI”
14-LEAD PDIP
“P” OR “PD”
20-LEAD CERDIP 28-LEAD SKINNY PDIP
“JW” “SP” OR “PJ”
44-LEAD PLCC
“L” OR “W”
18-LEAD PDIP
“P”
28-LEAD CERDIP
“JW”
40-LEAD PDIP
20-LEAD PDIP “P” OR “PL”
“P”
68-LEAD PLCC
“L” OR “LS”
16-LEAD QSOP
8-LEAD SOIC 18-LEAD SOIC 14-LEAD SIDE BRAZED
(.208”) “SM” “SO” “JW”
64-LEAD TQFP
8-LEAD MSOP “PT”
“MS”
14-LEAD SOIC 20-LEAD SOIC 20-LEAD SIDE BRAZED
(.150”) “SL” OR “OD” “SO” “JW”
8-LEAD MSOP
“UA”
80-LEAD TQFP’
28-LEAD SOIC 28-LEAD SIDE BRAZED
“PT”
“SO” OR “OI”
(.300”) “JW”
PLASTIC THIN SHRINK
CHIP SCALE
SMALL OUTLINE SMALL OUTLINE TRANSISTOR
PACKAGES
“TSOP”
SOT-143
“RC” 3-LEAD SC-70
44-LEAD QFN
20-LEAD TSSOP
“ML”
(4.4MM) “ST”
14
1.3. CORE FEATURES 15
The core pertains to the basic features that are required to make the device operate. These
include:
• Oscillator
• Reset Logic
• Memory
• Configuration bits
• Watchdog timer
• Interrupts
The Central Processing Unit (CPU) is responsible for using the information in the program
memory (instructions) to control the operation of the device. It is responsible for fetching
the correct instruction for execution, decoding that instruction and then executing that
instruction. Many of these instructions operate on data memory. The CPU controls the
program memory address bus, the data memory address bus and accesses to the stack.
To operate on data memory, the Arithmetic Logical Unit (ALU) is required. In addition
to performing arithmetical and logical operations, the ALU controls the state of the status
bits, which are found in the STATUS register. The result of some instructions force status
bits to a value depending on the state of the result.
PICmicro devices contain an 8-bit ALU and an 8-bit working register (WREG). The
ALU is a general purpose arithmetic and logical unit. It performs arithmetic and boolean
functions between the data in the working register and any register file. The WREG register
is directly addressable and in the SFR memory map.
The ALU is 8-bits wide and is capable of addition, subtraction, multiplication, shift
and logical operations. Unless otherwise mentioned, arithmetic operations are two’s com-
plement in nature. In two-operand instructions, typically one operand is the working
register (WREG register). The other operand is a file register or an immediate constant.
In single operand instructions, the operand is either the WREG register or a file register.
Depending on the instruction executed, the ALU may affect the values of the Carry (C),
Digit Carry (DC), Zero (Z), Overflow (OV), and Negative (N) bits in the STATUS register.
The C and DC bits operate as a borrow bit and a digitborrow out bit, respectively, in
subtraction.
1.3. CORE FEATURES 16
8
8-bit register value Special
Function
8 (from direct or indirect Registers
W Register address of instruction)
(SFR’s)
and
8 8 General
Purpose
RAM
ALU (GPR)
8
d bit, or from instruction
d = '0' or d = '1'
Literal Instructions
The STATUS register contains the arithmetic status of the ALU. The STATUS register
can be the destination for any instruction, as with any other register. If the STATUS
register is the destination for an instruction that affects the Z, DC, C, OV or N bits, then
the write to these five bits is disabled. These bits are set or cleared according to the device
logic. Therefore, the result of an instruction with the STATUS register as destination may
be different than intended. For example, CLRF STATUS will clear the upper three bits and
set the Z bit. This leaves the STATUS register as 000u u1uu (where u = unchanged). It
is recommended, therefore, that only BCF, BSF, SWAPF, MOVFF, and MOVWF instructions are
used to alter the STATUS register, because these instructions do not affect the Z, C, DC,
OV or N bits of the STATUS register.
An 8x8 hardware multiplier is included in the ALU of some of the devices. By making
the multiplication a hardware operation, it completes in a single instruction cycle. This is
an unsigned multiplication that gives a 16-bit result. The result is stored into the 16-bit
Product register (PRODH:PRODL). The multiplier does not affect any flags in the ALUSTA
register.
Making the 8 x 8 multiplier execute in a single cycle gives higher computational throu-
ghput and reduces code size requirements for multiplication algorithms. The performance
1.3. CORE FEATURES 17
increase allows the device to be used in applications previously reserved for Digital Signal
Processors.
Example 1.7 shows the sequence to do an 8 x 8 unsigned multiply. Only one instruction
is required when one argument of the multiply is already loaded in the WREG register.
Example 1.8 shows the sequence to do an 8 x 8 signed multiply. To account for the
sign bits of the arguments, each argument’s most significant bit (MSb) is tested and the
appropriate subtractions are done.
1.3.3 Oscillator
The device clock is required for the device to execute instructions and for the peripherals
to function. Four device clock periods (TSCLK) generate one internal instruction clock
(TCY) cycle.
The clock input is internally divided by four to generate four non-overlapping quadra-
ture clocks, namely Q1, Q2, Q3 and Q4. Internally, the program counter is incremented
every Q1, and the instruction is fetched from the program memory and latched into the
instruction register in Q4. The instruction is decoded and executed during the following
Q1 through Q4.
Basically you can choose between three clock sources:
• Crystal
• External RC
• Internal RC
1.3. CORE FEATURES 18
Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4
Tosc
Using a crystal ensures the maximum stability and precision in clock frequency,
therefore in istruction timing. You must use a crystal to have reliable serial comunications.
The external RC is a cost-effective solution when you don’t need such precision and
can tolerate some shift in timings.
The internal RC is available on some low pin-count devices as the PIC12 series, to
save pins for I/O functions and board space. Such devices need no external components
to work.
Some devices can also use Timer1 Oscillator as a low frequency low power clock
source during sleep status, or multiply the clock by 4 with a Phase Lock Loop (PLL),
making the internal instruction clock (TCY) equal to the external clock.
Crystal Oscillator
The PICmicros internal oscillator circuit is a parallel oscillator circuit, which requires that
a parallel resonant crystal be selected. The load capacitance is usually specified in the
20 pF to 32 pF range. The crystal will oscillate closest to the desired frequency with
capacitance in this range.
Clock mode is primarily chosen by using the FOSC parameter specification (parameter
1A) in the device’s data sheet, based on frequency. Clock modes are simply gain selections,
lower gain for lower frequencies, higher gain for higher frequencies. It is possible to select
a higher or lower gain, if desired, based on the specific needs of the oscillator circuit.
The OSC2 signal should be a nice clean sine wave that easily spans the input minimum
and maximum of the clock input pin (4V to 5V peak to peak for a 5V VDD is usually
good). An easy way to set this is to again test the circuit at the minimum temperature and
maximum VDD that the design will be expected to perform in, then look at the output.
This should be the maximum amplitude of the clock output.
If there is clipping or the sine wave is squashing near VDD and VSS at the top and
bottom, and increasing load capacitors will risk too much current through the crystal or
push the value too far from the manufacturer’s load specification, then add a trimpot
between the output pin and C2, and adjust it until the sine wave is clean. Try to get a
1.3. CORE FEATURES 19
combination where Rs is around 10k or less, and load capacitance is not too far from the
20 pF or 32 pF manufacturer specification. Remember that a scope probe adds its own
capacitance to the circuit, so this may have to be accounted for in your design, i.e. if the
circuit worked best with a C2 of 20 pF and scope probe was 10 pF, a 30 pF capacitor may
actually be called for. The output signal should not be clipping or squashed. Overdriving
the crystal can also lead to the circuit jumping to a higher harmonic level or even crystal
damage.
Application Note AN588 is an excellent reference if you would like to know more about
crystal operation and their ordering information.You may also check Fact Sheet 00838a.
A typical oscillator circuit is made by a 4MHz crystal and two 22 pF capacitors.
OSC1
C1 (3)
To internal logic
XTAL SLEEP
RF (2)
OSC2
Rs (1)
C2 To internal logic (3)
PIC16CXXX
Note 1: A series resistor, RS, may be required for AT strip cut crystals.
2: The feedback resistor, RF, is typically in the range of 2 to 10 MΩ.
3: Depending on the device, the buffer to the internal logic may be
either before or after the oscillator inverter.
External RC Oscillator
For timing insensitive applications, the RC and RCIO device options offer additional cost
savings. The RC oscillator frequency is a function of the:
• Supply voltage
• Operating temperature
In addition to this, the oscillator frequency will vary from unit to unit due to normal
process parameter variation. The user also needs to take into account variation due to
tolerance of external REXT and CEXT components used. Figure 1.11 shows how the
1.3. CORE FEATURES 20
RC combination is connected. For REXT values below 2.2 kΩ, oscillator operation may
become unstable, or stop completely. For very high REXT values (e.g. 1 MΩ), the
oscillator becomes sensitive to noise, humidity and leakage. Thus, we recommend keeping
REXT between 3 kΩ and 100 kΩ.
V DD
REXT
Internal
OSC1 Fosc
clock
CEXT PIC16CXXX
VSS
Fosc/4 (1)
Note 1: This output may also be able to be configured as a general purpose I/O pin.
Although the oscillator will operate with no external capacitor (CEXT = 0 pF), we
recommend using values above 20 pF for noise and stability reasons. With no or a small
external capacitance, the oscillation frequency can vary dramatically. See characterization
data for the variation of oscillator frequency due to VDD for given REXT/CEXT values,
as well as frequency variation due to operating temperature for given REXT, CEXT and
VDD values.
The oscillator frequency, divided by 4, is available on the OSC2/CLKO pin, and can
be used for test purposes or to synchronize other logic. On some devices the OSC2/CLKO
pin can be configured as generic I/O pin.
The internal RC oscillator (not on all devices) provides a fixed 4 MHz (nominal) system
clock at VDD = 5V and 25◦ C. The value in the OSCCAL register is used to tune the
frequency of the internal RC oscillator. The calibration value that Microchip programs
into the device will “trim” the internal oscillator to remove process variation from the
oscillator frequency. Upon a device reset, the OSCCAL register is forced to the midpoint
value.
A calibration instruction is programmed into the last address of the implemented
program memory. This instruction contains the calibration value for the internal RC
oscillator. This value is programmed as a RETLW XX instruction where XX is the calibration
value. In order to retrieve the calibration value, issue a CALL YY instruction where YY is
the last location in the device’s user accessible program memory. The calibration value
1.3. CORE FEATURES 21
900
R = 3.3k
800
700
Fosc (kHz)
600 R = 5k
500
400
R = 10k
300
200
100 R = 100k
0
2.5 3.0 3.5 4.0 4.5 5.0 5.5
VDD (Volts)
is now loaded in the W register. The program should then perform a MOVWF OSCCAL
instruction to load the value into the internal RC oscillator calibration register.
The internal RC oscillator can be configured to provide a clock out signal on the
CLKOUT pin. When the calibration value of the internal RC oscillator is accidently
erased, the clock out feature allows the user to determine what the calibration value
should be. This is achieved by writing a program which modifies (increments/decrements)
the value of the OSCCAL register. When the CLKOUT pin is at 4 MHz (± 1.5%) at 5V
and 25◦ C, the OSCCAL register has the correct calibration value. This value then needs
to be written to a port or shifted out serially, so that the value can be written down and
programmed into the calibration location.
The reset logic is used to place the device into a known state. Devices differentiate between
various kinds of reset:
• MCLR Reset
• RESET Instruction
1.3. CORE FEATURES 22
Average
CEXT R EXT
Fosc @ 5V, 25°C
Most registers are unaffected by a reset; their status is unknown on POR and unchan-
ged by all other resets2 . The other registers are forced to a “reset state” on Power-on
Reset, MCLR, WDT Reset, Brown-out Reset, MCLR Reset during SLEEP and by the
RESET instruction. Most registers are not affected by a WDT wake-up, since this is viewed
as the resumption of normal operation. Status bits from the RCON register are used in
software to determine the nature of the reset.
A simple configuration used to ensure a safe startup in standard conditions is made
by tying the MCLR pin to Vdd as shown in figure 1.13, with an optional reset button. If
you’re planning to use ICSP, see section 1.5.
A resistor of 1 to 10 kΩ is probably appropriate; the input is CMOS and does not
draw any current through the resistor. The resistor is primarily used as a current-limiting
device for the momentary-on switch. In the configuration registers of the mid-range parts
there is a bit known as PWRTE. This bit will insert a 72-ms delay during PICmicro MCU
power up before the first instruction is fetched and executed. The purpose of this function
is to allow the PICmicro’s clock to stabilize before the application starts.
You must use a different configuration3 with slow Vdd rise time or noisy power sources.
2
see the family datasheets for the reset status of each register
3
see Application Notes AN522 and AN607 from Microchip web site for a thorough explanation of
power-up sequence
1.3. CORE FEATURES 23
VDD
VDD
(1)
R
MCLR
PIC18CXXX
There are two memory blocks in the memory map: program memory and data memory.
Each block has its own bus, so that access to each block can occur during the same
instruction cycle. The data memory can further be broken down into General Purpose
RAM and the Special Function Registers (SFRs). The operation of the SFRs that control
the “core” are described here. The SFRs used to control the peripheral modules are
described in the section discussing each individual peripheral module.
In addition, there are other registers used that are neither part of the program nor data
memory spaces. These registers are not directly addressable and include return address
stack and fast return stack.
Program memory
The program memory contains instructions for execution and data tables for storing fixed
data. Data tables may be written once using table write instructions and read as required,
using the table read instructions. The program space is implemented as a single contiguous
block.
The reset vector4 (the address that program execution will branch to when a device
reset occurs) is at address 000000h, the high priority interrupt vector is at address
000008h, and the low priority interrupt vector is at address 000018h. In the Mid-
range family the interrupt vector is at address 0004h. CALL and GOTO instructions can
address any location in the memory map, while the BRA and RCALL instructions have
a limited program memory reach (+1024, -1023 program memory word locations). To
allow the CALL and GOTO instructions to contain the entire address, it requires that these
instructions use 2 program memory words (2 word instruction).
Instructions are also available to move information between the data memory and the
program memory areas. These are called table operations 5 . Table operations work with
byte entities.
4
for details on interrupts see section 1.3.10
5
for details on table operations see section 1.3.9
1.3. CORE FEATURES 24
The Program Counter (PC) specifies the address of the instruction to fetch for
execution.
Mid-Range MCU devices have a 13-bit program counter capable of addressing
an 8K x 14 program memory space. The width of the program memory bus (instruction
word) is 14-bits. Since all instructions are a single word, a device with an 8K x 14 program
memory has space for 8K of instructions. This makes it much easier to determine if a device
has sufficient program memory for a desired application.
PCLATH
Stack Level 1
Stack Level 8
Note 1: Not all devices implement the entire program memory space
2: Calibration Data may be programmed into program memory locations.
This program memory space is divided into four pages of 2K words each (0h - 7FFh,
800h - FFFh, 1000h - 17FFh, and 1800h - 1FFFh). Figure 1.14 shows the program memory
1.3. CORE FEATURES 25
map as well as the 8 level deep hardware stack. Depending on the device, only a portion
of this memory may be implemented.
To jump between the program memory pages, the high bits of the Program Counter
(PC) must be modified. This is done by writing the desired value into a SFR called PCLATH
(Program Counter Latch High). If sequential instructions are executed, the program
counter will cross the page boundaries without any user intervention. For devices that
have less than 8K words, accessing a location above the physically implemented address
will cause a wraparound (that is, in a 4K-word device accessing 17FFh actually addresses
7FFh). 2K-word devices (or less) do not require paging.
ORG 0x500
BSF PCLATH, 3 ; Select Page1 (800h-FFFh)
CALL SUB1_P1 ; Call subroutine in Page1 (800h-FFFh)
:
:
ORG 0x900
SUB1_P1: ; called subroutine Page1 (800h-FFFh)
:
RETURN ; return to Call subroutine in Page0 (000h-7FFh)
In the PIC18x family the PC is 21-bits wide and addresses each byte (rather than
words) in the program memory. The low byte is called the PCL register (PC<7:0>). This
register is readable and writable. The high byte is called the PCH register (PC<15:8>). This
register is not directly readable or writable. Updates to the PCH register may be performed
through the PCLATH register. The upper byte is called the PCU register (PC<20:16>). The
PCU register is not directly readable or writable. Updates to the PCU register may be per-
formed through the PCLATU register. The PC structure is PCU<4:0>:PCH<7:0>:PCL<7:0>
and is equivalent to PC<20:0>.
The stack allows program calls and interrupts to occur. The stack contains the return
address from this branch in program execution. Enhanced MCU devices have an 31-level
deep x 21-bit wide hardware stack. Mid-Range MCU devices have an 8-level deep x 13-bit
wide hardware stack. The stack space is not part of either program or data space and the
stack pointer is not readable nor writable. The PC is PUSHed onto the stack when a CALL
instruction is executed or an interrupt causes a branch. The stack is POPed in the event
of a RETURN, RETLW or a RETFIE instruction execution. PCLATH is not modified when the
stack is PUSHed or POPed. There are no explicit PUSH or POP instructions.
There is a subtle difference in stack behaviour when an overflow occurs between the
mid-range and the enhanced families. In the Mid-range family, after the stack has been
PUSHed eight times, the ninth push overwrites the value that was stored from the first
push. The tenth push overwrites the second push (and so on). There are no status bits
to indicate stack overflow or stack underflow conditions. In the Enhanced MCUs, after
the PC is PUSHed onto the stack 31 times (without POPing any values off the stack),
1.3. CORE FEATURES 26
PCLATU PCLATH
23 21 20 16 15 8 7 0
the 32nd PUSH over-writes the value from the last push (the 31st) and sets the STKFUL
bit while the STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and
so on) while STKPTR remains 11111b. When the stack overflow enable bit is enabled a
device reset will occur.
Data memory
Data memory is made up of the Special Function Registers (SFR) area and the General
Purpose Registers (GPR) area. The SFRs are used for control and status of the micro-
controller and peripheral functions, while GPRs are the general area for user data storage
and scratch pad operations. This memory is partitioned into banks. To directly access to
a specific memory location you must select the right bank. In the mid-range family you
must select the right bank by setting bits STATUS<RP1:RP0> for direct memory access, or
by setting bit STATUS,IRP for indirect access. In the 18 family for direct access you must
select the right bank in BSR<3:0>, while indirect access does not require bank selection.
Special Function Registers are used by the CPU and peripheral modules for con-
trolling the desired operation of the device. These registers are implemented as static
RAM. The SFRs can be classified into two sets; those associated with the “core” function
and those related to the peripheral functions.
Unfortunately in mid-range PICs SFRs are distributed in the first location across
banks6 . You must ensure always to select the right bank prior trying to read or write to
any register. The MPLAB compiler doesn’t help too much, nothing more than giving a
warning for every istruction that accesses SFRs in banks different than bank 0, without
doing any check. You must take care of saving the status of the bank select bits when
servicing interrupts.
Things are easier in the PIC18 family, where SFRs are mapped in a special way called
Access Bank, available regardless of the BSR setting. You can use also some unassigned
6
please refer to the device data sheet for that device’s register map
1.3. CORE FEATURES 27
locations in the Access Bank for your own variables, but using that can compromise
portability to future devices.
General Purpose Registers (GPR) are not initialized by a Power-on Reset and are
unchanged on all other resets. The register file can be accessed either directly, or indirectly,
using the File Select Register (FSR). Some devices have areas that are shared across the
data memory banks, so a read/write to that area will appear as the same location (value),
regardless of the current bank. We refer to this area as the Common RAM.
The device configuration bits allow each user to customize certain aspects of the device to
the needs of the application. When the device powers up, the state of these bits determines
the modes that the device uses. To know what features are supported by your specific
device, please see it’s datasheet.
Microchip’s assembler, MPASM, has a nice feature (directives) that allows you to spe-
cify the device configuration in the source code file. This ensures that when programming
a device for an application, the required configuration is also programmed. This minimizes
the risk of programming the wrong device configuration and then wondering why it no
longer works in the application.
As long as the correct device is specified (in the LIST and INCLUDE file directives),
the correct polarity of all bits is ensured.
The Watchdog Timer may be used to return to operating mode, or to cause a controller
RESET if the program begins to behave erratically. This enhances the overall operation
of the system.
The Watchdog Timer (WDT) is a free running on-chip RC oscillator that does not
require any external components. This RC oscillator is separate from the device RC
oscillator of the OSC1/CLKI pin. The Watchdog Timer (WDT) is enabled/disabled by a
device configuration bit. If the WDT is enabled, software execution may not disable this
function. When the WDTEN configuration bit is cleared, the SWDTEN bit enables/disables
the operation of the WDT. During normal operation, a WDT time-out generates a device
reset. If the device is in sleep mode, a WDT time-out causes the device to wake-up and
continue with normal operation. This is known as a WDT wake-up.
The WDT has a nominal time-out period which varies with temperature, VDD and
process variations from part to part. If longer time-outs are desired, a postscaler with a
division ratio of up to 1:128 can be assigned to the WDT. It should also be taken in account
that under worst case conditions (VDD = Minimum, Temperature = Maximum, WDT
postscaler = Maximum), it may take several seconds before a WDT time-out occurs. The
CLRWDT and SLEEP instructions clear the WDT counter and the WDT postscaler which
prevents it from timing out and generating a device reset.
The CLRWDT instruction will force the count value of the WDT counter to ’0’.
1.3. CORE FEATURES 28
end
Figura 1.17: Example: Specify configuration bits using the CONFIG directive
The SLEEP function halts controller activity and reduces current consumption to a mini-
mum. The sleep mode is a reduced power state, where it is possible to halt almost all
activity in the controller. In this mode, power consumption is very low, allowing for long
term operation from battery powered applications.
The device oscillator is turned off, so no system clocks are occurring in the device. If
enabled, theWatchdog Timer will be cleared but keeps running, the I/O ports maintain
the status they had before the SLEEP instruction was executed (driving high, low, or
hi-impedance).
The device can wake-up from sleep through one of the following events:
• Any peripheral module which can set its interrupt flag while in sleep.
The first event will reset the device upon wake-up. However, the latter two events will
wake the device and then resume program execution.
1.3. CORE FEATURES 29
For the device to wake-up through an interrupt event, the corresponding interrupt
enable bit must be set (enabled). Wake-up is regardless of the state of the GIE bit. If
the GIE bit is clear (disabled), the device continues execution at the instruction after the
SLEEP instruction. If the GIE bit is set (enabled), the device executes the instruction after
the SLEEP instruction and then branches to the interrupt address. This way, interrupt
sources can wake the controller from sleep without actually causing an interrupt.
During sleep, some of the peripherals works, some works partially, some not. See the
reference manual for your particolar application.
Enhanced devices have two memory spaces. The program memory space and the data
memory space. The program memory space is 16 bits wide, while the data memory space
is 8 bits wide. Table Reads and Table Writes have been provided to move data between
these two memory spaces through an 8-bit register (TABLAT).
For more details see the 18F family datasheet, or AN556 (Implementing a Table Read).
1.3.10 Interrupts
Interrupts can come from many sources. These sources currently include:
• Timer overflow
When a valid interrupt occurs, program execution vectors to one of these interrupt
vector addresses and the corresponding Global Interrupt Enable bit (GIE, GIEH, or GIEL)
is automatically cleared. In the interrupt service routine, the source(s) of the interrupt
can be determined by testing the interrupt flag bits. The interrupt flag bit(s) must be
cleared before re-enabling interrupts to avoid infinite interrupt requests. Most flag bits
are required to be cleared by the application software. There are some flag bits that
are automatically cleared by the hardware. When an interrupt condition is met, that
individual interrupt flag bit will be set regardless of the status of its corresponding mask
bit.
The “return from interrupt“ instruction, RETFIE, can be used to mark the end of the
interrupt service routine. When this instruction is executed, the stack is “POPed” and
the GIE bit is set (to re-enable interrupts).
Generally devices have a minimum of four registers associated with interrupts. The
INTCON register contains the Global Interrupt Enable bit, GIE, as well as the Peripheral
1.4. PERIPHERALS 30
Interrupt Enable bit, PEIE, the PIE / PIR register pair that enables the peripheral inter-
rupts and displays the interrupt flag status, and the Interrupt Priority Register IPR that
controls whether the interrupt source is a high priority or low priority interrupt.
Always use the symbolic names of the bits to avoid problems when recompiling the
code for a different device. This will allow the Assembler/Compiler to automatically take
care of the placement of these bits by specifying the correct Register number and bit name.
The PIE registers contain the individual enable bits for the peripheral interrupts.
The PIR registers contain the individual flag bits for the peripheral interrupts. In-
terrupt flag bits are set when an interrupt condition occurs, regardless of the state of its
corresponding enable bit or the global enable bit. User software should ensure the appro-
priate interrupt flag bits are cleared prior to enabling an interrupt and after servicing that
interrupt.
The IPR registers (18F) contain the individual priority bits for the peripheral inter-
rupts.
In the PIC18 family there are two interrupt vectors, one for high priority interrupts, the
other for low priority interrupts. Each interrupt can be assigned a priority level by clearing
or setting the corresponding interrupt priority bit located in the interrupt priority registers
(IPR and INTCON). A ‘1’ in the priority register assigns high priority to the corresponding
interrupt. A ‘0’ in the register assigns low priority to the interrupt. All interrupt are
assigned high priority at reset. The IPEN bit in the RCON register enables priority levels
for interrupts. If clear, all priorities are set to high.
If a high priority interrupt occurs while servicing a low priority interrupt, the high
priority interrupt will cause the low priority ISR to be interrupted. A low priority interrupt
cannot interrupt a high priority ISR. The low priority interrupt will be served after all
high priority interrupts have been served. If a high priority interrupt and a low priority
interrupt are sampled at the same time, the high priority interrupt service routine is always
serviced first.
If you need the exact interrupt latency see the family datasheet.
1.4 Peripherals
Peripherals are the features that add a differentiation from a microprocessor. These ease
in interfacing to the external world (such as general purpose I/O, A/D inputs, and PWM
outputs), and internal tasks, such as keeping different time bases (i.e. timers). The
peripherals that are discussed are:
• Generic I/O
• Timers
;
; High Priority Interrupt Service Routine (ISR) Code goes here
;
RETFIE 0x00
;
; Low Priority Interrupt Service Routine (ISR) code goes here
;
RETFIE 0x00
RIVEDERE
CLRF INTCON3
CLRF INTCON2
MOVLW OxC0 ; Enable high and low global interrupts.
MOVWF INTCON
• Voltage References
• Comparators
• A/D converters
• USB
General purpose I/O pins can be considered the simplest of peripherals. They allow the
PICmicro to monitor and control other devices. To add flexibility and functionality to a
device, some pins are multiplexed with alternate functions. These functions depend on
which peripheral features are on the device. In general, when a peripheral is functioning,
that pin may not be used as a general purpose I/O pin.
For most ports, the I/O pin’s direction (input or output) is controlled by the data
direction register, called the TRIS register. TRISx<y> controls the direction of PORTx<y>.
A ‘1’ in the TRIS bit corresponds to that pin being an input, while a ‘0’ corresponds to
that pin being an output. An easy way to remember is that a ‘1’ looks like an I (input)
and a ‘0’ looks like an O (output).
1.4. PERIPHERALS 33
When enabling peripheral functions, care should be taken in defining TRIS bits for
each port pin. Some peripherals override the TRIS bit to make a pin an output, while
other peripherals override the TRIS bit to make a pin an input, and other peripherals may
not override the TRIS bits (requires that TRIS bits are configured for proper peripheral
operation). The user should refer to the corresponding peripheral section in the device
datasheet for the correct TRIS bit settings. A read from the TRIS register bits will always
yield the value contained in the TRIS latch whether or not a peripheral is overriding the
setting.
The PORT register7 is the latch for the data to be output. When the PORT is read, the
device reads the levels present on the I/O pins (not the latch). This means that care should
be taken with read-modify-write commands on the ports8 and changing the direction of a
pin from an input to an output. Figure 1.20 shows a typical I/O port. This does not take
into account peripheral functions that may be multiplexed onto the I/O pin. Reading the
PORT register reads the status of the pins whereas writing to it will write to the port latch.
All write operations (such as BSF and BCF instructions) are read-modify-write operations.
Therefore a write to a port implies that the port pins are read, this value is modified, and
then written to the port data latch.
PORTA
PORTA is a 5-7 bit latch. The corresponding data direction register is TRISA, the data
output latch is PORTA (LATA), and the pins are PORTA. Except for RA4, all PORTA pins
have TTL input buffers and full CMOS output drivers. All pins are configured as inputs
on a reset.
The RA4 pin is a Schmitt Trigger input and an open drain output. All other RA port
pins have TTL input levels and full CMOS output drivers. All pins have data direction
bits (TRIS registers) which can configure these pins as output or input. Setting a TRISA
register bit puts the corresponding output driver in a hi-impedance mode. Clearing a bit
in the TRISA register puts the contents of the output latch on the selected pin(s).
On some devices PORTA pins can be multiplexed with the A/D converters.
PORTB
PORTB is an 8-bit wide bi-directional port. The corresponding data direction register is
TRISB, the data output latch is PORTB (LATB), and the pins are PORTB. All pins have
TTL inputs. Setting a bit in the TRISB register puts the corresponding output driver in a
high-impedance input mode. Clearing a bit in the TRISB register puts the contents of the
output latch on the selected pin(s). All pins are configured as inputs on a reset.
Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on
all the pull-ups. This is performed by clearing bit RBPU. The weak pull-up is automati-
7
in the 18F family the PORTx register is also called LATx
8
when you modify a bit in the PORT register, the real status of the whole port is read, the bit is
modified and the result is written back. This can be an issue with successive high-speed port operation if
the capacitance of the circuit is too high. See the reference manual for a thorough explanation.
1.4. PERIPHERALS 34
Data bus
D Q
VDD
WR PORT
CK Q
P
Data Latch
I/O pin
D Q
N
WR TRIS
CK Q VSS
TRIS Latch
TTL or
Schmitt
Trigger
RD TRIS
Q D
EN
RD PORT
cally turned off when the port pin is configured as an output. The pull-ups are disabled
on a Power-on Reset.
Four of PORTB’s pins, RB7:RB4, have an interrupt on change feature. Only pins
configured as inputs can cause this interrupt to occur (i.e. any RB7:RB4 pin configured
as an output is excluded from the interrupt on change comparison). The input pins (of
RB7:RB4) are compared with the old value latched on the last read of PORTB. The present
inputs of RB7:RB4 and their previous values are XOR’ed together to detect a “mismatch”
condition and set the RB Port change interrupt flag bit RBIF. When enabled, this flag
will generate an interrupt that can wake the device from sleep.
The user, in the interrupt service routine, can clear the interrupt in the following
manner:
• Any read or write of PORTB. This will end the mismatch condition.9
A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the
mismatch condition, and allow flag bit RBIF to be cleared.
This interrupt on mismatch feature, together with software configurable pull-ups on
these four pins allow easy interface to a keypad and make it possible for wake-up on key-
depression. The interrupt on change feature is recommended for wake-up on key depression
and operations where PORTB is only used for the interrupt on change feature. Polling of
PORTB is not recommended while using the interrupt on change feature.
PORTF
If the device have an LCD segment driver, PORTF is a digital input only port, and each
pin is multiplexed with an LCD segment driver. These pins have Schmitt Trigger input
buffers. Otherwise PORTF is an 8-bit bi-directional port with Schmitt Trigger input
buffers, with each pin individually configured as an input or output.
1.4.2 Timers
In every PIC there is at least a basic 8-bit timer/counter (namely Timer0) with the
following features:
• 8-bit timer/counter
VDD
RBPU(2) weak
P pull-up
Data Latch
Data bus
D Q
WR Port I/O
CK pin(1)
TRIS Latch
D Q
TTL
WR TRIS Input
CK Buffer
RD TRIS
Q D
RD Port EN
To Peripheral Module
In timer mode, the Timer0 module will increment every instruction cycle (without
prescaler). If the TMR0 register is written, the increment is inhibited for the following
two instruction cycles. The user can work around this by writing an adjusted value to the
TMR0 register.
Timer0 and the watchdog timer share the same prescaler. A prescaler assignment for
the Timer0 module means that there is no postscaler for the Watchdog Timer, and vice-
versa. The prescaler assignment is fully under software control, i.e., it can be changed “on
the fly” during program execution10 .
10
To avoid an unintended device reset, a precise instruction sequence must be executed when changing
the prescaler assignment from Timer0 to the WDT even if the WDT is disabled. See the family datasheet.
1.4. PERIPHERALS 37
Data bus
FOSC/4 0
PSout 8
1
Sync with
1 Internal TMR0
clocks
T0CKI pin Programmable 0 PSout
Prescaler
T0SE (2 cycle delay)
3
Set interrupt
PS2, PS1, PS0 PSA flag bit T0IF
T0CS on overflow
Counter mode is selected by setting the T0CS bit (OPTION register). In counter
mode, Timer0 will increment either on every rising or falling edge of the T0CKI pin. The
incrementing edge is determined by the Timer0 Source Edge Select the T0SE bit. Clearing
the T0SE bit selects the rising edge. Restrictions on the external clock input are discussed
in detail in the family reference manual.
The TMR0 interrupt cannot awaken the processor from sleep since the timer is shut-off
during sleep.
In addiction to this, there can be addictional timer/counter modules (TIMER1, TI-
MER2, TIMER3).
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H:TMR1L),
increments from 0000h to FFFFh and rolls over to 0000h. If enabled, the Timer1 Interrupt
is generated on overflow that is latched in the TMR1IF interrupt flag bit. Timer1 can
operate in one of three modes:
• As a synchronous timer
1.4. PERIPHERALS 38
• As a synchronous counter
• As an asynchronous counter
In timer mode, Timer1 increments every instruction cycle. In counter mode, it incre-
ments on every rising edge of the external clock input pin T1OSI. It has the capability
to operate off an external crystal. When the Timer1 oscillator is enabled (T1OSCEN is
set), the T1OSI and T1OSO pins become inputs, so their corresponding TRIS values are
ignored.
Timer2 is an 8-bit timer with a prescaler, a postscaler and a period register. Using
the prescaler and postscaler at their maximum settings, the overflow time is the same as
a 16-bit timer. Timer2 is the PWM time-base when the CCP module(s) is used in the
PWM mode.
The Timer3 module is same as Timer1, used as the alternate time base for captu-
re/compare operations. The Timer3 module also has a software programmable prescaler.
For detailed timing diagrams and related problematics see the Family Reference Ma-
nual and the device datasheet.
• Capture mode;
• Compare mode;
• PWM mode;
Each CCP (Capture/Compare/PWM) module has three 8-bit registers. These are:
Multiple CCP modules may exist on a single device. The CCP modules are identical
in operation, with the exception of the operation of the special event trigger. Because
multiple CCP modules must share the timers available on the MCU, there are some
restriction on the use of the two units, as in table 1.2.
1.4. PERIPHERALS 39
Capture mode
In Capture mode, CCPRxH:CCPRxL captures the 16-bit value of the TMR1 register when
an event occurs on pin CCPx. An event is defined as:
When a capture is made, the interrupt request flag bit, CCPxIF, is set. If another
capture occurs before the value in register CCPRx is read, the previous captured value will
be lost. A capture does not reset the 16-bit TMR1H:TMR1L register. The time between
two captures can easily be computed as the difference between the value of the second
capture that of the first capture.
In Capture mode, the CCPx pin should be configured as an input by setting its cor-
responding TRIS bit. Timer1 must be running in timer mode or synchronized counter
mode; in asynchronous counter mode, the capture operation may not work.
Compare mode
In Compare mode, the 16-bit CCPRx register value is constantly compared against the
TMR1 register pair value. When a match occurs, the CCPx pin is:
1.4. PERIPHERALS 40
• Driven High
• Driven Low
PWM mode
In Pulse Width Modulation (PWM) mode, the CCPx pin produces up to a 10-bit reso-
lution PWM output. Since the CCPx pin is multiplexed with the PORT data latch, the
corresponding TRIS bit must be cleared to make the CCPx pin an output.
DutyCycle = DCxB9:DCxB0
Period = PR2 + 1
1 2 3
1 Timer2 is cleared and new duty cycle value is loaded from the Duty Cycle latch into the
Duty Cycle Slave register
2 Timer2 value equals to value in Duty Cycle Latch register, CCP Pin is driven low
3 Timer2 overflow, value from Duty Cycle Latch is loaded into Slave Register, CCP Pin driven high
The PWM period is specified by writing to the PR2 register. The PWM period can
be calculated using the following formula:
11
only in PIC18F family
1.4. PERIPHERALS 41
The PWM duty cycle is specified by writing to the CCPRxL register and to the DCxB<1:0>
bits. Up to 10-bit resolution is available: the CCPRxL contains the eight MSbs and
CCPxCON<5:4> contains the two LSbs. This 10-bit value is represented by DCxB9:0.
The following equation is used to calculate the PWM duty cycle:
PWMdutycycle = (DCxB < 9 : 0 > bits value) ∗ Tosc ∗ (TMR2 prescale value)
The DCxB9:0 bits can be written to at any time, but the duty cycle value is not latched
into CCPRxH until after a match between PR2 and TMR2 occurs (which is the end of the
current period). In PWM mode, CCPRxH is a read-only register.
The maximum PWM resolution in bits for a given PWM frequency is
fosc
fpwm
Max PWM Resolution = log bits
log(2)
The minimum resolution (in time) of each bit of the PWM duty cycle depends on the
prescaler of Timer2 (see table 1.3).
1 TSCLK
4 TCY
16 4 * TCY
The following steps configure the CCP module for PWM operation:
3. Make the CCPx pin an output by clearing the appropriate TRIS bit.
4. Establish the TMR2 prescale value and enable Timer2 by writing to T2CON.
For a thorough explanation see “Using the CCP modules”, AN594 from Microchip web
site.
1.4. PERIPHERALS 42
The Synchronous Serial Port (SSP) module is a serial interface useful for communicating
with other peripherals or microcontroller devices. These peripheral devices may be serial
EEPROMs, shift registers, display drivers, A/D converters, etc. The SSP module can
operate in one of two modes:
– Slave mode
– I/O slope control, and Start and Stop bit detection to ease software implemen-
tation of Master and Multi-master modes
The SPI mode allows 8-bits of data to be synchronously transmitted and received
simultaneously. All four modes of SPI are supported, as well as Microwire (sample edge)
when the SPI is in the master mode.
The SSP module in I2C mode fully implements all slave functions, except general call
support, and provides interrupts on start and stop bits in hardware to facilitate software
implementations of the master functions12 . The SSP module implements the standard
mode specifications as well as 7-bit and 10-bit addressing.
The two very common synchronous data protocols are Microwire and SPI. These me-
thods of interfacing are used in a number of chips (such as the serial EEPROMs used in
the BASIC Stamps). The Microwire protocol is capable of transferring data at up to 1
Mbps. Sixteen bits are transferred at a time. The SPI protocol is similar to Microwire,
but with a few differences: SPI is capable of up to 3-Mbps data-transfer rate with a data
word size is eight bits and data can be transferred as multiple bytes, known as blocks or
pages. SPI has a hold that allows transmitter to suspend data transfer.
Addressable USART
To set the Baud Rate Generator please see the tables on the Mid-range and 18F Family
Datasheet. You must set the SPBRG register and the BRGH bit for your clock speed and
desidered baud rate.
In Asynchronous Mode, the USART uses standard nonreturn-to-zero (NRZ) format
(one start bit, eight or nine data bits and one stop bit). The most common data format
is 8 bits. The USART transmits and receives the LSb first. Parity is not supported by
the hardware, but can be implemented in software. Asynchronous mode is selected by
clearing the SYNC bit (TXSTA register).
Steps to follow when setting up an Asynchronous Transmission:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud
rate is desired, set the BRGH bit.
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN
bit.
3. If interrupts are desired, then set the TXIE, GIE/GIEH and PEIE/GIEL bits.
Specify the interrupt priority if required.
4. If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data
bit).
5. Enable the transmission by setting the TXEN bit, which will also set the TXIF bit.
6. If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit.
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud
rate is desired, set bit BRGH.
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN
bit.
3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
6. The RCIF flag bit will be set when reception is complete. An interrupt will be genera-
ted depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL
bits.
1.4. PERIPHERALS 44
7. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
9. If any error occurred, clear the error by clearing the CREN bit.
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud
rate is desired, set bit BRGH.
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN
bit.
3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
6. The RCIF flag bit will be set when reception is complete. An interrupt will be genera-
ted depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL
bits.
7. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
9. If any error occurred, clear the error by clearing the CREN bit.
The USART module has a special provision for multi-processor communication. When
the RX9 bit is set in the RCSTA register, 9-bits are received and the ninth bit is placed
in the RX9D status bit of the RSTA register. Address detect mode allows an Addressable
USART node to ignore all data on the bus until a new address byte is present. This
reduces the interrupt overhead since not every byte will generate an interrupt (only bytes
that are directed to that node).
Steps to follow when setting up an Asynchronous Reception with Address
Detect enabled:
1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud
rate is desired, set bit BRGH.
2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN
bit.
3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH
and PEIE/GIEL bits, appropriately.
1.4. PERIPHERALS 45
7. The RCIF flag bit will be set when reception is complete. An interrupt will be genera-
ted depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL
bits.
8. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error
occurred during reception.
9. Read the 8-bit received data by reading the RCREG register, to determine if the
device is being addressed.
10. If any error occurred, clear the error by clearing the CREN bit.
11. If the device has been addressed, clear the ADDEN bit to allow data bytes and address
bytes to be read into the receive buffer, and interrupt the CPU.
I2C
I2C The most popular form of microcontroller network is I2C (Inter-Integrated Circuit).
This standard was originally developed by Philips in the late ‘70s as a method to provide
an interface between microprocessors and peripheral devices without wiring full address,
data, and control busses between devices. I2C also allows sharing of network resources
between processors (which is known as multi-mastering).
The I2C bus consists of two lines, a clock line (SCL), which is used to strobe data (from
the SDA line) from or to the master that currently has control over the bus. Both of these
bus lines are pulled up (to allow multiple devices to drive them). Data is transmitted in a
synchronous (clocked) fashion, with the most-significant bit sent first and. After eight bits
are sent, the master allows the data line to float (it doesn’t drive it low) while strobing the
clock to allow the receiving device to pull the data line low as an acknowledgment that
the data was received.
The two maximum speeds for I2C (because the clock is produced by a master, there
really is no minimum speed) are standard mode and fast mode. Standard mode runs at
up to 100 kbps and fast mode can transfer data at up to 400 kbps.
CAN
The Controller Area Network (CAN) is a serial communications protocol which efficiently
supports distributed real-time control with a very high level of robustness. The Protocol
is fully defined by Robert Bosch GmbH, in the CAN Specification V2.0B from 1991. Its
domain of application ranges from high speed networks to low cost multiplex wiring. CAN
is an asynchronous serial bus system with one logical bus line. It has an open, linear bus
structure with equal bus nodes.
1.4. PERIPHERALS 46
A CAN bus consists of two or more nodes. The number of nodes on the bus may be
changed dynamically without disturbing the communication of other nodes. This allows
easy connection and disconnection of bus nodes (e.g. for addition of system function, error
recovery or bus monitoring).
One of the most common and cheapest medium is a twisted wire pair. The bus lines
are then called “CANH” and “CANL”, and may be connected directly to the nodes or via
a connector. There’s no standard defined by CAN regarding the connector to be used.
The twisted wire pair is terminated by terminating resistors at each end of the bus line.
The maximum bus speed is 1 Mbit, which can be achieved with a bus length of up to 40
meters. At least 20 nodes may be connected without additional equipment. Due to the
differential nature of transmission, CAN is insensitive to EMI because both bus lines are
affected in the same way which leaves the differential signal unaffected.
In the CAN protocol it is not bus nodes that are addressed, but the address infor-
mation is contained in the messages that are transmitted. This is done via an iden-
tifier (part of each message) which identifies the message content (e.g. engine speed,
oil temperature etc.). The identifier additionally indicates the priority of the message.
For bus arbitration, Carrier Sense Multiple Access/Collision Detection (CSMA/CD) with
Non-Destructive Arbitration (NDA) is used.
Due to the complexity of the CAN bus module (nearly 120 registers involved) please
see the family datasheet for a trorough explanation.
1.4. PERIPHERALS 47
PIC18CXX8
with CAN
CAN
Transceiver
CAN
BUS
Microchip Microchip
MCP2510 MCP2510
SPI
INTERFACE
PICmicro PIC18CXX8 PIC18CXX8 PICmicro
with integrated with integrated
Controller Controller
CAN CAN
The LCD module generates the timing control to drive a static or multiplexed LCD panel,
with support for up to 32 segments multiplexed with up to four commons. It also provides
control of the LCD pixel data.
The interface to the module consists of three control registers (LCDCON, LCDSE, and
LCDPS) used to define the timing requirements of the LCD panel and up to 16 LCD data
registers (LCD00-LCD15) that represent the array of the pixel data. In normal operation,
the control registers are configured to match the LCD panel being used. Primarily, the
initialization information consists of selecting the number of commons and segments re-
quired by the LCD panel, and then specifying the LCD Frame clock rate to be used by
the panel. Once the module is initialized for the LCD panel, the individual bits of the
LCD data registers are cleared/set to represent a turned-on pixel respectively.
Once the module is configured, the LCDEN bit (LCDCON¡7¿) is used to enable or
disable the LCD module. The LCD panel can also operate during sleep by clearing the
SLPEN bit (LCDCON¡6¿).
If pins are multiplexed with LCD driver segments, then on a Power-on Reset these pins
are configured as LCD driver segments, as controlled by the LCDSE register. To configure
the pins as a digital port, the corresponding bits in the LCDSE register must be cleared.
Any bit set in the LCDSE register overrides any bit settings in the corresponding TRIS
register.
For a detailed explanation see the MidRange Reference Manual, AN658 “LCD Fun-
damentals Using PIC16C92x Microcontrollers”, AN649 “Yet Another Clock Using the
1.4. PERIPHERALS 48
1.4.6 Comparators
The comparator module contains two analog comparators. The inputs to the comparators
are multiplexed with the I/O pins. The on-chip Voltage Reference (see the “Voltage
Reference” section) can also be an input to the comparators.
A single comparator is shown in Figure 1.28 along with the relationship between the
analog input levels and the digital output. When the analog input at VIN+ is less than the
analog input VIN-, the output of the comparator is a digital low level. When the analog
input at VIN+ is greater than the analog input VIN-, the output of the comparator is a
digital high level. The shaded areas of the output of the comparator (figure 1.28) represent
the uncertainty due to input offsets and response time.
VIN + +
Output
VIN – –
VIN–
VIN+
Output
There are eight modes of operation for the comparators. The CMCON <2:0> register
is used to select the mode. Figure 1.29 shows the eight possible modes. The internal
reference signal is used when the comparators are in mode <CM2:CM0> = 110. In this
mode, the internal voltage reference is applied to the VIN+ input of both comparators.
The internal voltage reference may be used in any comparator mode if any comparator
input pin is connected externally to the VREF pin.
The comparator outputs are read through the CMCON register. These bits are read
only. The comparator outputs may also be directly output to the I/O pins.
The comparator interrupt flag is set whenever the comparators value changes relative
to the last value loaded into CMxOUT bits. Software will need to maintain information
about the status of the output bits, as read from CMCON<7:6>, to determine the actual
1.4. PERIPHERALS 49
ANx0 A VIN -
ANx0 A VIN -
C1OUT ANx3 A VIN + C1 C1OUT
A VIN + C1
ANx3
C1OUT
C1OUT
C2OUT
change that has occurred. The user, in the interrupt service routine, can clear the interrupt
reading or writing to the CMCON register and clearing the CMIF flag bit.
This Voltage Reference module is typically used in conjunction with the Comparator
module.
The Voltage Reference is a 16-tap resistor ladder network that provides a selectable
Voltage Reference. The resistor ladder is segmented to provide two ranges of VREF values
and has a power-down function to conserve power when the reference is not being used.
The VRCON register controls the operation of the reference.
16 Stages
VREN (1)
8R (1) R R (1) R (1) R (1)
8R (1) VRR
VR3
VREF 16-1 Analog MUX (From VRCON<3:0>)
VR0
The equations used to calculate the output of the Voltage Reference are as follows:
VR3 : VR0
if VRR = 1 : VREF = ∗ VDD
24
VDD VR3 : VR0
if VRR = 0 : VREF = + ∗ VDD
4 32
The standard analog-to-digital (A/D) converter module has up to eight analog inputs,
while the 10-bit Analog-to-Digital (A/D) Converter module can have up to sixteen analog
inputs. The analog input charges a sample and hold capacitor. The output of the sample
and hold capacitor is the input into the converter. The converter then generates a digital
result of this analog level via successive approximation. This A/D conversion of the analog
input signal results in a corresponding 8/10-bit digital number.
1.4. PERIPHERALS 51
The analog reference voltage is software selectable to either the device’s supply voltage
(VDD) or the voltage level on the VREF pin. The A/D converter has a unique feature of
being able to operate while the device is in SLEEP mode.
The A/D module has three registers (five for the 10-bit module). These registers are:
The ADCON0 register controls the operation of the A/D module. The ADCON1 register
configures the functions of the port pins. The I/O pins can be configured as analog inputs
(one I/O can also be a voltage reference) or as digital I/O. Note that pins multiplexed with
Analog inputs are configured as analog inputs on a Power-on Reset. Reading port pins
configured as analog inputs read a ‘0’. ADCON2 (if present) selects the A/D conversion
clock source and the format of the A/D result.
The block diagram of the 8-bit A/D module is shown in fig. 1.31.
CHS2:CHS0
111
AN7
110
AN6
101
AN5
100
AN4
VAIN
(Input voltage) 011
AN3/VREF
010
8-bit A/D AN2
Converter
001
AN1
Note: On some devices this is a separate pin called AVDD. This allows the A/D VDD to be connected to a precise voltage source.
When the A/D conversion is complete, the result is loaded into the ADRES register
(ADRESH:ADRESL for the 10-bit), the GO/DONE bit (ADCON0<2>) is cleared, and A/D
interrupt flag bit, ADIF, is set. After the A/D module has been configured as desired,
1.4. PERIPHERALS 52
the selected channel must be acquired before the conversion is started. The analog input
channels must have their corresponding TRIS bits selected as an input.
To determine acquisition time, see Subsection 21.4 “A/D Acquisition Requirements.”
After this acquisition time has elapsed the A/D conversion can be started.
The following steps should be followed for doing an A/D conversion:
4. Start conversion:
• Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or
• Waiting for the A/D interrupt
6. Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required.
The A/D conversion time per bit is defined as TAD. A minimum wait of 2TAD is
required before next acquisition starts. Acquisition time is the time that the A/D module’s
holding capacitor is connected to the external voltage level. When the GO bit is set, the
conversion time of 12 TAD is started. The sum of these two times is the sampling time.
There is a minimum acquisition time to ensure that the holding capacitor is charged to a
level that will give the desired accuracy for the A/D conversion. To calculate the minimum
acquisition time, see the device datasheet.
Not all applications require a result with 10-bits of resolution, but may instead require
a faster conversion time. The A/D module allows users to make the trade-off of conversion
13
For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum
TAD time of 1.6 µs as shown in Electrical Specifications.
1.4. PERIPHERALS 53
speed to resolution. Regardless of the resolution required, the acquisition time is the same.
To speed up the conversion, the clock source of the A/D module may be switched so
that the TAD time violates the minimum specified time. Once the TAD time violates the
minimum specified time, all the following A/D result bits are not valid.
; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.
Additional informations on the A/D converter can be found on documents “Using the
Analog to Digital Converter” AN546, “Four Channel Digital Voltmeter with Display and
Keyboard” AN557 from the Microchip web site.
Some devices have an 8-bit wide Parallel Slave Port (PSP). The port operates as an 8-bit
wide Parallel Slave Port, or microprocessor port, asynchronously readable and writable by
the external world through RD control input pin and the WR control input pin. In this
mode, the input buffers are TTL14 .
At present the Parallel Slave Port (PSP) is only multiplexed onto PORTD and PORTE.
The microprocessor port becomes enabled when the PSPMODE bit is set. In this mode,
the user must make sure that the TRISE bits are set (pins are configured as digital
inputs) and that PORTE is configured for digital I/O. PORTD will override the values in
the TRISD register.
14
PIC18C is edge sensitive, while the PIC16 is level sensitive.
1.4. PERIPHERALS 54
The port uses 11 I/O pins: the 8 data bit, CS as Chip Select, RD as ReaD opera-
tion and WR as WRite operation. The terms read and write are referred to the master
microprocessor, that reads data from the PIC and writes data to it.
A write to the PSP from the external system, occurs when both the CS and WR
lines are first detected low. When either the CS or WR lines become high (edge triggered),
the Input Buffer Full status flag bit IBF and the interrupt flag bit PSPIF are set.
The IBF flag bit is cleared by reading the PORTD input latch, and this has to be a
read-only instruction (i.e., MOVF). The input Buffer Overflow status flag bit IBOV is set
if a second write to the Parallel Slave Port is attempted when the previous byte has not
been read out of the buffer.
A read from the PSP from the external system, occurs when both the CS and
RD lines are first detected low. The Output Buffer Full status flag bit OBF is cleared
immediately indicating that the PORTD latch was read by the external bus. When either
the CS or RD pin becomes high (edge triggered), the interrupt flag bit PSPIF is set
indicating that the read is complete. OBF remains low until data is written to PORTD
by the user firmware.
When in sleep mode the microprocessor may still read and write the Parallel Slave
Port. These actions will set the PSPIF bit. If the PSP interrupts are enabled, this will
wake the processor from sleep mode so that the PSP data latch may be either read, or
written with the next value for the microprocessor.
After any reset the PSP is disabled and PORTD and PORTE are forced to their default
mode.
For a trorough explanation see “Using the 8-bit Parallel Slave Port”, AN579 from
Microchip web site.
1.4.10 USB
The PIC16C745/765 USB are currently the only PICmicros supporting USB comunication.
The USB peripheral module supports Low Speed control and interrupt (IN and OUT)
transfers only. The implementation supports 3 endpoint numbers (0, 1, 2) for a total of 6
endpoints.
Microchip provides a comprehensive support library of standard chapter 9 USB com-
mands. These libraries provide a software layer to insulate the application software from
having to handle the complexities of the USB protocol. A simple Put/Get interface is
implemented to allow most of the USB processing to take place in the background within
the USB interrupt service routine.
An on-chip integrated transceiver is included to drive the D+/D- physical layer of the
USB. A 3.3V regulator provides the D+/D- drives with power, as well as an external pin.
This pin is intended to be used to power a 1.5kΩ ± 5% pull-up resistor on the Dline
to signal a low speed device, as specified by the USB 1.1 Specification. A ±20% 200nF
capacitor is required on VUSB for regulator stability.
For more details on USB, see the USB V1.1 spec, available from the USB website at
1.5. IN-CIRCUIT SERIAL PROGRAMMING 55
APPLICATION
Host
PIC16C745/765 Controller/HUB
VUSB
200 nF
1.5K
D-
D+
www.usb.org.
For a reference on the Microchip USB library see the PIC16C7xx Datasheet from
Microchip web site.
Related Microchip Application notes are: TB054 Gameport to USB Joystick Converter,
TB055 PS/2 Mouse to USB, TB056 PS/2 Keyboard to USB, TB057 Gameport and PS/2
Mouse to USB Converter, TB058 Soft Detach and Change Configurations.
18datasheet p221 If ICSP is implemented in the target application, some means of isolating
RB7:RB6 from the rest of the circuit should be provided. The ISCP inputs have Schmitt
Triggers while the RB7:RB6 inputs have TTL inputs.
All Enhanced MCU devices can be In-Circuit Serial Programmed (ICSP) while in the
end application circuit. This is simply done with two lines for clock and data, and three
other lines for power, ground and the programming voltage.
We will skip all the details on voltages, timing and procedures. If you need them
you can read Application Note DS30277 In-Circuit Serial Programming Guide from the
Microchip web site.
The application circuit must be designed to allow all the programming signals to be
directly connected to the PICmicro MCU. Figure 1.34 shows a typical circuit that is
a starting point when designing with ICSP. The application must compensate for the
following:
Isolation of the MCLR/VPP pin: The resistor (R1) should be greater than 10kΩ
to provide isolation between VDD and VPP. The application circuit must also be
isolated from the +13V voltage provided by the programmer.
1.5. IN-CIRCUIT SERIAL PROGRAMMING 56
Loading of pins CLOCK and DATA: These pins must be isolated from the rest of the
application circuit so as not to affect the signals during programming, accounting
for CLOCK being an input on the MCU and for DATA being bi-directional. If the
design permits, these pins should not be used by the application.
Capacitance on each of the VDD, MCLR/VPP, CLOCK and DATA pins: The
total capacitance on the programming pins affects the rise rates of these signals as
they are driven out of the programmer. Keep it as low as possible, or use a driver
board between the programmer and the application circuit.
VDD
VSS
DATA
CLOCK
To application circuit
Isolation circuits
Interfacing PICs
The PICmicro MCU’s I/O pins provide digital output levels that can interface directly
to TTL and CMOS digital logic devices. The PICmicro MCU pins are specified to drive
(source) up to 20-25 mA1 and sink (pull the output to ground) 25 mA. These current
capabilities easily allow the PICmicro MCU to drive LEDs. The total current sourced or
sunk by the PICmicro MCU should not exceed 150 mA (which is six I/O pins sinking the
maximum current).
2.1 LED
The most common form of output from a microcontroller is the Light-Emitting Diode
(LED). Generally, LEDs require anywhere from 5 mA of current to light (which is within
the output sink/source specification for most microcontrollers). The typical circuit that
used to control an LED from a PICmicro MCU I/O pin is shown in Figure 2.1. With
this circuit, the LED will light when the microcontroller’s output pin is set to 0 (ground
potential). When the pin is set to input or outputs a 1, the LED will be turned off.
The 220 Ohm resistor is used for current limiting and will prevent excessive current
that can damage the microcontroller, LED and the power supply.
Probably the easiest way to output numeric (both decimal and hex) data is via seven
segment LED displays. Wiring one display to a microcontroller is quite easy, it is typically
wired as seven (or eight, if the decimal point, DP, is used) LEDs wired to individual pins.
The typical method of wiring multiple seven-segment LED displays together is to wire
them all in parallel and then control the current flow through the common pin (figure 2.2).
Because the current is generally too high for a single microcontroller pin, a transistor is
used to pass the current to the common power signal.
In this circuit, the microcontroller will shift between the displays showing each digit in
a very short time slice. This is usually done in a timer interrupt handler. To avoid flicker,
you must run the code so that each digit is turned on/off at least 50 times per second.
1
Depending on device. Devices in the 17C family have 2 special I/O ports capable do drive up to 60
mA.
2.2. SWITCH DE-BOUNCE 58
When a button is opened or closed, we perceive that it is a clean operation that really
looks like a step function. In reality, the contacts of a switch bounce when they make
contact, resulting in a jagged signal (see figure 2.3).
When this signal is passed to a PICmicro MCU, the microcontroller can recognize this
as multiple button presses, which will cause the application software to act as if multiple,
very fast button presses have occurred.
Two common methods are used to debounce button inputs. The first is to poll the
switch line at short intervals until the switch line stays at the same level for an extended
period of time. A button is normally considered to be debounced if it does not change
state for 20 ms or longer. The advantage of this method is that it can be done in an
interrupt handler and the line can be scanned periodically with a flag set if the line is high
and another flag in the line is low. This method of debouncing is good for debouncing
keyboard inputs.
If you don’t want to use the software approaches, you can use a capacitor to filter the
bouncing signal and pass it into a Schmidt trigger input. This method is fairly reliable,
but requires an available Schmidt trigger gate in your circuit. A Schmidt trigger input
might be available in your PICmicro MCU, but check the data sheet to find out which
states and peripheral hardware functions can take advantage of it.
Some real-life devices that you might have to control by a microcontroller are electroma-
gnetic, such as relays, solenoids, and motors. These devices cannot be driven directly by
a microcontroller because of the current required and the noise generated by them. This
means that special interfaces must be used to control electromagnetic devices.
The simplest method to control these devices is to just switch them on and off and
by supplying power to the coil in the device. The circuit shown in fig. 2.5 is true for
relays (as shown), solenoids (which are coils that draw an iron bar into them when they
are energized), or a DC motor (which will only turn in one direction). In this circuit, the
microcontroller turns on the Darlington transistor pair, causing current to pass through
the relay coils, closing the contacts. To open the relay, the output is turned off (or a 0 is
output).
The shunt diode across the coil is used as a kick-back suppressor. When the current
is turned off, the magnetic flux in the coil will induce a large back EMF (voltage), which
must be absorbed by the circuit or a voltage spike will occur, which can damage the
2.4. MOTORS 60
relay power supply and even the microcontroller. This diode must never be forgotten in
a circuit that controls an electromagnetic device. The kick-back voltage is usually on the
order of several hundred volts for a few nanoseconds. This voltage causes the diode to
breakdown and allows current to flow, attenuating the induced voltage which can damage
the PICmicro
r MCU and other electronic devices in the application circuit.
Rather than designing discrete circuits to carry out this function, is best to use in-
tegrated chips for the task. One of the most useful devices is the ULN2003A or the
ULN2803 series of chips, which have Darlington transistor pairs and shunt diodes built in
for multiple drivers.
2.4 Motors
Motors can be controlled by exactly the same hardware as shown in the previous section,
but as I noted, they will only run in one direction. A network of switches (transistors)
can be used to control turning a motor in either direction; this is known as an H-bridge
(fig. 2.6).
In this circuit, if all the switches are open, no current will flow and the motor won’t
turn. If switches 1 and 4 are closed, the motor will turn in one direction. If switches 2
and 3 are closed, the motor will turn in the other direction. Both switches on one side
of the bridge should never be closed at the same time because this will cause the motor
power supply will burn out or a fuse will blow because a short circuit is directly between
the motor power and ground.
Controlling a motor’s speed is normally done by “pulsing” the control signals in the
form of a PWM signal. The frequency of the PWM signal should be greater than 20 kHz
to prevent the PWM from producing an audible signal in the motors as the field is turned
on and off.
Like the ULN2003A simplified the wiring of a relay control, the 293D or 298 chips can
be used to control a motor.
2.4. MOTORS 61
The 293D chip can control two motors (one on each side) connected to the buffer
outputs (pins 3, 6, 11, and 14). Pins 2, 7, 10, and 15 are used to control the voltage level
(the switches in the H-bridge diagram) of the buffer outputs. Pins 1 and 9 are used to
control whether or not the buffers are enabled. The buffer controls can be PWM inputs,
which make control of the motor speed very easy to implement. Vs is 5V used to power
the logic in the chip and Vss is the power supplied to the motors (anywhere from 4.5 to
36 volts). A maximum of 500 mA can be supplied to the motors. Like the ULN2003A,
the 293D contains integral shunt diodes. The 293D is limited to 1 amp total output and
the 298 is limited to 3 amps. For these circuits to work best, a large heatsink is required.
Another H-bridge circuit is the National2 LMD18200, rated 3A 55V, that features also
6A peak current, thermal warning flag and thermal shutdown, shorted load protection,
brake input and current sense output.
2
http://www.national.com
2.5. RS232 62
2.5 RS232
It’s quite easy to connect a PICmicro to an RS232 serial port, the kind is usually found
on PCs. A chip from the widespread family MAX220-249 takes care of translating the
voltage levels from TTL to RS232 and vice-versa, including the pump-circuit to generate
the various voltages from the 5v supply, and offering a good protection against electrostatic
discharges.
The most used chip is the MAX232, made by Maxim3 , offering level translation for 2
input channels (RS232 ⇒ TTL) and 2 output channels (TTL ⇒ RS232).
Using the MAX232 is immediate: the only external components needed are five 1µF
capacitors for the voltage doubler and the voltage inverter connected as in figure 2.9.
To know about the software details for setting up a serial communication, see section
1.4.4 Addressable USART.
An example circuit with the MAX232 is in Appendix B
3
www.maximic.com
2.5. RS232 63
+5V INPUT C3
TOP VIEW
C5
16
1 VCC
C1+ 1 16 VCC C1+ V+ 2 +10V
C1 +5V TO +10V
V+ 2 3 C1-
15 GND VOLTAGE DOUBLER
4
C1- 3 C2+ +10V TO -10V 6 -10V
14 T1OUT C2 5 C2- VOLTAGE INVERTER
V-
C4
C2+ 4 MAX220 13 R1IN
+5V
MAX232
C2- 5 MAX232A 12 R1OUT 400kΩ
V- 6 11 T1IN T1OUT 14
11 T1IN
+5V
T2OUT 7 10 T2IN TTL/CMOS RS-232
INPUTS 400kΩ OUTPUTS
R2IN 8 9 R2OUT 10 T2IN T2OUT 7
GND
15
Programmazione
Nel capitolo 1 abbiamo mostrato l’architettura dei PICmicro e le periferiche che questi
metono a disposizione. In questo capitolo mostreremo come scrivere un programma che ci
permetta di sfruttare al meglio il chip per le nostre applicazioni.
I PICmicro, date le piccole dimensioni del codice e il ridotto numero di istruzioni, pos-
sono essere facilmente programmate in assembler, assemblando pezzi di codice da librerie
o progetti già sviluppati. Per progetti più complessi sono disponibili vari tools tra cui un
compilatore C.
MOVF RegistroA, w
SUBWF RegistroB, w : non modifichiamo il registro
BTFSZ STATUS, Z : testiamo il flag Z
GOTO SonoUguali
GOTO SonoDiversi
Una anche minima familiarità con i linguaggi a basso livello di qualsiasi microprocessore
vi permetterà di scrivere codice funzionante in brevissimo tempo.
A mio avviso il modo migliore per capire il linguaggio è analizzare del codice già pronto,
tenendo sottomano il set di istruzioni del dispositivo. Per questo vi rimando alla lettura
del capitolo 4.
3.2 Linguaggio C
Per i microcontrollori delle famiglie PIC17 e PIC18 sono stati sviluppati diversi compilatori
C, tra cui l’MPLAB C17 e l’MPLAB C18 della Microchip stessa.
2
i 4 bit meno significativi, detti anche nibble
3.3. APPLICATION MAESTRO 66
3.4 FilterLab
FilterLab è un’applicazione rilasciata come download gratuito dalla microchip che per-
mette un facile design di filtri attivi. Le principali caratteristiche sono:
Pur non essendo direttamente collegata alla programmazione dei PICmicro, l’applica-
zione risulta utile per l’utilizzo dei convertitori A/D inclusi nei microcontrollori.
La documentazione dell’applicazione consiste in un overview (51204b) e nella “User’s
guide” (51419a).
3.5. MPLAB IDE 68
MPLAB IDE e’ un ambiente di sviluppo integrato fornito dalla Microchip. Esso consiste
in un ambiente di lavoro con gestione di progetti che permette di invocare i vari tools quali
assemblatore, linker, debugger, simulatore, compilatori di terze parti.
Editor
.asm .inc
Compilatore
assembler
PIC Programmatore
Nel creare il nostro programma possiamo scegliere se lavorare su un singolo file, nel
qual caso è sufficiente eseguire una quickbuild, o creare un progetto composto da più files
su cui bisogna eseguire il linking. La scelta ovviamente dipenderà dalla complessità del
progetto da affrontare.
3.6. PROGRAMMARE CON L’ICD 2 69
Utilizzando un singolo file, una volta steso il programma è sufficiente scegliere Quic-
kbuild dal menù per assemblare il programma con MPASM Assembler. Se sono stati
installati tools di terze parti è necessario accertarsi che sia selezionato il tool corretto nelle
impostazioni del progetto (Project → Set Language Tool Locations). Una volta corretti
tutti gli eventuali errori, è possibile passare alla fase successiva, il debugging.
Dovendo realizzare un programma di dimensioni maggiori sarà opportuno impostare
un progetto. MPLAB offre un Wizard che permette di semplificare la fase iniziale di
set-up. Nel progetto andremo ad includere i files sorgenti e le librerie necessarie, oltre ad
un file per il linking specifico del MCU che andremo a programmare. Per compilare il
progetto andremo a selezionare Project → Build All.
Prima di procedere è importante ricordarsi di impostare correttamente i bit di confi-
gurazione. E’ consigliabile farlo all’interno del codice tramite le direttive di configurazione
(vedi sezione 3.1.1) in modo da rendere le scelte immediatamente visibili e “trasportabili”,
oppure tramite l’interfaccia grafica di MPLAB.
Al termine della compilazione il codice generato è immediatamente disponibile per la
successiva fase di debug, o per essere direttamente programmato sul PICmicro.
Una guida all’utilizzo di MPLAB IDE è fornita dalla microchip nel file “Application
Development With MPLAB IDE” (51410a).
3.5.2 Simulare
L’ICD2 è il nuovo programmatore-debugger a basso costo offerto dalla Microchip. Pur non
presentando le caratteristiche di verifica sulla programmazione necessarie in un ambiente
di produzione3 offre all’utente tutte le funzionalità necessarie per sviluppare applicazioni
su una vasta gamma di PICmicro.
L’ICD2 può essere collegato al PC di controllo tramite porta seriale o USB.
Se utilizziamo la porta seriale dobbiamo:
L’ICD2, oltre ad essere un valido programmatore, offre alcune funzionalità di debug pre-
ziose per individuare in breve tempo difetti nel software che altrimenti richiederebbero un
impegno maggiore per essere scoperti.
Utilizzando l’ICD2 come debugger abbiamo la possibilità di:
• impostare un breakpoint;
che permetteranno di controllare l’esecuzione del software. Al termine della fase di svilup-
po è importante riprogrammare il PICmicro con il codice originale, altrimenti il circuito
non funzionerà scollegato dell’ICD2.
Per utilizzare il debugger è altresı̀ necessario disabilitare il timer di watchdog ed impo-
stare correttamente l’indirizzo finale del programma. Se alcuni parametri di configurazione
sono incompatibili con le esigenze del debugger MPLAB provvederà a mostrare un avviso.
Capitolo 4
Esempi
Imparare tramite esempi è sicuramente il modo più semplice per avvicinarsi ai micro-
controllori. In questo capitolo presenteremo alcune applicazioni di difficoltà crescente
commentando esaustivamente il codice sorgente e motivando le scelte progettuali.
Persino un task basilare come far lampeggiare un led può essere risolto in più modi: il
primo basilare, il secondo un po più “furbo”.
Single-task
Per iniziare vediamo il metodo più semplice: facciamo eseguire un numero fisso di istruzioni
nulle (NOP, No OPeration) al PICmicro nell’intervallo tra un accensione e uno spegnimento.
Seguiamo passo passo il programma: le prime linee sono direttive di compilazione che
impostano il dispositivo target ed includono il relativo file di configurazione. In seguito
riserviamo due bytes nello spazio di memoria utente attribuendo al primo il nome simbolico
“Count”.
Dall’istruzione ORG 0x000, inizia il programma vero e proprio. Poiché 0x000 e’ l’indi-
rizzo del vettore di reset, l’istruzione seguente sarà la prima ad essere eseguita dopo un
reset. Subito impostiamo la direzione delle porte (PORTB<0> come output e le rimanenti
come input) srcivendo il valore opportuno nel registro TRISB. Utilizzare il valore binario
aiuta a visualizzare la configurazione (l’1 somiglia alla I di Input, mentre lo zero ricorda la
O di Output), ma avremmo potuto utilizzare indifferentemente ’0xFE’ oppure ’255’. Se il
codice dovesse essere utilizzato su un PICmicro della serie 16 è necessario ricordare che il
registro TRISB si trova nel Banco 0, quindi per accedervi è necessario manipolare il valore
di STATUS, RP0 come spiegato nel capitolo 1.3.5.
A questo punto abbiamo il nostro ciclo principale, illustrato nel diagramma di flusso
in figura 4.2. A seconda dello stato attuale del LED decidiamo se accenderlo o spegnerlo,
ed entriamo nella routine di ritardo.
4.1. LAMPEGGIO LED 73
ORG 0x80
MainLoop
btfsc PORTB,0 ; Se il LED e’ acceso
goto SpegniLED ; Vai a SpegniLED
bsf PORTB,0 ; Accendi il led
call Delay
goto MainLoop
SpegniLED
bcf PORTB,0 ; Spegni il LED
call Delay
goto MainLoop
;Subroutines
Delay
clrf Count
clrf Count+1
DelayLoop
decfsz Count,1 ; Decrementa Count, salta se zero
goto DelayLoop
decfsz Count+1,1 ; Decrementa Count+1, salta se zero
goto DelayLoop
return ; Ritorna al punto di chiamata
END
Impostazione Decrementa
porte I/O Count
No No
Led acceso? Count = 0
goto DelayLoop
skip if clear
Vai a Decrementa
SpegniLed Count+1
goto MainLoop
Accendi Spegni il No
il LED LED Count+1 = 0
La routine di ritardo decrementa due registri a 8 bit, ottenendo cosı̀ un ritardo pari a
16 bit, cioè 65.536 unità. Per sapere a quanto tempo corrisponda dobbiamo considerare
che ogni istruzione di decremento viene eseguita in 1 TCY, mentre le istruzioni di salto,
provocando lo svuotamento della pipeline1 , vengono eseguite in 2 TCY. Ogni ciclo di
ritardo sul primo registro quindi occupa 3 TCY mentre ogni ciclo sul secondo ne occupa
5, quindi in totale occupiamo 3 ∗ 256 + 5 ∗ 256 TCY, cioè 983’040 TCY pari a 0,983040
secondi con un clock a 4 MHz. Se avessimo voluto una frequenza più vicina ad un secondo
avremmo potuto scegliere di caricare un valore iniziale diverso da zero ad ognuno dei due
registri.
1
vedi la sezione 1.1
4.1. LAMPEGGIO LED 75
A livello di curiosità in figura 4.3 abbiamo riportato il codice esadecimale generato dal
nostro programma, ciò che verrà effettivamente programmato nel PIC.
:020000040000FA
:1000000002EF00F01F0E926EFE0E936E81B010EFA5
:1000100000F08180070E826F17EC00F006EF00F011
:1000200081900F0E826F17EC00F006EF00F0806BEE
:10003000816B802F19EF00F0812F19EF00F0822FD4
:0600400019EF00F01200B0
:00000001FF
Interrupt-driven
Il programma descritto nella sezione precedente esegue perfettamente il task per cui è stato
sviluppato, ma ha un grosso difetto: tutta la potenza di calcolo della CPU è impegnata a
contare il tempo tra un lampeggio e il successivo. Un modo migliore per effettuare la stessa
operazione lasciando la CPU libera di eseguire altre operazioni è demandare l’operazione
di conteggio ad una periferica TIMER, che ci segnalerà la necessità di aggiornare lo stato
del LED tramite un interrupt. Vediamo come:
Inizialmente, dopo le usuali direttive per il compilatore, troviamo subito una novità:
Per capire il perchè di questa scelta dobbiano sapere come è organizzata la memoria
del PICmicro (vedi sezione 1.3.5). Tra il vettore di reset che si trova in 0x000h e il vettore
di interrupt 0x0008 abbiamo solo 8 locazioni di memoria. Anche se attualmente il nostro
loop principale è lungo solamente 2 istruzioni, supponiamo che in una applicazione reale
sia più lungo e quindi non entri nello spazio tra i due vettori. Per questo motivo inseriamo
solamente una chiamata al nostro codice.
Le stesse considerazioni si applicano al vettore di interrupt ad alta priorità che si trova
a dieci locazioni dal vettore a bassa priorità 0x0018.
Le istruzioni di set-up prevedono di impostare la porta PORTB<0> come output per
il LED e le restanti come input, di impostare il Timer0 in modalità 16 bit con in input il
TCY e prescaler 1:16 e di abilitare l’interrupt per il timer.
La routine principale in questo esempio è vuota, ma in un applicazione reale sarebbe
stata utilizzata per altri task.
Mentre il processore è libero il Timer0 decrementa con frequenza pari a 1/64 del clock
esterno e genera un interrupt ogni volta che raggiunge lo zero. A questo punto la routine di
4.1. LAMPEGGIO LED 76
Start
movlw B’11111110’
movwf TRISB
movlw B’10000011’ ;Set-up timer
;Bit 7 1 Timer0 on
;Bit 6 0 16bit
;Bit 5 0 count Tcy
;Bit 3 0 Prescaler on
;Bit 2-0 011 1:16 prescaler
movwf T0CON
movlw B’11100000’ ;Set-up interrupts
;Bit 7 1 Global enable
;Bit 6 1 Peripheral enable
;Bit 5 1 Timer0 interrupt enable
movwf INTCON
MainLoop
nop ; Your software here
goto MainLoop
Timer0Interrupt
btfsc PORTB,0 ; Se il LED e’ acceso
goto SpegniLED
bsf PORTB,0 ; Accendi il led
bcf INTCON,2 ; Elimina il flag di Interrupt
retfie
SpegniLED
bcf PORTB,0 ; Spegni il LED
bcf INTCON,2 ; Elimina il flag di Interrupt
retfie
END
Reset vector
0x0000 goto Start
0x0001
Start
ISR
servizio dell’interrupt verifica che l’interrupt sia stato effettivamente generato dal Timer0
e in caso affermativo modifica lo stato del LED. E’ importante notare che il Timer0 non
viene mai fermato e continua a correre anche durante la ISR, quindi gli intervalli tra due
interrupt successivi sono costanti e dipendono solamente dal clock e dalle impostazioni del
prescaler, non dal numero di istruzioni nelle varie routines.
L’intervalo di lampeggio nel nostro esempio è 65536 ∗ 16 ∗ 4 cioè 4’194’304 colpi di clock
che a 4 MHz corrispondono a 1,048 secondi.
Se avessimo avuto bisogno di una frequenza esatta, ad es. per realizzare un orologio,
avremmo potuto collegare un quarzo da 32,768 kHz al piedino di ingresso del Timer0.
Impostando il timer a 8 bit con prescaler 1:128 otterremmo una frequenza di interrupt di
32768/(256 ∗ 128), cioè 1 secondo.
tro presente sulla PICDEM2 collegato al piedino RA0. La modalità di controllo viene
selezionata tramite la pressione del pulsante collegato al piedino RA4.
Analizziamo il codice sorgente. Tra le direttive di compilazione e le istruzioni per la
gestione dei vettori di interrupt visti in precedenza, abbiamo un istruzione per riservare
una variabile. Il comando in realtà non verrà programmato nel PIC, ma sarà interpretato
dall’assemblatore che sostituirà le occorrenze del nome simbolico con l’indirizzo di memoria
reale.
La prima parte del programma contiene tutte le istruzioni di inizializzazione: prima il
modulo USART viene abilitato in ricezione e in trasmissione, con un baud rate di 9600; in
seguito viene abilitato il modulo A/D; infine viene impostato il modulo CCP in modalità
PWM con frequenza di 78 kHz e duty-cycle del 50 % .
Il loop principale non fa altro che apettare la pressione del tasto S2 per modificare lo
stato dell’uscita RB0, che viene usata anche come flag dal programma. Se il nostro pro-
gramma avesse avuto la necessità di compiere altre operazioni avremmo potuto utilizzare
in input un piedino che genera un interrupt, e lasciando cosı̀ il ciclo principale libero.
Solamente le routine di servizio degli interrupt modificano il duty-cycle: se il modulo
A/D genera un interrupt ed è selezionata la modalità “potenziometro”, gli 8 bit più signi-
ficativi derivanti dalla conversione determinano gli 8 bit più significativi del duty-cycle e
vengono trasmessi sulla porta seriale. Per semplicità si è deciso di non sfruttare l’intera
risoluzione (10 bit) del modulo A/D e del modulo CCP.
Similarmente quando viene generato un interrupt dall’unità USART, se è selezionata
la modalità “seriale”, il byte ricevuto determina gli 8 bit più significativi del duty-cycle.
Per semplicità e poichè non si presentava necessità di farlo, sono state omesse le rou-
tine di salvataggio del contesto durante il servizio degli interrupt. In caso di programmi
principali più complessi la gestione di un interrupt può modificare alcuni registri di stato
ed influenzare il flusso principale del programma. In caso ciò sia possibile è necessario
prevedere una routine che memorizzi il contenuto dei registri “a rischio” e lo ripristini alla
fine del servizio dell’interrupt.
E’ stato deciso di sviluppare il controllore per motori stepper in linguaggio C. Tale appli-
cazione sarà presentata nel documento relativo alla programmazione dei PIC in linguaggio
C.
4.3. CONTROLLORE PER MOTORI STEPPER 79
;************************************************************
; Produce un PWM il cui Duty Cycle puo’ essere controllato
; via il potenziometro su RA0 o tramite un byte trasmesso
; sulla porta seriale.
; Per scegliere la modalita’ premere S2 (RA4).
; Led acceso = controllo potenziometro
; Led spento = controllo seriale
; Il PWM sarà emesso su RC1.
;************************************************************
;************************************************************
; variables
;************************************************************
; reset and interrupt vectors
;************************************************************
; program
org 0x00020
Start
clrf PORTB ; clear all bits of PORTB
clrf TRISB ; Set PORTB as outputs
bcf TRISC,6 ; Make RC6 an output
;Set the TMR2 prescale value and enable Timer2 by writing to T2CON
;Configure the CCP2 module for PWM operation
clrf T2CON ; clear T2CON
clrf TMR2 ; clear Timer2
bsf T2CON,TMR2ON ; turn on Timer2
MLOOP
btfsc PORTA,4 ; Has S2 been pressed? (low when pressed.)
goto MLOOP ; No, check again
SwitchMode
btfss PORTB,RB0 ; if was POT
goto SetPot
bcf PORTB,RB0 ; set to SER
goto Debounce
Debounce
btfss PORTA,4 ; Has key been released?
goto Debounce ; No, wait some more
goto MLOOP ; yes, wait for next key press
;************************************************************
; Service A/D interrupt
ISR
; Save context (WREG and STATUS) if required.
;A/D Interrupt
ADInt
;USART Interrupt
USARTInt
btfss PIR1,RCIF ; Did USART cause interrupt?
goto OtherInt ; No, some other interrupt
RcvError
bcf RCSTA,CREN ; Clear receiver status
bsf RCSTA,CREN
; Signal error to user
goto EndISR ; go to end of ISR, restore context, return
OtherInt
; Check and service other interrupt sources
goto $ ; trap here, loops to self
EndISR
; Restore context if saved.
retfie ; Return, enables GIE
;************************************************************
; InitializeAD - initializes and sets up the A/D hardware.
; Select AN0 to AN3 as analog inputs, RC clock, and read AN0.
InitializeAD
movlw B’00000100’ ; Make RA0,RA1,RA4 analog inputs
movwf ADCON1
return
;************************************************************
; This is used to allow the A/D time to sample the input
; (acquisition time).
;
; This routine requires 11 cycles to complete.
; The call and return add another 4 cycles.
;
; 15 cycles with Fosc=4MHz means this delay consumes 15us.
SetupDelay
movlw .3 ; Load Temp with decimal 3
movwf TEMP
SD
decfsz TEMP, F ; Delay loop
goto SD
return
END
La PICDEM2 plus è una demo board realizzata dalla Microchip. Presenta a bordo vari
componenti per permettere la dimostrazione di gran parte delle periferiche presenti sui
microcontrollori della serie 16 e 18.
La scheda ha a bordo:1
• 4 LED
• 2 pulsanti + reset
• Potenziometro
La scheda permette la prototipazione rapida di gran parte dei PICmicro grazie agli
zoccoli da 18, 28 e 40 PIN e al connettore per la programmazione in-circuit. Tutti i
piedini di I/O sono disponibili sulle piazzole, e sono predisposti un oscillatore al quarzo
da 4 MHz, un oscillatore RC da 2MHz e un quarzo per applicazioni di timing da 32.768
KHz.
Nel caso in cui stiamo utilizzando la scheda con l’ICD2 collegato al PC tramite porta
USB, dobbiamo alimentare la scheda tramite un alimentatore non regolato da 9V, tramite
una batteria da 9V oppure con un alimentatore stabilizzato da 5V collegato ai ganci posti
vicino all’area di prototipazione (figura A.1 particolare 2).
1
Per una descrizione più completa fare riferiento al documento Microchip 51275a
2
Per il datasheet del sensore cercare il documento Microchip DS21462
84
7 9 8
2
15
13
10
11
3
5
14
12
4 17
18
1
16
2
6
Pot Temp
Device LEDs RS-232 S1 S2 S3 LCD EEPROM Buzzer ICD Y1/Y2
R16 Sensor
18-pin RB3:RB0 N/A MCLR RA4 RB0 RA0 N/A N/A N/A RB6/RB7 N/A Yes
28-pin RB3:RB0 RC6/RC7 MCLR RA4 RB0 RA0 RA3:RA1 RC3/RC4 RC2 RB6/RB7 RC3/RC4 Yes
RD3:RD0
40-pin RB3:RB0 RC6/RC7 MCLR RA4 RB0 RA0 RA3:RS1 RC3/RC4 RC2 RB6/RB7 RC3/RC4 Yes
RD3:RD0
B.1 16F84
Lo sbroglio del circuito stampato è stato effettuato a mano in due versioni diverse: i
ringraziamenti per la versione B vanno all’ Ing. Valerio Senni.
Poichè non è possibile garantire l’accuratezza della scala di riproduzione, e’ necessario
assicurarsi che la distanza tra i piedini del PIC sia pari a 2.54 mm, per una distanza totale
tra il piedino 1 e il piedino 9 di 22.86 mm.
1
Il prototipo realizzato monta un quarzo da 4 MHz e due condensatori da
B.1. 16F84 86
C4 C7 C8
J1 IC2 C2 IC1
X1
C1
C5 C3
C6
+5V INPUT C3
TOP VIEW
C5
16
1 VCC
C1+ 1 16 VCC C1+ V+ 2 +10V
C1 +5V TO +10V
V+ 2 3 C1-
15 GND VOLTAGE DOUBLER
4
C1- 3 C2+ +10V TO -10V 6 -10V
14 T1OUT C2 5 C2- VOLTAGE INVERTER
V-
C4
C2+ 4 MAX220 13 R1IN
+5V
MAX232
C2- 5 MAX232A 12 R1OUT 400kΩ
V- 6 11 T1IN T1OUT 14
11 T1IN
+5V
T2OUT 7 10 T2IN TTL/CMOS RS-232
INPUTS 400kΩ OUTPUTS
R2IN 8 9 R2OUT 10 T2IN T2OUT 7
GND
15
Instruction sets
Tutte le istruzioni sono eseguite in un sigolo ciclo di clock, ad eccezione dei salti, che ne
impiegano due. Questo rende la tempistica di esecuzione molto prevedibile e più facilmente
calcolabile rispetto a processori più complessi.
Il significato dei simboli utilizzati nella descrizione del set di istruzioni è riportato in
tabella C.4.
C.2 PIC18F45x
Il set di istruzioni del PIC18F45x aggiunge diversi miglioramenti a quello della famiglia
PIC16F, pur mantenendo la stessa semplicità ed ortogonalità.
Tutte le istruzioni tranne tre occupano una singola word (16 bit). Tentare di eseguire
la seconda word di un istruzione non provoca danni, in quanto viene riconosciuta come
C.2. PIC18F45X 89
tale ed eseguita come NOP. Tutte le istruzioni single-word sono eseguite in un ciclo di clock,
ad eccezione dei salti.
Le operazioni sono suddivise in cinque categorie principali:
• Operazioni letterali
• Operazioni di controllo
CONTROL OPERATIONS
BC n Branch if Carry 1 (2) 1110 0010 nnnn nnnn None
BN n Branch if Negative 1 (2) 1110 0110 nnnn nnnn None
BNC n Branch if Not Carry 1 (2) 1110 0011 nnnn nnnn None
BNN n Branch if Not Negative 1 (2) 1110 0111 nnnn nnnn None
BNOV n Branch if Not Overflow 1 (2) 1110 0101 nnnn nnnn None
BNZ n Branch if Not Zero 2 1110 0001 nnnn nnnn None
BOV n Branch if Overflow 1 (2) 1110 0100 nnnn nnnn None
BRA n Branch Unconditionally 1 (2) 1101 0nnn nnnn nnnn None
BZ n Branch if Zero 1 (2) 1110 0000 nnnn nnnn None
CALL n, s Call subroutine1st word 2 1110 110s kkkk kkkk None
2nd word 1111 kkkk kkkk kkkk
CLRWDT — Clear Watchdog Timer 1 0000 0000 0000 0100 TO, PD
DAW — Decimal Adjust WREG 1 0000 0000 0000 0111 C
GOTO n Go to address1st word 2 1110 1111 kkkk kkkk None
2nd word 1111 kkkk kkkk kkkk
NOP — No Operation 1 0000 0000 0000 0000 None
NOP — No Operation 1 1111 xxxx xxxx xxxx None 4
POP — Pop top of return stack (TOS) 1 0000 0000 0000 0110 None
PUSH — Push top of return stack (TOS) 1 0000 0000 0000 0101 None
RCALL n Relative Call 2 1101 1nnn nnnn nnnn None
RESET Software device RESET 1 0000 0000 1111 1111 All
RETFIE s Return from interrupt enable 2 0000 0000 0001 000s GIE/GIEH,
PEIE/GIEL
RETLW k Return with literal in WREG 2 0000 1100 kkkk kkkk None
RETURN s Return from Subroutine 2 0000 0000 0001 001s None
SLEEP — Go into Standby mode 1 0000 0000 0000 0011 TO, PD
LITERAL OPERATIONS
ADDLW k Add literal and WREG 1 0000 1111 kkkk kkkk C, DC, Z, OV, N
ANDLW k AND literal with WREG 1 0000 1011 kkkk kkkk Z, N
IORLW k Inclusive OR literal with WREG 1 0000 1001 kkkk kkkk Z, N
LFSR f, k Move literal (12-bit) 2nd word 2 1110 1110 00ff kkkk None
to FSRx 1st word 1111 0000 kkkk kkkk
MOVLB k Move literal to BSR<3:0> 1 0000 0001 0000 kkkk None
MOVLW k Move literal to WREG 1 0000 1110 kkkk kkkk None
MULLW k Multiply literal with WREG 1 0000 1101 kkkk kkkk None
RETLW k Return with literal in WREG 2 0000 1100 kkkk kkkk None
SUBLW k Subtract WREG from literal 1 0000 1000 kkkk kkkk C, DC, Z, OV, N
XORLW k Exclusive OR literal with WREG 1 0000 1010 kkkk kkkk Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD* Table Read 2 0000 0000 0000 1000 None
TBLRD*+ Table Read with post-increment 0000 0000 0000 1001 None
TBLRD*- Table Read with post-decrement 0000 0000 0000 1010 None
TBLRD+* Table Read with pre-increment 0000 0000 0000 1011 None
TBLWT* Table Write 2 (5) 0000 0000 0000 1100 None
TBLWT*+ Table Write with post-increment 0000 0000 0000 1101 None
TBLWT*- Table Write with post-decrement 0000 0000 0000 1110 None
TBLWT+* Table Write with pre-increment 0000 0000 0000 1111 None
Field Description
f Register file address (0x00 to 0x7F)
W Working register (accumulator)
b Bit address within an 8-bit file register (0 to 7)
k Literal field, constant data or label (may be either an 8-bit or an 11-bit value)
x Don't care (0 or 1)
The assembler will generate code with x = 0. It is the recommended form of use for
compatibility with all Microchip software tools.
d Destination select;
d = 0: store result in W,
d = 1: store result in file register f.
dest Destination either the W register or the specified register file location
label Label name
TOS Top of Stack
PC Program Counter
PCLATH Program Counter High Latch
GIE Global Interrupt Enable bit
WDT Watchdog Timer
TO Time-out bit
PD Power-down bit
[ ] Optional
( ) Contents
→ Assigned to
<> Register bit field
∈ In the set of
italics User defined term (font is courier)
Glossary
Absolute Section A section with a fixed (absolute) address which can not be changed
by the linker.
Access RAM (PIC18CXXX Devices Only) This is a region of data memory RAM
that can be accessed regardless of the currently selected bank. This allows special
function registers to be accessed by the instruction without changing the currently
selected bank. Access RAM also contains some General Purpose Registers (GPRs).
This is useful for the saving of required variables during context switching (such as
during an interrupt). When used in reference to PIC18CXXX devices, Access RAM
refers to special general purpose registers that allow access regardless of the setting
of the bank select bit(BSR).
ALU Arithmetical Logical Unit. Device logic that is responsible for the mathemati-
cal(add, subtract, ...), logical (and, or, ...), and shifting operation.
Assembly Language A symbolic language that describes the binary machine code in a
readable form.
Breakpoint - Software An address where execution of the firmware will halt. Usually
achieved by a special break opcode.
Build A function that recompiles all the source files for an application.
C A high level programming language that may be used to generate code for PICmicro
MCUs, especially high-end device families.
Calibration Memory A special function register or registers used to hold values for
calibration of a PICmicro microcontroller on-board RC oscillator.
CAN Controller Area Network. A peripheral interface targeting automotive and indu-
strial applications.
Capture A function of the CCP module in which the value of a timer/counter is “cap-
tured” into a holding register module when a predetermined event occurs.
Capture Register A 16-bit register that is loaded with the value of the 16-bit TMR1
register when a capture event occurs.
CCP Capture, Compare, Pulse Width Modulation (PWM). The CCP module can be
configured to operate as an input capture, or a timer compare, or a PWM output.
COFF Common Object File Format. An intermediate file format generated by MPLINK
LINKER that contains machine code and debugging information.
Common RAM This is a region of the data memory RAM that is the same RAM loca-
tion across all banks. This common RAM may be implemented between addresses
70h - 7Fh (inclusive). This common area is useful for the saving of required variables
during context switching (such as during an interrupt).
Compare A function of the CCP module in which the device will perform an action when
a timer’s register value matches the value in the compare register.
Compare Register A 16-bit register that contains a value that is compared to the 16-
bit TMR1 register. The compare function triggers when the counter matches the
contents of the compare register.
Compiler A language tool that translates a user’s C source code into machine code.
MPLAB C17 and MPLAB C18 are Microchip’s C compilers for PIC17CXXX and
PIC18CXXX devices, respectively.
97
Configuration Word This is a non-volatile memory location that specifies the characte-
ristics that the device will have for operation (such as oscillator mode, WDT enable,
start-up timer enables). These characteristics can be specified at the time of device
programming. For EPROM memory devices, as long as the bit is a ’1’, it may at
a later time be programmed as a ’0’. The device must be erased for a ‘0’ to be
returned to a ‘1’.
CPU Central Processing Unit. Decodes the instructions, and determines the operands
and operations that are needed for program execution. Arithmetic, logical, or shift
operations are passed to the ALU.
Data Bus The bus which is used to transfer data to and from the data memory.
Data EEPROM Data Electrically Erasable Programmable Read Only Memory. This
memory is capable of being programmed and re-programmed by the CPU to ensure
that in the case of a power loss, critical values/variables are retained in the non-
volatile memory.
Data Memory The memory that is on the Data Bus. This memory is volatile (SRAM)
and contains both the Special Function Registers and General Purpose Registers.
Data Memory General purpose file registers (GPRs) from RAM on the PICmicro device
being emulated. The File Register window displays data memory.
Direct Addressing When the Data Memory Address is contained in the Instruction.
The execution of this type of instruction will always access the data at the embedded
address.
Directives Directives provide control of the assembler’s operation by telling the MPA-
SM Assembler how to treat mnemonics, define data, and format the listing file.
Directives make coding easier and provide custom output according to specific needs.
Download Download is the process of sending data from the PC host to another device,
such as an emulator, programmer or target board.
98
Emulation The process of executing software loaded into emulation memory as if the
firmware resided on the microcontroller device under development.
Emulator System The MPLAB ICE emulator system includes the pod, processor mo-
dule, device adapter, cables, and MPLAB Software. The PICMASTER; emulator
system includes the pod, device-specific probe, cables, and MPLAB software.
EPROM Electrically Programmable Read Only Memory. This memory has the capa-
bility to be programmed in-circuit. Erasing requires that the program memory be
exposed to UV light.
Event A description of a bus cycle which may include address, data, pass count, external
input, cycle type (fetch, R/W), and time stamp. Events are used to describe triggers
and break points.
Expressions Expressions are used in the operand field of the MPASM Assembler source
line and may contain constants, symbols, or any combination of constants and sym-
bols separated by arithmetic operators. Each constant or symbol may be preceded
by a plus or minus to indicate a positive or negative expression.
External RAM (PIC17Cxxx and PIC18Cxxx Devices Only) Off-chip Read / Wri-
te memory.
EXTRC External Resistor-Capacitor (RC). Some devices have a device oscillator option
that allows the clock to come from an external RC. This is the same as RC mode
on some devices.
Flash A type of EEPROM where data is written or erased in blocks instead of bytes.
FLASH Memory This memory has the capability to be programmed and erased in-
circuit. Program Memory technology that is almost functionally equivalent to Pro-
gram EEPROM Memory.
99
Import Bring data into the MPLAB IDE from an outside source, such as from a hex file.
Indirect Addressing When the Data Memory Address is not contained in the Instruc-
tion, the instruction operates on the INDF address, which causes the Data Memory
Address to be the value in the FSR register. The execution of the instruction will
always access the data at the address pointed to by the FSR register.
Initialized Data Data which is defined with an initial value. In C, int myVar=5; defines
a variable which will reside in an initialized data section.
Instruction Bus The bus which is used to transfer instruction words from the program
memory to the CPU.
Instruction Cycle The events for an instruction to execute. There are four events which
can generally be described as: Decode, Read, Execute, and Write. Not all events
will be done by all instructions. To see the operations during the instruction cycle,
please look at the description of each instruction. Four external clocks(TOSC) make
one instruction cycle (TCY).
Instruction Fetch Due to the Harvard architecture, when one instruction is to be exe-
cuted, the next location in program memory is fetched and ready to be decoded as
soon as the currently executing instruction is completed.
Interrupt A signal to the CPU that causes the program flow to be forced to the Interrupt
Vector Address (04h in program memory). Before the program flow is changed, the
contents of the Program Counter (PC) are forced onto the hardware stack, so that
program execution may return to the interrupted point.
INTRC Internal Resistor-Capacitor (RC). Some devices have a device oscillator option
that allows the clock to come from an internal RC combination.
LCD Liquid Crystal Display. Useful for giving visual status of a system. This may require
the specification of custom LCD glass.
LED Light Emitting Diode. Useful for giving visual status of a system.
Librarian A language tool that creates and manipulates libraries. MPLIB; is Microchip’s
librarian.
LIN Protocol Specification A low cost, short-distance, low speed network designed to
transmit changes in switch settings and respond to switch changes. Used in many
automotive subsystems.
Linker A language tool that combines object files and libraries to create executable code.
Linking is performed by Microchip’s linker, MPLINK LINKER.
Linker Script Files Linker script files are the command files of the MPLINK LINKER
(.LKR). They define linker options and describe available memory on the target
platform.
Listing File A listing file is an ASCII text file that shows the machine code generated
for each C source statement, assembly instruction, MPASM Assembler directive, or
macro encountered in a source file.
Logic Probes Up to 14 logic probes connected to the emulator. The logic probes provide
external trace inputs, trigger output signal, +5V, and a common ground.
Long Word Instruction An instruction word that embeds all the required information
(opcode and data) into a single word. This ensures that every instruction is accessed
and executed in a single instruction cycle.
LP One of the device oscillator modes. Used for low frequency operation which allows
the oscillator to be tuned for low power consumption. Operation is up to 200 kHz.
Machine cycle This is a concept where the device clock is divided down to a unit time.
For PICmicro devices, this unit time is 4 times the device oscillator(4TOSC), also
known as TCY.
Macro A collection of assembler instructions that are included in the assembly code when
the macro name is encountered in the source code. Macros must be defined before
they are used; forward references to macros are not allowed.
Master Synchronous Serial Port The MSSP has two operational functions. The first
is a “Serial Peripheral Interface (SPI)” and the second is the Inter-Integrated Circuit
(“I2C”). The I2C function supports both master and slave functions in hardware.
Memory Models Versions of libraries and/or precompiled object files based on a device’s
memory (RAM/ROM) size and structure.
102
Microcontroller A highly integrated chip that contains all the components comprising
a controller. Typically this includes a CPU, RAM, some form of ROM, I/O ports,
and timers. Unlike a general-purpose computer, which also includes all of these
components, a microcontroller is designed for a very specific task - to control a
particular system. As a result, the parts can be simplified and reduced, which cuts
down on production costs.
MIPS The unit commonly used to give the rate at which a processor executes instruc-
tions.
Mnemonics Instructions that are translated directly into machine code. Mnemonics are
used to perform arithmetic and logical operations on data residing in program or
data memory of a microcontroller. They can also move data in and out of registers
and memory as well as change the flow of program execution. Also referred to as
Opcodes.
MPLAB ICD Microchip’s in-circuit debugger for PIC16F87X devices. MPLAB ICD
works with MPLAB IDE. The MPLAB ICD system consists of a module, header,
demo board (optional), cables, and MPLAB Software.
MPLAB ICE Microchip’s in-circuit emulator that works with MPLAB IDE.
MPLAB IDE The name of the main executable program that supports the IDE with an
Editor, Project Manager, and Emulator/Simulator Debugger. The MPLAB Software
resides on the PC host. The executable file name is MPLAB.EXE. MPLAB.EXE
calls many other files.
MPLIB; Librarian MPLAB Librarian is a librarian for use with COFF object modules
(filename.o) created using either MPASM v2.0, MPASMWIN v2.0, or MPLAB C
v2.0 or later. The MPLAB Librarian will combine multiple object files into one
library file. Then the MPLAB Librarian can be used to manipulate the object files
within the created library.
MPLINK LINKER MPLINK LINKER is a linker for the Microchip relocatable assem-
bler, MPASM Assembler, and the Microchip C compilers, MPLAB C17 or MPLAB
C18. MPLINK LINKER also may be used with the Microchip librarian, MPLAB
Librarian. MPLINK LINKER is designed to be used with MPLAB IDE, though it
does not have to be. MPLINK LINKER will combine object files and libraries to
create a single executable file.
103
MPSIM; Simulator The DOS version of Microchip’s simulator. MPLAB SIM is the
newest simulator from Microchip.
Non-Return to Zero (NRZ) Two-level encoding used to transmit data over a commu-
nications medium. A bit value of ’1’ indicates a high voltage signal. A bit value of
’0’ indicates a low voltage signal. The data line defaults to a high level.
Object Code The intermediate code that is produced from the source code after it is
processed by an assembler or compiler. Relocatable code is code produced by MPA-
SM Assembler or MPLAB C17/C18 that can be run through MPLINK LINKER to
create executable code. Object code is contained in an object file.
Opcode The portion of the 16-bit instruction word that specifies the operation that needs
to occur. The opcode is of variable length depending on the instruction that needs
to be executed. The opcode varies from 4-bits to 8-bits. The remainder of the
instruction word contains program or data memory information.
Oscillator Start-up Timer (OST) This timer counts 1024 crystal/resonator oscillator
clock cycles before releasing the internal RESET signal.
OTP One-Time-Programmable
Pages Method of addressing the Program Memory. Mid-range devices have 11-bit ad-
dressing for CALL and GOTO instructions, which gives these instructions a 2-Kword
reach. To allow more program memory to be present on a device, program memory
is partitioned into contiguous pages, where each page is 2-Kwords. To select the
desired page, the page selection bits (PCLATCH<5:4>) need to be appropriately
configured. Since there are presently 2 page selection bits, 4 pages can be imple-
mented. The enhanced devices do not have paging. PIC16CXXX code migrates to
the PIC18CXXX without modification (with respect to paging). Optimization may
be implemented.
Parallel Slave Port (PSP) A parallel communication port which is used to interface
to a microprocessor’s 8-bit data bus.
PC Host Any IBM or compatible Personal Computer running Windows 3.1x or Win-
dows 95/98, Windows NT, or Windows 2000. MPLAB IDE runs on 486 or higher
machines.
104
PICMASTER; Emulator The hardware unit that provides tools for emulating and
debugging firmware applications. This unit contains emulation memory, break point
logic, counters, timers, and a trace analyzer among some of its tools. MPLAB ICE
is the newest emulator from Microchip.
POP A term used to refer to the action of restoring information from a stack(software
and/or hardware). See “Serial Peripheral Interface (SPI)”.
Postscaler A circuit that slows the rate of the interrupt generation (or WDT Reset) from
a counter/timer by dividing it down.
Power-on Reset (POR) Circuitry which determines if the device power supply voltage
rose from a powered down level (0V). If the device power supply voltage is rising
from ground, a device RESET occurs and the PWRT is started.
Power-up Timer (PWRT) A timer which holds the internal RESET signal low for a
timed delay to allow the device voltage to reach the valid operating voltage range.
Once the timer times out, the OST circuitry is enabled (for all crystal/resonator
device oscillator modes).
Program Bus The bus used to transfer instruction words from the program memory to
the CPU.
Program Counter A register which specifies the address in program memory that con-
tains the next instruction to execute.
Project A set of source files and instructions to build the object and executable code for
an application.
Pulse Width Modulation (PWM) A serial signal in which the information is contai-
ned in the width of a(high) pulse of a constant frequency signal. A PWM output,
from the CCP module, of the same duty cycle requires no software overhead. Pulse
Width Modulation Signals. Certain PICmicro devices have a PWM peripheral.
PUSH A term used to refer to the action of saving information onto a stack (software
and/or hardware). See “Serial Peripheral Interface (SPI)”.
Q-cycles This is the same as a device oscillator cycle. There are 4 Q-cycles for each
instruction cycle.
Raw Data The binary representation of code or data associated with a section.
RC Resistor-Capacitor. The default configuration for the device oscillator. This allows
for a cost effective implementation for the device clock source. This clock source
does not supply an accurate time-base.
Read-Modify-Write This is where a register is read, then modified, and then written
back to the original register. This may be done in one instruction cycle or multiple
instruction cycles.
Register File This is the Data Memory. Contains the SFRs and GPRs.
Real-Time When released from the halt state in the emulator or MPLAB ICD mode,
the processor runs in real-time mode and behaves exactly as the normal chip would
behave. In real-time mode, the real-time trace buffer of MPLAB ICE is enabled and
constantly captures all selected cycles, and all break logic is enabled. In the emulator
or MPLAB ICD, the processor executes in real-time until a valid break point causes
a halt, or until the user halts the emulator. In the simulator real-time simply means
execution of the microcontroller instructions as fast as they can be simulated by the
host CPU.
ROM Read Only Memory. Memory that is fixed and cannot be modified.
Sampling Time Sampling time is the complete time to get an A/D result. It includes
the acquisition time and the conversion time.
Serial Peripheral Interface (SPI) This is one of the modes of the SSP and MSSP
modules. This is typically a 3-wire interface, with a data out line, a data in line,
and a clock line. Since the clock is present, this is a synchronous interface.
Section An portion of code or data which has a name, size, and address.
106
SFR Special Function Register. These registers contain the control bits and status
information for the device.
Shared Section A section which resides in a shared (non-banked) region of data RAM.
Simulator A software program that models the operation of the PICmicro microproces-
sor.
Single Cycle Instruction An instruction that executes in a single machine cycle (TCY).
Sleep This is a low power mode of the device, where the device’s oscillator circuitry is
disabled. This reduces the current the device consumes. Certain peripherals may be
placed into modes where they continue to operate.
Source Code - Assembly Source code consists of PICmicro instructions and the MPA-
SMAssembler directives and macros that will be translated into machine code by an
assembler.
Source Code - C A program written in the high level language called “C” which will
be converted into PICmicro machine code by a compiler. Machine code is suitable
for use by a PICmicro MCU or Microchip development system product like MPLAB
IDE.
Source File - Assembly The ASCII text file of PICmicro instructions and the MPASM
Assembler directives and macros (source code) that will be translated into machine
code by an assembler. It is an ASCII file that can be created using any ASCII text
editor.
Source File - C The ASCII text file containing C source code that will be translated
into machine code by a compiler. It is an ASCII file that can be created using any
ASCII text editor.
Special Function Registers (SFR) These registers contain the control bits and status
information for the device.
SSP Synchronous Serial Port. The SSP has two operational functions. The first is a
“Serial Peripheral Interface (SPI)” and the second is the Inter-Integrated Circuit
(I2C). The I2C function supports the slave function in hardware and has additional
status information to support a software implemented master.
Stack - Hardware An area in PICmicro MCU memory where function arguments, re-
turn values, local variables, and return addresses are stored; i.e., a “Push-Down”
list of calling routines. Each time a PICmicro MCU executes a CALL or responds
to an interrupt, the software pushes the return address to the stack. A return com-
mand pops the address from the stack and puts it in the program counter. The
PIC18CXXX family also has a hardware stack to store register values for “fast”
interrupts.
107
Stack - Software The compiler uses a software stack for storing local variables and for
passing arguments to and returning values from functions.
Static RAM or SRAM Static Random Access Memory. Program memory you can
Read/Write on the target board that does not need refreshing frequently.
TAD In the A/D Converter, the time for a single bit of the analog voltage to be converted
to a digital value.
Target Board The circuitry and programmable device that makes up the target appli-
cation.
Target Processor The microcontroller device on the target application board that is
being emulated.
TCY The time for an instruction to complete. This time is equal to Fosc/4 and is divided
into four Q-cycles.
Tosc The time for the single period of the device oscillator.
Upload The Upload function transfers data from a tool, such as an emulator or program-
mer, to the host PC or from the target board to the emulator.
Voltage Reference (VREF) A voltage level that can be used as a reference point for
A/D conversions (A VDD and A VSS) or the trip point for comparators.
Von Neumann Acrchitecture In this architecture the Program memory and Data Me-
mory are contained in the same area. This means that accesses to the program
memory and data memory must occur sequentially, which affects the performance
of the device.
Watchdog Timer (WDT) A timer on a PICmicro microcontroller that resets the pro-
cessor after a selectable length of time. The WDT is enabled or disabled and set up
using configuration bits.
Appendice E
Application Notes
Microchip Documentation The following documents are available from Microchip. Many
of these documents provide application specific information that give actual examples of
using, programming and designing with PICmicro MCUs.
Fundamentals
Programmazione