You are on page 1of 115

An introduction to PICMicro Microcontrollers

Nicholas Amadori

21 dicembre 2004
Indice

1 Architecture and Hardware Design 5


1.1 Generalities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 PIC Families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.1 Memory Varieties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.2 Logical Families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2.3 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.2.4 How to choose the right MCU for your needs . . . . . . . . . . . . . 12
1.3 Core Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.1 CPU (Central Processing Unit) . . . . . . . . . . . . . . . . . . . . . 15
1.3.2 ALU (Arithmetic Logical Unit) . . . . . . . . . . . . . . . . . . . . . 15
1.3.3 Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.3.4 Reset logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.5 Memory Organization . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.3.6 Device configuration bits . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.7 Watchdog Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.3.8 Low power mode (Sleep) . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.3.9 Table Read/Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.3.10 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.4 Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.4.1 Generic I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.4.2 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.4.3 Capture, Compare, PWM (CCP) . . . . . . . . . . . . . . . . . . . . 38
1.4.4 Serial ports and protocols . . . . . . . . . . . . . . . . . . . . . . . . 42
1.4.5 LCD driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.4.6 Comparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.4.7 Voltage References . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.4.8 A/D converters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.4.9 Parallel Slave Port (PSP) . . . . . . . . . . . . . . . . . . . . . . . . 53
1.4.10 USB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
1.5 In-Circuit Serial Programming . . . . . . . . . . . . . . . . . . . . . . . . . 55

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

A Descrizione della PICDEM2 plus 83

B Realizzazione di una demo-board 85


B.1 16F84 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
B.1.1 Schema elettrico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
B.1.2 Circuito stampato . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

C Instruction sets 88
C.1 PIC16F84A e PIC16F87x . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
C.2 PIC18F45x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

D Glossary 94

E Application Notes 108


Elenco delle figure

1.1 MID-Range PICMicro architecture . . . . . . . . . . . . . . . . . . . . . . . 6


1.2 Architectures: Harvard vs. von Neumann . . . . . . . . . . . . . . . . . . . 7
1.3 Two-stage Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Packaging of PICmicro MCUs . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 Packaging of PICmicro MCUs (continued) . . . . . . . . . . . . . . . . . . . 14
1.6 ALU and WREG register operation . . . . . . . . . . . . . . . . . . . . . . . 16
1.7 8 x 8 Unsigned Multiply Routine . . . . . . . . . . . . . . . . . . . . . . . . 17
1.8 8 x 8 Signed Multiply Routine . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9 Internal instruction clock (TCY) . . . . . . . . . . . . . . . . . . . . . . . . 18
1.10 Typical crystal oscillator configuration . . . . . . . . . . . . . . . . . . . . . 19
1.11 Typical RC oscillator configuration . . . . . . . . . . . . . . . . . . . . . . . 20
1.12 Example RC Oscillator Frequency vs. VDD . . . . . . . . . . . . . . . . . . 21
1.13 Reset circuitry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.14 Mid-range devices memory map . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.15 Example: call of a subroutine in page 1 from page 0 . . . . . . . . . . . . . 25
1.16 PIC18x PC structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.17 Example: Specify configuration bits using the CONFIG directive . . . . . . 28
1.18 Example: Interrupt Service Routine Template . . . . . . . . . . . . . . . . . 31
1.19 Example: Interrupt Initialization . . . . . . . . . . . . . . . . . . . . . . . . 32
1.20 Generic I/O port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.21 Initializing PORTA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.22 PORTB block diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.23 Timer0 simplified block diagram . . . . . . . . . . . . . . . . . . . . . . . . 37
1.24 Initializing Timer0 on PIC16F . . . . . . . . . . . . . . . . . . . . . . . . . 37
1.25 PWM Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1.26 I2C connections and data format . . . . . . . . . . . . . . . . . . . . . . . . 46
1.27 Example of a CAN network . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.28 Single Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.29 Comparator Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.30 Vref diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.31 8-bit A/D converter module diagram . . . . . . . . . . . . . . . . . . . . . . 51
1.32 A/D conversion example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
1.33 USB external circuitry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
1.34 Typical In-Circuit Serial Programming (ICSP) Application Circuit . . . . . 56
ELENCO DELLE FIGURE IV

2.1 LED connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58


2.2 Multiple 7-segments display wiring . . . . . . . . . . . . . . . . . . . . . . . 58
2.3 Swich bouncing signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.4 Hardware debounce circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.5 Relay control circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.6 H-bridge circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.7 Using the 293D to control a motor . . . . . . . . . . . . . . . . . . . . . . . 61
2.8 Functional block diagram of LMD18200 . . . . . . . . . . . . . . . . . . . . 62
2.9 Piedinatura e descrizione del MAX232 . . . . . . . . . . . . . . . . . . . . . 63

3.1 La finestra principale di Application Maestro . . . . . . . . . . . . . . . . . 66


3.2 FilterLab in azione . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.3 Files generati dal compilatore . . . . . . . . . . . . . . . . . . . . . . . . . . 68

4.1 Lampeggio di un LED senza interrupt . . . . . . . . . . . . . . . . . . . . . 73


4.2 Lampeggio Led: Diagramma di flusso . . . . . . . . . . . . . . . . . . . . . 74
4.3 Lampeggio di un LED, Codice HEX . . . . . . . . . . . . . . . . . . . . . . 75
4.4 Lampeggio di un LED con interrupt . . . . . . . . . . . . . . . . . . . . . . 76
4.5 Posizione in memoria dell’esempio Lampeggio LED con interrupt . . . . . . 77
4.6 Generazione PWM (1/4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.7 Generazione PWM (2/4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.8 Generazione PWM (3/4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.9 Generazione PWM (4/4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

A.1 PICDEM2 plus hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

B.1 Posizionamento dei componenti demo board A . . . . . . . . . . . . . . . . 86


B.2 Piedinatura e descrizione del MAX232 . . . . . . . . . . . . . . . . . . . . . 86
B.3 Circuito stampato demo board A . . . . . . . . . . . . . . . . . . . . . . . . 87
B.4 Circuito stampato demo board B . . . . . . . . . . . . . . . . . . . . . . . . 87
Elenco delle tabelle

1.1 Example RC oscillator frequencies . . . . . . . . . . . . . . . . . . . . . . . 22


1.2 Interaction between two CCP modules . . . . . . . . . . . . . . . . . . . . . 39
1.3 Minimum Duty Cycle Bit Time . . . . . . . . . . . . . . . . . . . . . . . . . 41

A.1 PICDEM2 plus connections . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

C.1 PIC16F84A instruction set . . . . . . . . . . . . . . . . . . . . . . . . . . . 90


C.2 PIC18F45x instruction set . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C.3 PIC18F45x instruction set (continued) . . . . . . . . . . . . . . . . . . . . . 92
C.4 Istruction set conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Introduzione

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

il debug. Nel capitolo 4 due esempi mettono in pratica quanto illustrato.


Nelle appendici si trovano la descrizione della scheda scheda di test PICDEM2 plus,
gli schemi per realizzare una scheda “custom” basata sul PIC16F84A dotata di interfaccia
seriale, i set di istruzioni dei PIC16F84A e PIC18F45x utilizzati negli esempi. Chiudono
la relazione un esaustivo glossario dei termini tecnici e la bibliografia delle Application
Notes più utili.
Ringraziamenti

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

Architecture Description and


Hardware Design

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

• Long Word Instructions

• Single Word Instructions

• Single Cycle Instructions

• Instruction Pipelining

• Reduced Instruction Set

• Register File Architecture

• Orthogonal (Symmetric) Instructions

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

13 Data Bus 8 PORTA


EPROM Program Counter
RA0
Program RA1
Memory RAM RA2
up to 8 Level Stack File RA3
8K x 14 (13-bit) Registers RA4
up to RA5
368 x 8
Program 14
Bus RAM Addr (1) 9 PORTB
RB0/INT
Addr MUX RB1
Instruction reg
RB2
Direct Addr 7 Indirect RB3
8 Addr
RB4
FSR reg RB5
RB6
STATUS reg RB7
8 PORTC
RC0
RC1
3 RC2
Power-up MUX
RC3
Timer
RC4
Instruction Oscillator RC5
Decode & Start-up Timer ALU RC6
Control RC7
Power-on
Reset 8
PORTD
Timing Watchdog RD0
Generation Timer W reg
RD1
OSC1/CLKIN Brown-out RD2
OSC2/CLKOUT Internal Reset (2)
RC clock (2) RD3
RD4
RD5
RD6
RD7
PORTE
MCLR VDD, VSS RE0
RE1
RE2
RE3
RE4
RE5
Timer0 Timer1 Timer2 A/D RE6
RE7

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

Peripheral Modules (Note 3) General Purpose I/O


(Note 3)

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.

Figura 1.1: MID-Range PICMicro architecture


1.1. GENERALITIES 7

Harvard (PICmicro)

Data 8 12-16 Program


CPU
memory memory

Von Neumann

8 Program
CPU and data
memory

Figura 1.2: Architectures: Harvard vs. von Neumann

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

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.

Single Word Instructions

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.

Double Word 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.

TCY0 TCY1 TCY2 TCY3 TCY4 TCY5


1. MOVLW 55h Fetch 1 Execute 1
2. MOVWF PORTB Fetch 2 Execute 2
3. BRA SUB_1 Fetch 3 Execute 3
4. BSF PORTA, BIT3 (Forced NOP) Fetch 4 Flush (NOP)
5. Instruction @ address SUB_1 Fetch SUB_1 Execute SUB_1

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.

Figura 1.3: Two-stage Pipeline

1
see section 1.2.2
1.2. PIC FAMILIES 9

Single Cycle Instructions

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.

Reduced Instruction Set

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.

Register File Architecture

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 (Symmetric) Instructions

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.

1.2 PIC Families

1.2.1 Memory Varieties

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, identified with the letter CR, as in PIC16CRxxx.

EPROM devices, identified with the letter C, as in PIC16Cxxx.


1.2. PIC FAMILIES 10

FLASH devices, identified with the letter F, as in PIC16Fxxx.

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.

Flash Memory Devices

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.

1.2.2 Logical Families

PICmicro devices are grouped by the size of their Instruction Word. The three current
PICmicro families are:

1. Base-Line: 12-bit Instruction Word length

2. Mid-Range: 14-bit Instruction Word length

3. High-End: 16-bit Instruction Word length


1.2. PIC FAMILIES 11

PIC12 Family: 8-pin 12-bit/14-bit program word

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.

PIC16C5x Family: 12-bit program word

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.

PIC16xxxx Family: 14-bit program word

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.

PIC17Cxxx Family: 16-bit program word

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.

PIC18xxxx Family: enhanced 16-bit program word

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.

1.2.4 How to choose the right MCU for your needs

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”

40-LEAD CERDIP 24-LEAD PDIP


“JW” “P” OR “PG” PLASTIC QUAD
FLATPACK
“QFP”

Figura 1.4: Packaging of PICmicro MCUs


CERAMIC CHIP CARRIER
CERQUAD
84-LEAD PLCC
“L”
44-LEAD MQFP
“PQ”

68-LEAD CERQUAD 84-LEAD CERQUAD


“CL” “CL”
13
PLASTIC SHRINK PLASTIC THIN QUAD SIDE BRAZED
PLASTIC SMALL OUTLINE SMALL OUTLINE FLATPACK DUAL-IN-LINE
“SOIC” “SSOP” “TQFP” “JW”

8-LEAD SOIC 16-LEAD SOIC


1.2. PIC FAMILIES

20-LEAD SSOP 28-LEAD SSOP 8-LEAD SIDE BRAZED


(.150”) “SN” OR “OA” (.150”) “SL”
“SS” “SS” “JW”
44-LEAD TQFP
“PT”

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”

8-LEAD TSSOP 6-LEAD SOT-23


8-LEAD DFN 3-LEAD TRANSISTOR
“CH” or “OT” 5-LEAD SOT-23
(4.4MM) “ST” “MF” “TO” OR “ZB”
“OT” OR “CT”

3-LEAD SC-89 3-LEAD SOT-23


14-LEAD TSSOP
28-LEAD QFN “TT” OR “CB” 5-LEAD SC-70
(4.4MM) “ST” (PICmicro MCU)
“ML”

Figura 1.5: Packaging of PICmicro MCUs (continued)


(4.4MM) “ST14” (MEMORY)

SOT-143
“RC” 3-LEAD SC-70
44-LEAD QFN
20-LEAD TSSOP
“ML”
(4.4MM) “ST”
14
1.3. CORE FEATURES 15

1.3 Core Features

The core pertains to the basic features that are required to make the device operate. These
include:

• Oscillator

• Reset Logic

• CPU (Central Processing Unit) and ALU (Arithmetic Logical Unit)

• Memory

• Configuration bits

• Watchdog timer

• Interrupts

1.3.1 CPU (Central Processing Unit)

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.

1.3.2 ALU (Arithmetic Logical Unit)

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-bit literal Register


(from instruction word) File

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

Figura 1.6: ALU and WREG register operation

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.

Hardware 8x8 Multiplier

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.

MOVFF ARG1, WREG ;


MULWF ARG2 ; ARG1 * ARG2 -> PRODH:PRODL

Figura 1.7: 8 x 8 Unsigned Multiply Routine

MOVFF ARG1, WREG


MULWF ARG2 ; ARG1 * ARG2 -> PRODH:PRODL
BTFSC ARG2, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH - ARG1
MOVFF ARG2, WREG
BTFSC ARG1, SB ; Test Sign Bit
SUBWF PRODH, F ; PRODH = PRODH - ARG2

Figura 1.8: 8 x 8 Signed Multiply Routine

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

TCY1 TCY2 TCY3

Figura 1.9: Internal instruction clock (TCY)

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.

Figura 1.10: Typical crystal oscillator configuration

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

• External resistor (REXT) values

• External capacitor (CEXT) values

• 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.

Figura 1.11: Typical RC oscillator configuration

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.

Internal 4 MHz RC Oscillator

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

C EXT = 300 pF, T = 25°C


1000

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)

Figura 1.12: Example RC Oscillator Frequency vs. VDD

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.

1.3.4 Reset logic

The reset logic is used to place the device into a known state. Devices differentiate between
various kinds of reset:

• Power-on Reset (POR)

• MCLR Reset

• WDT Reset (normal operation)

• Programmable Brown-out Reset (BOR)

• RESET Instruction
1.3. CORE FEATURES 22

Average
CEXT R EXT
Fosc @ 5V, 25°C

22 pF 5k 4.12 MHz ± 1.4%


10k 2.35 MHz ± 1.4%
100k 268 kHz ± 1.1%
100 pF 3.3k 1.80 MHz ± 1.0%
5k 1.27 MHz ± 1.0%
10k 688 kHz ± 1.2%
100k 77.2 kHz ± 1.0%
300 pF 3.3k 707 kHz ± 1.4%
5k 501 kHz ± 1.2%
10k 269 kHz ± 1.6%
100k 28.3 kHz ± 1.1%
The percentage variation indicated here is part to part variation due to normal process distribu-
tion. The variation indicated is ±3 standard deviation from average value for V DD = 5V.

Tabella 1.1: Example RC oscillator frequencies

• Stack Overflow or Underflow Reset

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

Figura 1.13: Reset circuitry

1.3.5 Memory Organization

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

PC<12:0> PC<12:8> PCL


CALL, RETURN
RETFIE, RETLW 13

Stack Level 1

Stack Level 8

Reset Vector 0000h

2K Interrupt Vector 0004h


4K 0005h
On-chip Program
Memory (Page 0)
6K 07FFh
0800h
8K On-chip Program
Memory (Page 1)
0FFFh
1000h
On-chip Program
Memory (Page 2)
17FFh
1800h
On-chip Program
Memory (Page 3)
1FFFh

Note 1: Not all devices implement the entire program memory space
2: Calibration Data may be programmed into program memory locations.

Figura 1.14: Mid-range devices memory map

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)

Figura 1.15: Example: call of a subroutine in page 1 from page 0

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

PC PCU PCH PCL

23 21 20 16 15 8 7 0

Reserved. Maintain these bits cleared.

Figura 1.16: PIC18x PC structure

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.

1.3.6 Device configuration bits

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.

1.3.7 Watchdog Timer

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

LIST p = p18C452 ; List Directive,

#INCLUDE <P18C452.INC> ; Microchip Device Header File

#INCLUDE <MY_STD.MAC> ; File which includes my standard macros


#INCLUDE <APP.MAC> ; File which includes macros specific
; to this application

; Specify Device Configuration Bits for


; Program Configuration Registers 0 through 6

__CONFIG _CONFIG0, CP_OFF_0


__CONFIG _CONFIG1, LPSCEN_OFF_1 & RCRA6_OSC_1
__CONFIG _CONFIG2, BORV_25_2 & BOREN_ON_2 & PWRTEN_OFF_2
__CONFIG _CONFIG3, WDPS_128_3 & WDT_ON_3
__CONFIG _CONFIG5, CCP2MX_ON_5
__CONFIG _CONFIG6, SVTREN_ON_6

org 0x00 ; Start of Program Memory


RESET_ADDR : ; First instruction to exec after a reset

end

Figura 1.17: Example: Specify configuration bits using the CONFIG directive

1.3.8 Low power mode (Sleep)

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 device reset, such as MCLR or Brown-out reset.

• Watchdog Timer Wake-up (if WDT was enabled).

• 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.

1.3.9 Table Read/Write

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:

• External interrupt from the INT, INT1, and INT2 pins

• Change on RB7:RB4 pins

• Timer overflow

• Interfaces (USART, SSP, PSP, CAN)

• Peripherals (A/D, CCP ecc...)

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

• Capture, Compare, PWM

• Serial ports and protocols (SSP, MSSP, USART, I2 C, CAN)


1.4. PERIPHERALS 31

ORG 0x08 ; high priority ISR

; Save status for High Priority Interrupts

PUSH_REG_H MOVWF WREG_TEMP_HIGH


MOVFF BSR, BSR_TEMP_HIGH
MOVFF STATUS, STATUS_TEMP_HIGH

;
; High Priority Interrupt Service Routine (ISR) Code goes here
;

; Restore status after servicing interrupt

POP_REG_H MOVFF BSR_TEMP_HIGH, BSR


MOVF WREG_TEMP_HIGH, W
MOVFF STATUS_TEMP_HIGH, STATUS

RETFIE 0x00

ORG 0x18 ; Low Priority ISR

; Save status for High Priority Interrupts

PUSH_REG_L MOVWF WREG_TEMP_LOW


MOVFF BSR, BSR_TEMP_LOW
MOVFF STATUS, STATUS_TEMP_LOW

;
; Low Priority Interrupt Service Routine (ISR) code goes here
;

; Restore status after servicing interrupt

POP_REG_L MOVFF BSR_TEMP_LOW, BSR


MOVF WREG_TEMP_LOW
MOVFF STATUS_TEMP_LOW, STATUS

RETFIE 0x00

Figura 1.18: Example: Interrupt Service Routine Template


1.4. PERIPHERALS 32

RIVEDERE

MOVLW RCON_VALUE ; RCON_VALUE = 1???????b


MOVWF RCON

MOVLW IPR1_VALUE ; Peripherals with high priority


; have a ’1’ in their bit position.
; Those with a low priority have
; a ’0’ in their bit position.
MOVWF IRP1

CLRF PIR1 ; Clear all flag bits

MOVLW PIE1_VALUE ; Enable desired peripheral interrupts


; by setting their bit position.
MOVWF PIE1

CLRF INTCON3
CLRF INTCON2
MOVLW OxC0 ; Enable high and low global interrupts.
MOVWF INTCON

Figura 1.19: Example: Interrupt Initialization

• Voltage References

• Comparators

• A/D converters

• Parallel Slave Port

• USB

1.4.1 Generic I/O

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

Note: I/O pin has protection diodes to VDD and VSS.

Figura 1.20: Generic I/O 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

• Clear flag bit RBIF.


9
The MOVFF instruction will not end the mismatch condition if PORTB is used only as the destination
register.
1.4. PERIPHERALS 35

CLRF STATUS ; Bank0


CLRF PORTA ; Initialize PORTA clearing output latches
BSF STATUS, RP0 ; Select Bank1
MOVLW 0xCF ; Value used to initialize data direction
MOVWF TRISA ; PORTA<3:0> = inputs
; PORTA<5:4> = outputs
; TRISA<7:6> always read as ’0’

Figura 1.21: Initializing PORTA

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.

PORTC, PORTD, PORTE, PORTG, PORTH, PORTJ, PORTK, PORTL

PORTC-D-E-G-H-J-K-L are 8-bit bi-directional port. Each pin is individually configurable


as an input or output through the TRISx (LATx) register. All pins have Schmitt Trigger
input buffers. Depending on the device they can be multiplexed with other peripherals.

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

• Readable and writable

• 8-bit software programmable prescaler

• Clock source selectable to be external or internal


1.4. PERIPHERALS 36

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

Schmitt Trigger RD Port


Buffer
Note 1: I/O pins have diode protection to VDD and VSS.
2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear
the RBPU bit (OPTION<7>).

Figura 1.22: PORTB block diagram

• Interrupt on overflow from FFh to 00h

• Edge select for external clock

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

Figura 1.23: Timer0 simplified block diagram

CLRF TMR0 ; Clear Timer0 register


CLRF INTCON ; Disable interrupts and clear T0IF
BSF STATUS, RP0 ; Bank1
MOVLW 0xC3 ; PortB pull-ups are disabled,
MOVWF OPTION_REG ; Interrupt on rising edge of RB0
; Timer0 increment from internal clock
; with a prescaler of 1:16.
BCF STATUS, RP0 ; Bank0

;** BSF INTCON, T0IE ; Enable TMR0 interrupt


;** BSF INTCON, GIE ; Enable all interrupts

Figura 1.24: Initializing Timer0 on PIC16F

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.

1.4.3 Capture, Compare, PWM (CCP)

The CCP module is a peripheral that can operate in 3 different modes:

• Capture mode;

• Compare mode;

• PWM mode;

Each CCP (Capture/Compare/PWM) module has three 8-bit registers. These are:

• An 8-bit control register (CCPxCON)

• A 16-bit register (CCPRxH:CCPRxL) that operates as:

– a 16-bit capture register


– a 16-bit compare register
– a 10-bit PWM master/slave duty cycle register

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

CCPx Mode CCPy Mode Interaction

Capture Capture TMR1 or TMR3 time-base. Time base can be


different for each CCP.
Capture Compare The compare could be configured for the special
event trigger, which clears either TMR1 or TMR3
depending upon which time base is used.
Compare Compare The compare(s) could be configured for the spe-
cial event trigger, which clears TMR1 or TMR3
depending upon which time base is used.
PWM PWM The PWMs will have the same frequency, and
update rate (TMR2 interrupt).
PWM Capture None
PWM Compare None

Tabella 1.2: Interaction between two CCP modules

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:

• Every falling edge

• Every rising edge

• Every 4th rising edge

• Every 16th rising edge

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

• Toggle output (Low to High or High to Low)11

• Not affected (remains unchanged)

At the same time, interrupt flag bit CCPxIF is set.


The user must configure the CCPx pin as an output by clearing the appropriate TRIS
bit. Selecting the compare output mode, forces the state of the CCP pin to the state that
is opposite of the match state. So if the Compare mode is selected to force the output pin
low on match, then the output will be forced high until the match occurs (or the mode is
changed). In the compare toggle mode, the CCPx pin output is initially forced to the low
state.
The special event trigger output of CCPx resets the TMR1 register pair without setting
the Timer1 interrupt flag bit, TMR1IF. This allows the CCPRx register to effectively be
a 16-bit programmable period register for Timer1. For some devices, the special trigger
output of the CCP module resets the TMR1 register pair, and starts an A/D conversion
(if the A/D module is enabled).

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

Figura 1.25: PWM Output

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

PWMperiod = [(PR2) + 1] ∗ 4 ∗ Tosc ∗ (TMR2 prescale value)

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).

Prescaler Minimum Resolution (Time)

1 TSCLK
4 TCY
16 4 * TCY

Tabella 1.3: Minimum Duty Cycle Bit Time

The following steps configure the CCP module for PWM operation:

1. Establish the PWM period by writing to the PR2 register.

2. Establish the PWM duty cycle by writing to the DCxB9:DCxB0 bits.

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.

5. Configure the CCP module for PWM operation.

For a thorough explanation see “Using the CCP modules”, AN594 from Microchip web
site.
1.4. PERIPHERALS 42

1.4.4 Serial ports and protocols

SSP and MSSP

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:

• Serial Peripheral Interface (SPI)

• Inter-Integrated Circuit (I2C)

– 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

The Addressable Universal Synchronous Asynchronous Receiver Transmitter can be confi-


gured as a full duplex asynchronous system that can communicate with peripheral devices,
such as CRT terminals and personal computers, or it can be configured as a half duplex
synchronous system that can communicate with peripheral devices, such as A/D or D/A
integrated circuits, Serial EEPROMs, etc.
The Addressable USART can be configured in the following modes:

• Asynchronous (full duplex)


12
Some devices have a fully automated hardware implementation of I2C Master Mode (Master SSP).
Otherwise see Microchip Application Note AN578 for software which uses the SSP module to implement
master mode.
1.4. PERIPHERALS 43

• Synchronous - Master (half duplex)

• Synchronous - Slave (half duplex)

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.

7. Load data to the TXREG register (starts transmission).

Steps to follow when setting up an Asynchronous Reception:

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.

4. If 9-bit reception is desired, then set the RX9 bit.

5. Enable the reception by setting the CREN bit.

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.

8. Read the 8-bit received data by reading the RCREG register.

9. If any error occurred, clear the error by clearing the CREN bit.

Steps to follow when setting up an Asynchronous Reception:

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.

4. If 9-bit reception is desired, then set the RX9 bit.

5. Enable the reception by setting the CREN bit.

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.

8. Read the 8-bit received data by reading the RCREG register.

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

4. Set bit RX9 to enable 9-bit reception.

5. Set ADDEN to enable address detect.

6. Enable the reception by setting the CREN bit.

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

Figura 1.26: I2C connections and data format

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

CAN CAN CAN CAN


Transceiver Transceiver Transceiver Transceiver

Microchip Microchip
MCP2510 MCP2510
SPI
INTERFACE
PICmicro PIC18CXX8 PIC18CXX8 PICmicro
with integrated with integrated
Controller Controller
CAN CAN

Figura 1.27: Example of a CAN network

1.4.5 LCD driver

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

PIC16C92X ”, DS51079 “PICDEM3 Demo Board User’s Guide”.

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

Figura 1.28: Single Comparator

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

CM2:CM0 = 000 CM2:CM0 = 111


Comparators Reset (POR Default Value) Comparators Off

ANx0 A VIN - ANx0 D VIN -

A VIN + C1 Off (Read as '0') D VIN + C1 Off (Read as '0')


ANx3 ANx3

ANx1 A VIN - ANx1 D VIN -


A VIN + C2 Off (Read as '0') D VIN + C2 Off (Read as '0')
ANx2 ANx2

CM2:CM0 = 010 CM2:CM0 = 011


Two Independent Comparators Three Inputs Multiplexed to Two Comparators

ANx0 A VIN -
ANx0 A VIN -
C1OUT ANx3 A VIN + C1 C1OUT
A VIN + C1
ANx3
C1OUT

ANx1 A ANx1 A VIN -


VIN -
C2OUT A VIN + C2 C2OUT
A VIN + C2 ANx2
ANx2
C2OUT

CM2:CM0 = 100 CM2:CM0 = 101


Two Common Reference Comparators Two Common Reference Comparators with Outputs

ANx0 A VIN - ANx0 A VIN -

ANx3 A VIN + C1 C1OUT ANx3 A VIN + C1 C1OUT

C1OUT

ANx1 A VIN - ANx1 A VIN -


D VIN + C2 C2OUT D VIN + C2 C2OUT
ANx2 ANx2

C2OUT

CM2:CM0 = 001 CM2:CM0 = 110


One Independent Comparator Four Inputs Multiplexed to Two Comparators

ANx1 A VIN - ANx0 A


CIS = 0 VIN-
A VIN + C1 C1OUT A
ANx2 ANx3 CIS = 1
VIN+ C1 C1OUT
C1OUT
A
ANx1
CIS = 0 VIN-
ANx0 D VIN - A CIS = 1
ANx2 C2 C2OUT
VIN+
ANx3 D VIN + C1 Off (Read as '0')

From VREF Module

A = Analog Input, port reads as zeros always.


D = Digital Input.
CIS (CMCON<3>) is the Comparator Input Switch.

Figura 1.29: Comparator Modes


1.4. PERIPHERALS 50

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.

1.4.7 Voltage References

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

Figura 1.30: Vref diagram

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

1.4.8 A/D converters

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:

• A/D Result Register ADRES (ADRESH:ADRESL for the 10-bit)

• A/D Control Register0 ADCON0

• A/D Control Register1 ADCON1

• A/D Control Register2 ADCON2 for the 10-bit module

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

VDD (1) 000


AN0
000 or
VREF 010 or
100
(Reference
voltage) 001 or
011 or
101
PCFG2:PCFG0

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.

Figura 1.31: 8-bit A/D converter module diagram

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:

1. Configure the A/D module

• Configure analog pins, Voltage Reference, and digital I/O (ADCON1)


• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)13
• Turn on A/D module (ADCON0)

2. Configure A/D interrupt (if desired):

• Clear the ADIF bit


• Set the ADIE bit
• Set/Clear the ADIP bit
• Set the GIE/GIEH or PEIE/GIEL bit

3. Wait the required acquisition time.

4. Start conversion:

• Set the GO/DONE bit (ADCON0)

5. Wait for the A/D conversion to complete, by either:

• 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.

7. For next conversion, go to step 1 or step 2 as 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.

CLRF ADCON1 ; Configure A/D inputs,


; result is left justified
BSF IPR1, ADIP ; High Priority.
BSF PIE1, ADIE ; Enable A/D interrupts
MOVLW 0xC1 ; RC Clock, A/D is on,
MOVWF ADCON0 ; Channel 0 is selected
MOVLW 0x4E ; Left Justified, AN0 is analog
MOVWF ADCON1 ; Vref comes from AVDD and AVSS
BCF PIR1, ADIF ; Clear A/D interrupt flag bit
BSF INTCON, PEIE ; Enable peripheral interrupts
BSF INTCON, GIE ; Enable all interrupts

; Ensure that the required sampling time for the selected input
; channel has elapsed. Then the conversion may be started.

BSF ADCON0, GO ; Start A/D Conversion


: ; The ADIF bit will be set and the
: ; GO/DONE bit is cleared upon
: ; completion of the A/D Conversion.

Figura 1.32: A/D conversion example

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.

1.4.9 Parallel Slave Port (PSP)

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+

Note: The PIC16C745/765 requires an external resistor and


capacitor to communicate with a host over USB.

Figura 1.33: USB external circuitry

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.

1.5 In-Circuit Serial Programming

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.

PICmicro oscillator When using RC or EC oscillator, the programmer must drive


MCLR/VPP to the program mode entry voltage before the oscillator toggles four
times. If the MCLR pin does not rise fast enough, while the device’s voltage is in
the valid operating range, the internal Program Counter (PC) can increment, and
the entire program will be shifted (offset) in the device program memory.

Application PCB VDD /VPP V DD


PIC18CXXX R1
MCLR/V PP
R2 ICSP Connector
C1

VDD
VSS
DATA
CLOCK

To application circuit
Isolation circuits

Figura 1.34: Typical In-Circuit Serial Programming (ICSP) Application Circuit


Capitolo 2

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

Figura 2.1: LED connection

Figura 2.2: Multiple 7-segments display wiring

2.2 Switch de-bounce

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).

Figura 2.3: Swich bouncing signal


2.3. RELAIS AND SOLENOIDS 59

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.

Figura 2.4: Hardware debounce circuit

2.3 Relais and Solenoids

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

Figura 2.5: Relay control circuit

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

Figura 2.6: H-bridge circuit

Figura 2.7: Using the 293D to control a motor

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

Figura 2.8: Functional block diagram of LMD18200

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

DIP/SO 12 R1OUT R1IN 13

CAPACITANCE (µF) TTL/CMOS 5kΩ RS-232


OUTPUTS INPUTS
DEVICE C1 C2 C3 C4 C5
9 R2OUT R2IN 8
MAX220 4.7 4.7 10 10 4.7
MAX232 1.0 1.0 1.0 1.0 1.0
MAX232A 0.1 0.1 0.1 0.1 0.1 5kΩ

GND
15

Figura 2.9: Piedinatura e descrizione del MAX232


Capitolo 3

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.

3.1 Linguaggio Assembly

L’assembler è il linguaggio più semplice da utilizzare per programmi di piccole dimensioni,


o che devono essere particolarmente accurati nei tempi di esecuzione. Il set di istruzioni,
rimanendo sempre ridotto, varia all’interno della gamma di prodotti da 33 a 77 istruzioni.
Tutte le istruzioni appartengono ad una delle quattro categorie1 :

• Byte-oriented, che effettuano operazioni tra registri;

• Bit-oriented, che effettuano operazioni su singoli bit di registri;

• Letterali, che effettuano operazioni con costanti;

• Controllo, che modificano l’esecuzione del programma.

Elemento centrale della CPU dei PICmicro é il registro W o “accumulatore”. Tutte


le operazioni aritmetiche vengono effettuate tra un registro e l’accumulatore, e il risultato
può essere memorizzato nel registro o nell’accumulatore stesso. Ad esempio se vogliamo
aggiungere al registro RegistroA il registro RegistroB e memorizzare il risultato nel registro
RegistroB dobbiamo eseguire:
1
Per semplicità consideriamo impropriamente le istruzioni di Table Read e Table Write come operazioni
di controllo
3.2. LINGUAGGIO C 65

MOVF RegistroA, w : w indica di muovere verso l’accumulatore


ADDWF RegistroB, f : f indica di salvare il risultato nel registro

La memorizzazione del risultato nella sorgente elimina la necessità di istruzioni ag-


giuntive per memorizzare il risultato dell’operazione.
L’esecuzione di una operazione aritmetica influenza i bit di stato nel registro STATUS,
in particolar modo i bit N, OV, Z, DC, C che indicano la presenza rispettivamente di un
risultato Negativo (in complemento a due), un OVerflow, un risultato nullo (Zero), un
riporto sul digit2 (Digit Carry), un riporto (Carry). Ad esempio se vogliamo verificare
che il contenuto dei due registri RegistroA e RegistroB sia uguale possiamo effettuare una
sottrazione e controllare il bit Z del registro di stato:

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.1.1 Direttive di compilazione

I programmi sviluppati in liguaggio assembler possono contenere alcune direttive di com-


pilazione interpretate dall’assemblatore MPASM.
In particolare alcune direttive permettono di impostare alcuni flag di programmazione,
che altrimenti andrebbero selezionati nelle varie schermate di configurazione di MPLAB,
direttamente dal codice sorgente, evitando cosı̀ errori dovuti a distrazione o mancanza di
documentazione sul sorgente.
Altre direttive permettono di compilare condizionalmente sezioni di codice, similar-
mente al linguaggio C / C++.
Una breve guida di riferimento e’ il documento Microchip 30400f “MPASM Quick
Reference Guide”.

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

La programmazione in linguaggio C dei PICmicro verrà trattata in un documento


successivo.

3.3 Application Maestro

Recentemente la Microchip ha rilasciato un nuovo tool di sviluppo chiamato Application


Maestro. Grazie ad esso è possibile generare in pochi minuti delle librerie in grado di
gestire autonomamente funzioni quali USART, CAN, I2C o polling degli ADC, tagliate su
misura per la nostra applicazione.

Figura 3.1: La finestra principale di Application Maestro

La finestra principale del programma ci permette da scegliere du quali funzioni abbiamo


bisogno trascinandole nel riquadro di destra. A questo punto dobbiamo selezionare le
impostazioni necessarie per la nostra applicazione (ad esempio per la USART se abilitare
ricezione e/o trasmissione, il baud rate, ecc... ) e selezionare “Generate Code” . Nella
cartella scelta verranno generati tutti i file necessari completi di commenti pronti per essere
inclusi nel nostro progetto MPLAB.
Il tool e’ liberamente scaricabile dal sito della Microchip, insieme alla sua “Getting
started guide” documento 51329a, e alla “User’s guide” documento 51328a.
3.4. FILTERLAB 67

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:

• Design automatico di filtri attivi passa-basso Chebyshev, Bessel o Butterworth fino


all’8vo ordine, da 0.1 Hz a 10 MHz, con ottimizzazione per conversioni A/D;

• Implementazione del circuito con resistenze e condensatori standard;

• Analisi del circuito risultante;

• Generazione del modello Spice.

Figura 3.2: FilterLab in azione

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

3.5 MPLAB IDE

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.

3.5.1 Programmare e compilare

Editor

.asm .inc

Compilatore
assembler

.cod .lst .err .hex

PIC Programmatore

Figura 3.3: Files generati dal compilatore

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

Una volta compilato il codice è possibile verificarne il funzionamento senza utilizzare un


vero PICmicro, ma simulandone il comportamento sul PC tramite il tool MPLAB SIM.
Il simulatore, pur non eseguendo il codice con la velocità di un vero PICmicro, permette
di eseguire misure accurate su quelli che saranno i tempi di esecuzione reali di istruzioni e
porzioni di codice.
Per utilizzare MPLAB SIM è sufficiente selezionarlo da Debugger → Select Tool →
MPLAB SIM. Nel menù compariranno i comandi per poterlo utilizzare.

3.6 Programmare con l’ICD 2

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:

• collegare l’ICD2 al PC tramite un cavo seriale


3
i programmatori della linea professionale verificano la corretta programmazione del dispositivo con
diversi livelli di tensione corrispondenti alle specifiche minime e massime del dispositivo, garantendo la
correttezza della programmazione. Infatti per la tecnologia costruttiva delle memorie è possibile che una
cella di memoria venga letta diversamente se alimentata a livelli di tensione differenti.
3.7. DEBUG CON L’ICD2 70

• alimentare l’ICD2 tramite un alimentatore stabilizzato da 9V

• collegare l’ICD2 al circuito target tramite un cavo con terminale RJ45

• selezionare nelle impostazioni all’interno di MPLAB l’opzione di alimentare il circuito


target tramite l’ICD2

Se invece utilizziamo la porta USB dobbiamo:

• collegare l’ICD2 al PC tramite un cavo USB A-B

• collegare l’ICD2 al circuito target tramite un cavo con terminale RJ45

• alimentare il circuito target separatamente

• selezionare nelle impostazioni all’interno di MPLAB l’opzione di NON alimentare il


circuito target tramite l’ICD2

Per utilizzare l’ICD2 come programmatore è sufficiente selezionarlo da Programmer →


Select Tool → MPLAB ICD2. Nel menù compariranno i comandi per poterlo utilizzare.
L’ICD2 dispone di due firmware differenti per poter programmare sia i PICmicro
della serie 16 che quelli della serie 18. Fortunatamente MPLAB provvede a caricare
preventivamente la versione corretta al dispositivo che si intende utilizzare.
Istruzioni dettagliate sull’utilizzo dell’ICD2 sono presenti sul sito della Microchip,
in particolare il documento 51268b “MPLAB ICD2 Quick Start Guide”, il documento
51265c “Setting up the MPLAB ICD2” e il documento 51331a “MPLAB ICD 2 In-Circuit
Debugger User’s Guide”

3.7 Debug con l’ICD2

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:

• interrompere e riprendere l’esecuzione del programma;

• eseguire il programma per passi (stepping);

• impostare un breakpoint;

• visualizzare e modificare il contenuto dei registri e della memoria utilizzando i nomi


simbolici.

Al momento della programmazione MPLAB chiederà se vogliamo utilizzare le funzio-


nalità di debug. In caso di risposta affermativa inserirà nel codice sorgente alcune funzioni
3.7. DEBUG CON L’ICD2 71

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.

4.1 Lampeggio LED

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

list p=18f452, n=48, t=ON, st=OFF


#include "p18f452.inc"

ORG 0x80

Count RES 2 ; Riserva due Bytes dall’indirizzo Count

ORG 0x00000 ; Reset vector

;bsf STATUS,RP0 ; Accedi al banco 1 (Mid-range)


movlw B’11111110’ ; Imposta PORTB <7:1> come Input
movwf TRISB ; e PORTB<0> come Output
;bcf STATUS,RP0 ; Accedi al banco 0 (Mid-range)

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

Figura 4.1: Lampeggio di un LED senza interrupt


4.1. LAMPEGGIO LED 74

Reset vector DelayLoop

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

Aspetta Aspetta Return


ritardo ritardo

Figura 4.2: Lampeggio Led: Diagramma di flusso

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

Figura 4.3: Lampeggio di un LED, Codice HEX

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à:

ORG 0x00000 ;Reset Vector


goto Start

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

list p=18f452, n=48, t=ON, st=OFF


#include "p18f452.inc"

ORG 0x00000 ;Reset Vector


goto Start

org 0x00008 ; Interrupt Vector Address


goto ISR ; goto Interrupt Service Routine

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

ISR ; Interrupt Service Routine


btfsc INTCON,2 ; Se interrupt sollevato dal timer
goto Timer0Interrupt
retfie

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

Figura 4.4: Lampeggio di un LED con interrupt


4.2. GENERAZIONE PWM 77

Reset vector
0x0000 goto Start

0x0001

goto ISR Interrupt vector


0x0008

Start

0x0009 movlw ...

ISR

0x0011 btfsc ...

Figura 4.5: Posizione in memoria dell’esempio Lampeggio LED con interrupt

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.

4.2 Generazione PWM

Il programma presentato in questo capitolo dimostra l’utilizzo di varie periferche tra le


più utili: l’unità CCP in modalità generazione PWM (capitolo 1.4.3), la porta seriale in
modalità asincrona RS232 (capitolo 1.4.4) e il convertitore A/D (capitolo 1.4.8).
L’applicazione produce sul piedino RC1 un segnale PWM il cui Duty Cycle può essere
controllato tramite un byte in ingresso sulla porta seriale, oppure tramite il potenziome-
4.3. CONTROLLORE PER MOTORI STEPPER 78

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.

4.3 Controllore per motori stepper

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.
;************************************************************

list p=18f452, n=48, t=ON, st=OFF


#include "p18f452.inc"

;************************************************************
; variables

TEMP equ 0x000

;************************************************************
; reset and interrupt vectors

org 0x00000 ; Reset Vector Address


goto Start

org 0x00008 ; Interrupt Vector Address


goto ISR ; goto Interrupt Service Routine

;************************************************************
; 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 up USART module

movlw 19h ; 9600 baud @4MHz


movwf SPBRG

bsf TXSTA,TXEN ; Enable transmit


bsf TXSTA,BRGH ; Select high baud rate

bsf RCSTA,SPEN ; Enable Serial Port


bsf RCSTA,CREN ; Enable continuous reception

bcf PIR1,RCIF ; Clear RCIF Interrupt Flag


bsf PIE1,RCIE ; Set RCIE Interrupt Enable
bsf INTCON,PEIE ; Enable peripheral interrupts
bsf INTCON,GIE ; Enable global interrupts

Figura 4.6: Generazione PWM (1/4)


4.3. CONTROLLORE PER MOTORI STEPPER 80

;Set up A/D module

call InitializeAD ; configure A/D module

call SetupDelay ; delay for 15 instruction cycles

bsf ADCON0,GO ; Start first A/D conversion

;Set up PWM module


;Set PWM period by writing to PR2
;Set PWM duty cycle by writing to the CCPR2L register
; and the CCP2CON<5:4>>bits
;Make the CCP2 pin an output by clearing the TRISC<2> bit.

clrf CCP2CON ; CCP module is off


bsf CCP2CON, CCP2M3 ; select PWM mode
bsf CCP2CON, CCP2M2 ; select PWM mode
movlw 0x3F ; Set PWM frequency to 78.12kHz
movwf PR2 ;
bcf TRISC, 1 ; make channel 1 an output
movlw 0x00
movwf CCPR2L

;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

;Start at 50% duty cycle


movlw 0x20 ;
movwf CCPR2L ; Set PWM duty cycle

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

SetPot ; if was SER


bsf PORTB,RB0 ; set to pot

Debounce
btfss PORTA,4 ; Has key been released?
goto Debounce ; No, wait some more
goto MLOOP ; yes, wait for next key press

Figura 4.7: Generazione PWM (2/4)


4.3. CONTROLLORE PER MOTORI STEPPER 81

;************************************************************
; Service A/D interrupt

ISR
; Save context (WREG and STATUS) if required.

;A/D Interrupt
ADInt

btfss PIR1,ADIF ; Did A/D cause interrupt?


goto USARTInt ; No, check other sources

movf ADRESH,W ; Get A/D value (hi bits)


btfsc PORTB,RB0 ; Skip if Serial mode
movwf CCPR2L ; Set PWM duty cycle
movwf TXREG ; Send carachter on Serial port
bcf PIR1,ADIF ; Reset A/D int flag
call SetupDelay ; Delay for 15 cycles
bsf ADCON0,GO ; Start A/D conversion
goto EndISR ; return from ISR

;USART Interrupt
USARTInt
btfss PIR1,RCIF ; Did USART cause interrupt?
goto OtherInt ; No, some other interrupt

movlw 06h ; Mask out unwanted bits


andwf RCSTA,W ; Check for errors
btfss STATUS,Z ; Was either error status bit set?
goto RcvError ; Found error, flag it

movf RCREG,W ; Get input data


btfss PORTB,RB0 ; Skip if Pot mode
movwf CCPR2L ; Set PWM duty cycle
movwf TXREG ; Echo character back
goto EndISR ; go to end of ISR, restore context, return

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

Figura 4.8: Generazione PWM (3/4)


4.3. CONTROLLORE PER MOTORI STEPPER 82

;************************************************************
; 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

movlw B’11000001’ ; Select RC osc, AN0 selected,


movwf ADCON0 ; A/D enabled

bcf PIR1,ADIF ; Clear A/D interrupt flag


bsf PIE1,ADIE ; Enable A/D interrupt

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

Figura 4.9: Generazione PWM (4/4)


Appendice A

Descrizione della PICDEM2 plus

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

• Display LCD 2 righe x 16 caratteri

• Circuiteria per interfaccia seriale RS232 (MAX232A)

• Sensore di temperatura TC742 con interfaccia I2 C

• EEPROM seriale 24L256 da 256K x 8

• Cicalino piezoelettrico pilotato in PWM

• 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

Figura A.1: PICDEM2 plus hardware

Se invece utilizziamo l’ICD2 tramite porta seriale, e quindi lo alimentiamo, possiamo


fare in modo che fornisca anche l’alimentazione alla scheda modificando le impostazioni
in MPLAB.
Sulla scheda sono presenti tre jumpers. Il primo, siglato J6, permette di disabilitare
i led posti sulla parte superiore della scheda e di utilizzare le porte relative come canali
di I/O generali; il secondo, J7, abilita l’oscillatore RC presente sulla scheda; il terzo, J9,
permette di scollegare il cicalino piezoelettrico.
Nella tabella A.1 sono riportati i collegamenti presenti sulla scheda.

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

Tabella A.1: PICDEM2 plus connections


Appendice B

Realizzazione di una demo-board

B.1 16F84

Per il funzionamento di un PICmicro sono sufficienti pochissimi componenti esterni. Per


poter realizzare prototipi in poco tempo, abbiamo sviluppato una piccola scheda che racco-
glie questi componenti, oltre ad un sempre utile regolatore di tensione e la predisposizione
alla comunicazione seriale con standard RS-232.

B.1.1 Schema elettrico

Lo schema elettrico è molto semplice. Connesso al connettore a vaschetta DB-9 (J1)


troviamo il MAX232 (IC2) con i suoi condensatori (C1-C5) come riportato in figura B.2.
Seguitando troviamo il PICmicro (IC1) con collegato sui piedini 14-15 il quarzo (X1) ed i
relativi condensatori1 C7 e C8.

B.1.2 Circuito stampato

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

Figura B.1: Posizionamento dei componenti demo board A

+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

DIP/SO 12 R1OUT R1IN 13

CAPACITANCE (µF) TTL/CMOS 5kΩ RS-232


OUTPUTS INPUTS
DEVICE C1 C2 C3 C4 C5
9 R2OUT R2IN 8
MAX220 4.7 4.7 10 10 4.7
MAX232 1.0 1.0 1.0 1.0 1.0
MAX232A 0.1 0.1 0.1 0.1 0.1 5kΩ

GND
15

Figura B.2: Piedinatura e descrizione del MAX232


B.1. 16F84 87

Figura B.3: Circuito stampato demo board A

Figura B.4: Circuito stampato demo board B


Appendice C

Instruction sets

C.1 PIC16F84A e PIC16F87x

Il set di istruzioni dei PIC16F84a e PIC16F87x sono caratterizzati da un numero di istru-


zioni estremamente ridotto. Ciò avvantaggia il programmatore che può imparare il set
di istruzioni velocemente ed efficacemente, ma allo stesso tempo lo costringe ad utilizzare
una serie di costrutti per operazioni di medio livello che in altri processori sono eseguite
con una sola istruzione.
Ogni istruzione è rappresentata da una parola di 14 bit divisa in un opcode che specifica
il tipo dell’istruzione, ed uno o più operandi. Il set di istruzioni è altamente ortogonale, e
le operazioni sono divise in tre categorie principali:

• Operazioni orientate al byte

• Operazioni orientate al bit

• Operazioni letterali e di controllo

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 orientate al byte

• Operazioni orientate al bit

• Operazioni letterali

• Operazioni di controllo

• Operazioni di trasferimento tra memoria programma e memoria dati (table read/write)


C.2. PIC18F45X 90

Mnemonic, 14-Bit Opcode Status


Description Cycles Notes
Operands MSb LSb Affected

BYTE-ORIENTED FILE REGISTER OPERATIONS


ADDWF f, d Add W and f 1 00 0111 dfff ffff C,DC,Z 1,2
ANDWF f, d AND W with f 1 00 0101 dfff ffff Z 1,2
CLRF f Clear f 1 00 0001 lfff ffff Z 2
CLRW - Clear W 1 00 0001 0xxx xxxx Z
COMF f, d Complement f 1 00 1001 dfff ffff Z 1,2
DECF f, d Decrement f 1 00 0011 dfff ffff Z 1,2
DECFSZ f, d Decrement f, Skip if 0 1 (2) 00 1011 dfff ffff 1,2,3
INCF f, d Increment f 1 00 1010 dfff ffff Z 1,2
INCFSZ f, d Increment f, Skip if 0 1 (2) 00 1111 dfff ffff 1,2,3
IORWF f, d Inclusive OR W with f 1 00 0100 dfff ffff Z 1,2
MOVF f, d Move f 1 00 1000 dfff ffff Z 1,2
MOVWF f Move W to f 1 00 0000 lfff ffff
NOP - No Operation 1 00 0000 0xx0 0000
RLF f, d Rotate Left f through Carry 1 00 1101 dfff ffff C 1,2
RRF f, d Rotate Right f through Carry 1 00 1100 dfff ffff C 1,2
SUBWF f, d Subtract W from f 1 00 0010 dfff ffff C,DC,Z 1,2
SWAPF f, d Swap nibbles in f 1 00 1110 dfff ffff 1,2
XORWF f, d Exclusive OR W with f 1 00 0110 dfff ffff Z 1,2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF f, b Bit Clear f 1 01 00bb bfff ffff 1,2
BSF f, b Bit Set f 1 01 01bb bfff ffff 1,2
BTFSC f, b Bit Test f, Skip if Clear 1 (2) 01 10bb bfff ffff 3
BTFSS f, b Bit Test f, Skip if Set 1 (2) 01 11bb bfff ffff 3
LITERAL AND CONTROL OPERATIONS
ADDLW k Add literal and W 1 11 111x kkkk kkkk C,DC,Z
ANDLW k AND literal with W 1 11 1001 kkkk kkkk Z
CALL k Call subroutine 2 10 0kkk kkkk kkkk
CLRWDT - Clear Watchdog Timer 1 00 0000 0110 0100 TO,PD
GOTO k Go to address 2 10 1kkk kkkk kkkk
IORLW k Inclusive OR literal with W 1 11 1000 kkkk kkkk Z
MOVLW k Move literal to W 1 11 00xx kkkk kkkk
RETFIE - Return from interrupt 2 00 0000 0000 1001
RETLW k Return with literal in W 2 11 01xx kkkk kkkk
RETURN - Return from Subroutine 2 00 0000 0000 1000
SLEEP - Go into standby mode 1 00 0000 0110 0011 TO,PD
SUBLW k Subtract W from literal 1 11 110x kkkk kkkk C,DC,Z
XORLW k Exclusive OR literal with W 1 11 1010 kkkk kkkk Z
Note 1: When an I/O register is modified as a function of itself ( e.g., MOVF PORTB, 1), the value used will be that value present
on the pins themselves. For example, if the data latch is ’1’ for a pin configured as input and is driven low by an external
device, the data will be written back with a ’0’.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if
assigned to the Timer0 Module.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second cycle is
executed as a NOP.

Tabella C.1: PIC16F84A instruction set


C.2. PIC18F45X 91

Mnemonic, 16-Bit Instruction Word Status


Description Cycles Notes
Operands MSb LSb Affected

BYTE-ORIENTED FILE REGISTER OPERATIONS


ADDWF f, d, a Add WREG and f 1 0010 01da0 ffff ffff C, DC, Z, OV, N 1, 2
ADDWFC f, d, a Add WREG and Carry bit to f 1 0010 0da ffff ffff C, DC, Z, OV, N 1, 2
ANDWF f, d, a AND WREG with f 1 0001 01da ffff ffff Z, N 1,2
CLRF f, a Clear f 1 0110 101a ffff ffff Z 2
COMF f, d, a Complement f 1 0001 11da ffff ffff Z, N 1, 2
CPFSEQ f, a Compare f with WREG, skip = 1 (2 or 3) 0110 001a ffff ffff None 4
CPFSGT f, a Compare f with WREG, skip > 1 (2 or 3) 0110 010a ffff ffff None 4
CPFSLT f, a Compare f with WREG, skip < 1 (2 or 3) 0110 000a ffff ffff None 1, 2
DECF f, d, a Decrement f 1 0000 01da ffff ffff C, DC, Z, OV, N 1, 2, 3, 4
DECFSZ f, d, a Decrement f, Skip if 0 1 (2 or 3) 0010 11da ffff ffff None 1, 2, 3, 4
DCFSNZ f, d, a Decrement f, Skip if Not 0 1 (2 or 3) 0100 11da ffff ffff None 1, 2
INCF f, d, a Increment f 1 0010 10da ffff ffff C, DC, Z, OV, N 1, 2, 3, 4
INCFSZ f, d, a Increment f, Skip if 0 1 (2 or 3) 0011 11da ffff ffff None 4
INFSNZ f, d, a Increment f, Skip if Not 0 1 (2 or 3) 0100 10da ffff ffff None 1, 2
IORWF f, d, a Inclusive OR WREG with f 1 0001 00da ffff ffff Z, N 1, 2
MOVF f, d, a Move f 1 0101 00da ffff ffff Z, N 1
MOVFF fs, fd Move fs (source) to 1st word 2 1100 ffff ffff ffff None
fd (destination) 2nd word 1111 ffff ffff ffff
MOVWF f, a Move WREG to f 1 0110 111a ffff ffff None
MULWF f, a Multiply WREG with f 1 0000 001a ffff ffff None
NEGF f, a Negate f 1 0110 110a ffff ffff C, DC, Z, OV, N 1, 2
RLCF f, d, a Rotate Left f through Carry 1 0011 01da ffff ffff C, Z, N
RLNCF f, d, a Rotate Left f (No Carry) 1 0100 01da ffff ffff Z, N 1, 2
RRCF f, d, a Rotate Right f through Carry 1 0011 00da ffff ffff C, Z, N
RRNCF f, d, a Rotate Right f (No Carry) 1 0100 00da ffff ffff Z, N
SETF f, a Set f 1 0110 100a ffff ffff None
SUBFWB f, d, a Subtract f from WREG with 1 0101 01da ffff ffff C, DC, Z, OV, N 1, 2
borrow
SUBWF f, d, a Subtract WREG from f 1 0101 11da ffff ffff C, DC, Z, OV, N
SUBWFB f, d, a Subtract WREG from f with 1 0101 10da ffff ffff C, DC, Z, OV, N 1, 2
borrow
SWAPF f, d, a Swap nibbles in f 1 0011 10da ffff ffff None 4
TSTFSZ f, a Test f, skip if 0 1 (2 or 3) 0110 011a ffff ffff None 1, 2
XORWF f, d, a Exclusive OR WREG with f 1 0001 10da ffff ffff Z, N
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF f, b, a Bit Clear f 1 1001 bbba ffff ffff None 1, 2
BSF f, b, a Bit Set f 1 1000 bbba ffff ffff None 1, 2
BTFSC f, b, a Bit Test f, Skip if Clear 1 (2 or 3) 1011 bbba ffff ffff None 3, 4
BTFSS f, b, a Bit Test f, Skip if Set 1 (2 or 3) 1010 bbba ffff ffff None 3, 4
BTG f, d, a Bit Toggle f 1 0111 bbba ffff ffff None 1, 2
Note 1: When a PORT register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that value
present on the pins themselves. For example, if the data latch is ’1’ for a pin configured as input and is driven low by an
external device, the data will be written back with a ’0’.
2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if assigned.
3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second cycle is
executed as a NOP.
4: Some instructions are 2-word instructions. The second word of these instructions will be executed as a NOP, unless the
first word of the instruction retrieves the information embedded in these 16-bits. This ensures that all program memory
locations have a valid instruction.
5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.

Tabella C.2: PIC18F45x instruction set


C.2. PIC18F45X 92

Mnemonic, 16-Bit Instruction Word Status


Description Cycles Notes
Operands MSb LSb Affected

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

Mnemonic, 16-Bit Instruction Word Status


Description Cycles Notes
Operands MSb LSb Affected

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

Tabella C.3: PIC18F45x instruction set (continued)


C.2. PIC18F45X 93

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)

Tabella C.4: Istruction set conventions


Appendice D

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).

Acquisition Time (TACQ) This is related to Analog-to-Digital (A/D) converters. This


is the time that the PIC18CXXX A/D’s holding capacitor acquires the analog in-
put voltage level connected to it. When the GO bit is set, the analog input is
disconnected from the holding capacitor and the A/D conversion is started.

A/D Refers to Analog-to-Digital Converter. See description under “Analog-to-Digital


(A/D)”.

ALU Arithmetical Logical Unit. Device logic that is responsible for the mathemati-
cal(add, subtract, ...), logical (and, or, ...), and shifting operation.

Analog Refers to electronic transmission accomplished by adding signals of varying fre-


quency or amplitude to carrier waves of a given frequency of alternating

Analog-to-Digital (A/D) The conversion of an analog input voltage to a ratiometric


digital equivalent value.

Assembly Language A symbolic language that describes the binary machine code in a
readable form.

AUSART Addressable Universal Synchronous Asynchronous Receiver Transmitter. This


module can either operate as a full duplex asynchronous communications port, or a
95

half duplex synchronous communications port. When operating in the asynchronous


mode, the USART can be interfaced to a PC’s serial port.
Alphanumeric Alphanumeric characters include alpha characters and numbers: (a...z,
A...Z, 1...9).
Application A set of software and hardware developed by the user, usually designed to
be a product controlled by a PICmicro microcontroller.
Assemble What an assembler does. See assembler.
Assembler A language tool that translates a user’s assembly source code (.asm) into
machine code. MPASM is Microchip’s assembler.
Assembly A programming language that is once removed from machine language. Ma-
chine languages consist entirely of numbers and are almost impossible for humans to
read and write. Assembly languages have the same structure and set of commands
as machine languages, but they enable a programmer to use names (mnemonics)
instead of numbers.
Assigned Section A section which has been assigned to a target memory block in the
linker command file. The linker allocates an assigned section into its specified target
memory block.
Bank This is a method of addressing Data Memory. Since enhanced devices have 8-bits
for direct addressing, instructions can address up to 256 bytes. To allow more data
memory to be present on a device, data memory is partitioned into contiguous banks
of 256 bytes each. To select the desired bank, the bank selection register (BSR) needs
to be appropriately configured. 16 banks can be implemented.
Baud Generally this is how the communication speed of serial ports is described. Equi-
valent to bits per second (bps).
BCD See description under “Binary Coded Decimal (BCD)”.
Binary Coded Decimal (BCD) Each 4-bit nibble expresses a digit from 0-9. Usually
two digits are contained in a byte yielding a range of 0 - 99.
BOR See description under “Brown-out Reset (BOR)”.
Brown-out A condition where the supply voltage of the device temporarily falls below
the specified minimum operation point. This can occur when a load is switched on
and causes the system/device voltage to drop.
Brown-out Reset (BOR) Circuitry which will force the device to the RESET state if
the device’s power supply voltage falls below a specified voltage level. Some devices
have an internal BOR circuit, while other devices would require an external circuit
to be created.
Bus width This is the number of bits of information that a bus carries. For the Data
Memory, the bus width is 8-bits. For enhanced devices the Program Memory bus
width is 16-bits.
96

Breakpoint - Hardware An event whose execution will cause a halt.

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.

Command Line Interface Command line interface refers to executing a program on


the DOS command line with options. Executing the MPASM Assembler with any
command line options or just the file name will invoke the assembler. In the absence
of any command line options, a prompted input interface (shell) will be executed.

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.

Compile What a compiler does. See compiler.

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 Bits Unique bits programmed to set PICmicro microcontroller modes of


operation. A configuration bit may or may not be preprogrammed. These bits are
set in the Options → Development Mode dialog for simulators or emulators and in
the CONFIG MPASM directive for programmers.

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’.

Conversion Time (Tconv) This is related to Analog-to-Digital (A/D) converters. This


is the time that the PIC18CXXX A/D’s converter requires to convert the analog
voltage level on the holding capacitor to a digital value.

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.

D/A See description under “Digital to Analog”.

DAC Digital-to-Analog converter.

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.

Digital-to-Analog The conversion of a digital value to an equivalent ratiometric analog


voltage.

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

EEPROM Electrically Erasable Programmable Read Only Memory. A special type of


PROM that can be erased electrically. Data is written or erased one byte at a time.
EEPROM retains its contents even when power is turned off.

Embedded System Special-purpose computer built into and integral to a device. It is


used to control, monitor or assist an operation. All embedded systems are or include
computers, the simplest being a single microprocessor (“chip”). A microprocessor
may be designed so that ROM software (“firmware”) for a particular purpose can
be added (e.g., a PC’s ROM BIOS).

Emulation The process of executing software loaded into emulation memory as if the
firmware resided on the microcontroller device under development.

Emulation Memory Program memory contained within the emulator.

Emulator Hardware that performs emulation.

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.

Executable Code See Hex Code.

Export Send data out of the MPLAB IDE in a standardized format.

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

FOSC Frequency of the device oscillator.


File Registers On-chip general purpose and special function registers.
GIO General Input/Output.
GPIO General Purpose Input/Output.
GPR General Purpose Register (RAM). A portion of the data memory that can be used
to store the program’s dynamic variables.
Harvard Architecture In this architecture, the Program Memory and Data Memory
buses are separated. This allows concurrent accesses to Data Memory and Pro-
gram Memory, which increases the performance of the device. All PICmicro devices
implement a Harvard Architecture.
Hex Code Executable instructions assembled or compiled from source code into standard
hexadecimal format code. Also called executable or machine code. Hex code is
contained in a hex file.
Hex File An ASCII file containing hexadecimal addresses and values (hex code) suitable
for programming a device. This format is readable by a device programmer.
High Level Language A language for writing programs that is of a higher level of ab-
straction from the processor than assembler code. High level languages (such as C)
employ a compiler to translate statements into machine instructions that the target
processor can execute.
Holding Capacitor This is a capacitor in the Analog-to-Digital (A/D) module which
“holds” an analog input level once a conversion is started. During acquisition, the
holding capacitor is charged/discharged by the voltage level on the analog input pin.
Once the conversion is started, the holding capacitor is disconnected from the analog
input and “holds” this voltage for the A/D conversion.
HS (High Speed) High Speed. One of the device oscillator modes. The oscillator circuit
is tuned to support the high frequency operation. Currently this allows for operation
from 4 MHz to 25 MHz.
I2C Inter-Integrated Circuit. This is a two wire communication interface. This feature
is one of the modes of the SSP and MSSP modules.
ICD In-Circuit Debugger. MPLAB ICD is Microchip’s in-circuit debugger for PIC16F87X
devices. MPLAB ICD works with MPLAB IDE.
ICE In-Circuit Emulator. MPLAB ICE is Microchip’s in-circuit emulator that works
with MPLAB IDE.
IDE Integrated Development Environment. An application that has multiple functions
for firmware development. The MPLAB IDE integrates a compiler, an assembler, a
project manager, an editor, a debugger, a simulator, and an assortment of other tools
within one Windows; application. A user developing an application can write code,
compile, debug, and test an application without leaving the MPLAB IDE desktop.
100

Identifier A function or variable name.

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.

KEELOQ KEELOQ is a patented code-hopping technology. Microchip KEELOQ pro-


ducts provide a method for encrypting data for a unidirectional transmission, where
each transmission is unique even if the same button is pressed.

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.

Library A library is a collection of relocatable object modules. It is created by assembling


multiple source files to object files, and then using the librarian to combine the object
files into one library file. A library can be linked with object modules and other
libraries to create executable code.
101

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.

Link What a linker does. See Linker.

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.

Literal This is a constant value that is embedded in an instruction word.

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.

LSb (or LSB) Least Significant Bit.

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.

Machine Code Either object or executable code.

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.

MCU Microcontroller Unit. An abbreviation for microcontroller. Also mC.

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.

MPASM Assembler Microchip Technology’s relocatable macro assembler. The MPA-


SM is a DOS or Windows-based PC application that provides a platform for de-
veloping assembly language code for Microchip’s PICmicro microcontroller families.
Generically, the MPASM Assembler will refer to the entire development platform
including the macro assembler and utility functions.

MPLAB CXX Refers to MPLAB C17 and MPLAB C18 C compilers.

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.

MPLAB SIM Microchip’s simulator that works with MPLAB IDE.

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.

MSb Most Significant Bit.

MSB Most Significant Byte.

MSSP See “Master Synchronous Serial Port”.

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.

NRZ See description under “Non-Return to Zero (NRZ)”.

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.

OST See description under “Oscillator Start-up Timer (OST)”.

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 Personal Computer or Program Counter.

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

PICmicro MCUs PICmicro microcontrollers (MCUs) refers to all Microchip microcon-


troller families.

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.

PICSTART; Plus Device Programmer A device programmer from Microchip. Pro-


grams 8-, 14-, 28-, and 40-pin PICmicro microcontrollers. Must be used with
MPLAB Software.

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).

Prescaler A circuit that slows the rate of a clocking source to a counter/timer.

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.

Program Memory The memory area in a PICmicro microcontroller where instructions


are stored. Memory in the emulator or simulator containing the downloaded target
application firmware.

Programmer A device used to program electrically programmable semiconductor devices


such as microcontrollers.

Project A set of source files and instructions to build the object and executable code for
an application.

PRO MATE; II Device Programmer A device programmer from Microchip. Pro-


grams all PICmicro microcontrollers and most memory and KEELOQ devices. Can
be used with MPLAB IDE or as a stand-alone.

Prototype System A term referring to a user’s target application, or target board.


105

PWM Signals See description under “Pulse Width Modulation (PWM)”.

PSP See description under “Parallel Slave Port (PSP)”.

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)”.

PWM See description under “Pulse Width Modulation (PWM)”.

Q-cycles This is the same as a device oscillator cycle. There are 4 Q-cycles for each
instruction cycle.

RAM Random Access Memory (Data Memory).

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.

SPI See description under “Serial Peripheral Interface (SPI)”.

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 Refers to user hardware.

Target Application Firmware residing on the target board.

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.

USART Universal Synchronous Asynchronous Receiver Transmitter. A module that


can operate as a full duplex asynchronous communications port or as a half duplex
synchronous communications port. When operating in the asynchronous mode, the
USART can be interfaced to the PC serial port.

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

DS39500 PIC18C reference manual


DS33023 Mid-Range MCU Family Reference Manual

Architecture and hardware design

DS30277 In-Circuit Serial Programming Guide


AN522 Power-Up Considerations
AN607 Power-Up Troubleshooting
AN594 Using the CCP modules
AN579 Using the 8-bit Parallel Slave Port
AN588 PIC16/17 Oscillator Design Guide
109

Programmazione

DS33014 MPASM User’s Guide


DS51014 MPLAB-C Compiler User’s Guide
DS51025 MPLAB User’s Guide
DS30420 MPLAB Editor User’s Guide
DS30027 MPSIM User’s Guide
AN575 IEEE 754 Compliant Floating Point Routines
AN617 Fixed Point Routines
AN660 Floating Point Math Functions
AN556 Implementing a Table Read
AN578 Use of the SSP Module in the I2 C Multi-Master Environment
51410a Application Development With MPLAB IDE

Interfacing PICs and examples

DS00092 Embedded Control Handbook Volume I


DS00167 Embedded Control Handbook Volume II
AN658 LCD Fundamentals Using PIC16C92x Microcontrollers
AN649 Yet Another Clock Using the PIC16C92X
DS51079 PICDEM3 Demo Board User’s Guide

You might also like