...

PIC

by user

on
Category:

design

95

views

Report

Comments

Description

Transcript

PIC
An introduction to PICMicro Microcontrollers
Nicholas Amadori
21 novembre 2003
Indice
1 Architecture and Hardware Design
1.1 Generalities . . . . . . . . . . . . . . . . . . .
1.2 PIC Families . . . . . . . . . . . . . . . . . .
1.2.1 Memory Varieties . . . . . . . . . . . .
1.2.2 Logical Families . . . . . . . . . . . .
1.2.3 Packages . . . . . . . . . . . . . . . . .
1.2.4 How to choose the right MCU for your
1.3 Core Features . . . . . . . . . . . . . . . . . .
1.3.1 CPU (Central Processing Unit) . . . .
1.3.2 ALU (Arithmetic Logical Unit) . . . .
1.3.3 Oscillator . . . . . . . . . . . . . . . .
1.3.4 Reset logic . . . . . . . . . . . . . . .
1.3.5 Memory Organization . . . . . . . . .
1.3.6 Device configuration bits . . . . . . .
1.3.7 Watchdog Timer . . . . . . . . . . . .
1.3.8 Low power mode (Sleep) . . . . . . . .
1.3.9 Table Read/Write . . . . . . . . . . .
1.3.10 Interrupts . . . . . . . . . . . . . . . .
1.4 Peripherals . . . . . . . . . . . . . . . . . . .
1.4.1 Generic I/O . . . . . . . . . . . . . . .
1.4.2 Timers . . . . . . . . . . . . . . . . . .
1.4.3 Capture, Compare, PWM (CCP) . . .
1.4.4 Serial ports and protocols . . . . . . .
1.4.5 LCD driver . . . . . . . . . . . . . . .
1.4.6 Comparators . . . . . . . . . . . . . .
1.4.7 Voltage References . . . . . . . . . . .
1.4.8 A/D converters . . . . . . . . . . . . .
1.4.9 Parallel Slave Port (PSP) . . . . . . .
1.4.10 USB . . . . . . . . . . . . . . . . . . .
1.5 In-Circuit Serial Programming . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
needs
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
8
8
12
12
13
15
15
18
18
18
20
24
26
30
30
31
32
32
33
35
38
41
45
50
51
53
53
56
57
58
2 Interfacing PICs
60
2.1 LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.2 Switch de-bounce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.3 Relais and Solenoids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1
INDICE
2.4
2.5
2
Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3 Programmazione
3.1 Linguaggio Assembly . . . . . . .
3.1.1 Direttive di compilazione
3.2 Linguaggio C . . . . . . . . . . .
3.3 Application Maestro . . . . . . .
3.4 FilterLab . . . . . . . . . . . . .
3.5 MPLAB IDE . . . . . . . . . . .
3.5.1 Programmare e compilare
3.5.2 Simulare . . . . . . . . . .
3.6 Programmare con l’ICD 2 . . . .
3.7 Debug con l’ICD2 . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
67
67
68
68
69
70
71
71
72
72
73
4 Esempi
75
4.1 Lampeggio LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.2 Generazione PWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.3 Controllore per motori stepper . . . . . . . . . . . . . . . . . . . . . . . . . 81
5 Descrizione della PICDEM2 plus
86
A Realizzazione di una demo-board
A.1 16F84 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A.1.1 Schema elettrico . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A.1.2 Circuito stampato . . . . . . . . . . . . . . . . . . . . . . . . . . . .
88
88
88
88
B Instruction sets
91
B.1 PIC16F84A e PIC16F87x . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
B.2 PIC18F45x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C Glossary
D Application Notes
97
111
Elenco delle figure
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11
1.12
1.13
1.14
1.15
1.16
1.17
1.18
1.19
1.20
1.21
1.22
1.23
1.24
1.25
1.26
1.27
1.28
1.29
1.30
1.31
1.32
1.33
1.34
MID-Range PICMicro architecture . . . . . . . . . . . . . . . . . .
Architectures: Harvard vs. von Neumann . . . . . . . . . . . . . .
Two-stage Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . .
Packaging of PICmicro MCUs . . . . . . . . . . . . . . . . . . . . .
Packaging of PICmicro MCUs (continued) . . . . . . . . . . . . . .
ALU and WREG register operation . . . . . . . . . . . . . . . . . .
8 x 8 Unsigned Multiply Routine . . . . . . . . . . . . . . . . . . .
8 x 8 Signed Multiply Routine . . . . . . . . . . . . . . . . . . . .
Internal instruction clock (TCY) . . . . . . . . . . . . . . . . . . .
Typical crystal oscillator configuration . . . . . . . . . . . . . . . .
Typical RC oscillator configuration . . . . . . . . . . . . . . . . . .
Example RC Oscillator Frequency vs. VDD . . . . . . . . . . . . .
Reset circuitry . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mid-range devices memory map . . . . . . . . . . . . . . . . . . . .
Example: call of a subroutine in page 1 from page 0 . . . . . . . .
PIC18x PC structure . . . . . . . . . . . . . . . . . . . . . . . . . .
Example: Specify configuration bits using the CONFIG directive .
Example: Interrupt Service Routine Template . . . . . . . . . . . .
Example: Interrupt Initialization . . . . . . . . . . . . . . . . . . .
Generic I/O port . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initializing PORTA . . . . . . . . . . . . . . . . . . . . . . . . . . .
PORTB block diagram . . . . . . . . . . . . . . . . . . . . . . . . .
Timer0 simplified block diagram . . . . . . . . . . . . . . . . . . .
Initializing Timer0 on PIC16F . . . . . . . . . . . . . . . . . . . .
PWM Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
I2C connections and data format . . . . . . . . . . . . . . . . . . .
Example of a CAN network . . . . . . . . . . . . . . . . . . . . . .
Single Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . .
Comparator Modes . . . . . . . . . . . . . . . . . . . . . . . . . . .
Vref diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-bit A/D converter module diagram . . . . . . . . . . . . . . . . .
A/D conversion example . . . . . . . . . . . . . . . . . . . . . . . .
USB external circuitry . . . . . . . . . . . . . . . . . . . . . . . . .
Typical In-Circuit Serial Programming (ICSP) Application Circuit
3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
9
10
11
16
17
19
20
20
21
22
23
24
26
27
28
29
31
34
35
37
38
39
40
40
43
49
50
51
52
53
54
56
58
59
ELENCO DELLE FIGURE
4
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
LED connection . . . . . . . . . . . . . .
Multiple 7-segments display wiring . . .
Swich bouncing signal . . . . . . . . . .
Hardware debounce circuit . . . . . . .
Relay control circuit . . . . . . . . . . .
H-bridge circuit . . . . . . . . . . . . . .
Using the 293D to control a motor . . .
Functional block diagram of LMD18200
Piedinatura e descrizione del MAX232 .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3.1
3.2
3.3
La finestra principale di Application Maestro . . . . . . . . . . . . . . . . . 69
FilterLab in azione . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Files generati dal compilatore . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
Lampeggio di un LED senza interrupt . . . .
Lampeggio Led: Diagramma di flusso . . . .
Lampeggio di un LED, Codice HEX . . . . .
Lampeggio di un LED con interrupt . . . . .
Posizione in memoria dell’esempio Lampeggio
Generazione PWM (1/4) . . . . . . . . . . . .
Generazione PWM (2/4) . . . . . . . . . . . .
Generazione PWM (3/4) . . . . . . . . . . . .
Generazione PWM (4/4) . . . . . . . . . . . .
5.1
PICDEM2 plus hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
A.1
A.2
A.3
A.4
Posizionamento dei componenti demo board
Piedinatura e descrizione del MAX232 . . .
Circuito stampato demo board A . . . . . .
Circuito stampato demo board B . . . . . .
. . .
. . .
. . .
. . .
LED
. . .
. . .
. . .
. . .
A
. .
. .
. .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
con interrupt
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
61
61
61
62
63
64
64
65
66
76
77
78
79
80
82
83
84
85
89
89
90
90
Elenco delle tabelle
1.1
1.2
1.3
Example RC oscillator frequencies . . . . . . . . . . . . . . . . . . . . . . . 25
Interaction between two CCP modules . . . . . . . . . . . . . . . . . . . . . 42
Minimum Duty Cycle Bit Time . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.1
PICDEM2 plus connections . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
B.1
B.2
B.3
B.4
PIC16F84A instruction set . . . . . .
PIC18F45x instruction set . . . . . . .
PIC18F45x instruction set (continued)
Istruction set conventions . . . . . . .
5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
93
94
95
96
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 numero di applicazioni industriali in cui sono stati impiegati, per la mole di documentazione
e codice sorgente che si può recuperare in rete e per il basso costo per unità. 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, e 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.
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.
Il capitolo 2 descrive il processo di programmazione delle unità, a partire dalla stesura
del programma in linguaggio Assembly o C, alla simulazione, la programmazione fisica e
il debug.
Il capitolo 3 offre qualche consiglio su come interfacciare i PICmicro ad alcune situazioni
tipiche.
Il capitolo 4 presenta alcuni esempi applicativi di difficoltà crescente realizzati e commentati.
Il capitolo 5 presenta la scheda PICDEM2 plus
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
6
ELENCO DELLE TABELLE
7
In appendice troviamo alcune sezioni di consultazione tra cui il layout di una demoboard, il set di istruzioni dei PICmicro utilizzati, un esaustivo glossario e un elenco di
Application Notes particolarmente utili.
conclusione
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
8
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
13
Program
Bus
EPROM
Program Counter
Program
Memory
up to
8K x 14
8 Level Stack
(13-bit)
14
8
Data Bus
PORTA
RA0
RA1
RA2
RA3
RA4
RA5
RAM
File
Registers
up to
368 x 8
RAM Addr (1)
PORTB
9
Addr MUX
Instruction reg
Direct Addr
7
8
Indirect
Addr
FSR reg
STATUS reg
8
3
Power-up
Timer
Instruction
Decode &
Control
Timing
Generation
OSC1/CLKIN
OSC2/CLKOUT
Internal
RC clock (2)
Oscillator
Start-up Timer
Power-on
Reset
Watchdog
Timer
Brown-out
Reset (2)
MCLR
Timer0
Timer1
PORTC
ALU
8
RB0/INT
RB1
RB2
RB3
RB4
RB5
RB6
RB7
RC0
RC1
RC2
RC3
RC4
RC5
RC6
RC7
MUX
PORTD
W reg
PORTE
VDD, VSS
Timer2
9
RD0
RD1
RD2
RD3
RD4
RD5
RD6
RD7
RE0
RE1
RE2
RE3
RE4
RE5
RE6
RE7
A/D
PORTF
CCPs
Comparators
Other
Modules
Voltage
Reference
Peripheral Modules (Note 3)
Synchronous
Serial Port
USARTs
Parallel
Slave Port
LCD Drivers
RF0
RF1
RF2
RF3
RF4
RF5
RF6
RF7
PORTG
RG0
RG1
RG2
RG3
RG4
RG5
RG6
RG7
Data EEPROM
up to
256 x 8
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
10
Harvard (PICmicro)
Data
memory
8
CPU
12-16
Program
memory
8
Program
and data
memory
Von Neumann
CPU
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
11
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.
1. MOVLW 55h
TCY0
TCY1
Fetch 1
Execute 1
Fetch 2
2. MOVWF PORTB
3. BRA
4. BSF
TCY2
PORTA, BIT3 (Forced NOP)
5. Instruction @ address SUB_1
TCY4
TCY5
Execute 2
Fetch 3
SUB_1
TCY3
Execute 3
Fetch 4
Flush (NOP)
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
12
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 instructions 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
1.2.1
PIC Families
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
13
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
14
PIC12 Family: 8-pin 12-bit/14-bit program word
The PIC12 family packs Microchip’s powerful RISC-based PICmicro architecture into 8pin 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 interrupthandling 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 integrated 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 architectural 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 reducing cost, enhancing system reliability and reducing power consumption. These include
programmable Low Voltage Detect (LVD) and programmable Brown-Out Detect (BOD).
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
1.2.3
15
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;
Figura 1.4: Packaging of PICmicro MCUs
24-LEAD PDIP
“P” OR “PG”
20-LEAD PDIP
“P”
18-LEAD PDIP
“P”
14-LEAD PDIP
“P” OR “PD”
8-LEAD PDIP
“P” OR “PA”
44-LEAD MQFP
“PQ”
PLASTIC QUAD
FLATPACK
“QFP”
40-LEAD PDIP
“P” OR “PL”
28-LEAD SKINNY PDIP
“SP” OR “PJ”
28-LEAD PDIP
“P” OR “PI”
PLASTIC DUAL IN-LINE
PDIP
84-LEAD CERQUAD
“CL”
CERAMIC CHIP CARRIER
CERQUAD
68-LEAD CERQUAD
“CL”
40-LEAD CERDIP
“JW”
28-LEAD CERDIP
“JW”
20-LEAD CERDIP
“JW”
18-LEAD CERDIP
“JW”
CERAMIC DUAL IN-LINE
CERDIP
84-LEAD PLCC
“L”
68-LEAD PLCC
“L” OR “LS”
44-LEAD PLCC
“L” OR “W”
32-LEAD PLCC
“L”
PLASTIC LEADED
CHIP CARRIER
PLCC
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
16
Figura 1.5: Packaging of PICmicro MCUs (continued)
28-LEAD QFN
“ML”
14-LEAD TSSOP
(4.4MM) “ST” (PICmicro MCU)
(4.4MM) “ST14” (MEMORY)
44-LEAD QFN
“ML”
8-LEAD DFN
“MF”
8-LEAD TSSOP
(4.4MM) “ST”
20-LEAD TSSOP
(4.4MM) “ST”
CHIP SCALE
PACKAGES
28-LEAD SOIC
“SO” OR “OI”
20-LEAD SOIC
“SO”
18-LEAD SOIC
“SO”
16-LEAD SOIC
(.150”) “SL”
PLASTIC THIN SHRINK
SMALL OUTLINE
“TSOP”
14-LEAD SOIC
(.150”) “SL” OR “OD”
8-LEAD SOIC
(.208”) “SM”
8-LEAD SOIC
(.150”) “SN” OR “OA”
PLASTIC SMALL OUTLINE
“SOIC”
28-LEAD SSOP
“SS”
8-LEAD MSOP
“UA”
8-LEAD MSOP
“MS”
16-LEAD QSOP
20-LEAD SSOP
“SS”
PLASTIC SHRINK
SMALL OUTLINE
“SSOP”
3-LEAD SC-89
6-LEAD SOT-23
“CH” or “OT”
SOT-143
“RC”
3-LEAD SOT-23
“TT” OR “CB”
3-LEAD TRANSISTOR
“TO” OR “ZB”
3-LEAD SC-70
5-LEAD SC-70
5-LEAD SOT-23
“OT” OR “CT”
28-LEAD SIDE BRAZED
(.300”) “JW”
20-LEAD SIDE BRAZED
“JW”
14-LEAD SIDE BRAZED
“JW”
8-LEAD SIDE BRAZED
“JW”
SIDE BRAZED
DUAL-IN-LINE
“JW”
SMALL OUTLINE TRANSISTOR
80-LEAD TQFP’
“PT”
64-LEAD TQFP
“PT”
44-LEAD TQFP
“PT”
PLASTIC THIN QUAD
FLATPACK
“TQFP”
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
17
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
1.3
18
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 complement 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
8-bit literal
(from instruction word)
8
W Register
8
8-bit register value
8 (from direct or indirect
address of instruction)
8
ALU
19
Register
File
Special
Function
Registers
(SFR’s)
and
General
Purpose
RAM
(GPR)
8
d bit, or from instruction
d = '0' or
Literal Instructions
d = '1'
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 throughput and reduces code size requirements for multiplication algorithms. The performance
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
20
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
MULWF
ARG1, WREG
ARG2
;
; ARG1 * ARG2 -> PRODH:PRODL
Figura 1.7: 8 x 8 Unsigned Multiply Routine
MOVFF
MULWF
BTFSC
SUBWF
MOVFF
BTFSC
SUBWF
ARG1, WREG
ARG2
ARG2, SB
PRODH, F
ARG2, WREG
ARG1, SB
PRODH, F
; ARG1 * ARG2 -> PRODH:PRODL
; Test Sign Bit
; PRODH = PRODH - ARG1
; Test Sign Bit
; 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 quadrature 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
Q1
Q2
Q3
Q4
Q1
Q2
Q3
Q4
Q1
Q2
21
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
22
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
To internal logic
XTAL
RF (2)
(3)
SLEEP
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
23
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
OSC1
CEXT
Fosc
Internal
clock
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
24
C EXT = 300 pF, T = 25°C
1000
900
R = 3.3k
800
Fosc (kHz)
700
R = 5k
600
500
400
R = 10k
300
200
R = 100k
100
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
25
Average
CEXT
22 pF
100 pF
300 pF
R EXT
Fosc @ 5V, 25°C
5k
4.12 MHz
± 1.4%
10k
2.35 MHz
± 1.4%
100k
268 kHz
± 1.1%
3.3k
1.80 MHz
± 1.0%
5k
1.27 MHz
± 1.0%
10k
688 kHz
± 1.2%
100k
77.2 kHz
± 1.0%
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 distribution. 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 unchanged 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
see Application Notes AN522 and AN607 from Microchip web site for a thorough explanation of
power-up sequence
3
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
26
VDD
VDD
R
(1)
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 Midrange 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
5
for details on interrupts see section 1.3.10
for details on table operations see section 1.3.9
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
27
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>
CALL, RETURN
RETFIE, RETLW
PCL
13
Stack Level 1
Stack Level 8
2K
4K
6K
8K
Reset Vector
0000h
Interrupt Vector
0004h
0005h
On-chip Program
Memory (Page 0)
On-chip Program
Memory (Page 1)
On-chip Program
Memory (Page 2)
On-chip Program
Memory (Page 3)
07FFh
0800h
0FFFh
1000h
17FFh
1800h
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
28
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
CALL SUB1_P1
:
:
ORG 0x900
SUB1_P1:
:
RETURN
; Select Page1 (800h-FFFh)
; Call subroutine in Page1 (800h-FFFh)
; called subroutine Page1 (800h-FFFh)
; 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 performed 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), the
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
PCLATU
PCLATH
PCU
PC
23
21
20
29
PCL
PCH
16 15
8
7
0
Reserved. Maintain these bits cleared.
Figura 1.16: PIC18x PC structure
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 microcontroller 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 controlling 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
30
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.
Direct Addressing and indirect addressing
CONTiNUARE MEMORIA PAG 149
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 specify 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
LIST p = p18C452
; List Directive,
#INCLUDE <P18C452.INC>
; Microchip Device Header File
#INCLUDE <MY_STD.MAC>
#INCLUDE <APP.MAC>
; File which includes my standard macros
; File which includes macros specific
; to this application
31
; Specify Device Configuration Bits for
; Program Configuration Registers 0 through 6
__CONFIG
__CONFIG
__CONFIG
__CONFIG
__CONFIG
__CONFIG
_CONFIG0,
_CONFIG1,
_CONFIG2,
_CONFIG3,
_CONFIG5,
_CONFIG6,
org 0x00
RESET_ADDR :
CP_OFF_0
LPSCEN_OFF_1 & RCRA6_OSC_1
BORV_25_2 & BOREN_ON_2 & PWRTEN_OFF_2
WDPS_128_3 & WDT_ON_3
CCP2MX_ON_5
SVTREN_ON_6
; Start of Program Memory
; First instruction to exec after a reset
end
Figura 1.17: Example: Specify configuration bits using the CONFIG directive
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.8
Low power mode (Sleep)
The SLEEP function halts controller activity and reduces current consumption to a minimum. 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
32
The first event will reset the device upon wake-up. However, the latter two events will
wake the device and then resume program execution.
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).
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
33
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
Interrupt Enable bit, PEIE, the PIE / PIR register pair that enables the peripheral interrupts 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. Interrupt 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 appropriate 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 interrupts.
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
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
34
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
35
RIVEDERE
MOVLW RCON_VALUE
MOVWF RCON
; RCON_VALUE = 1???????b
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
MOVWF INTCON
; Enable high and low global interrupts.
Figura 1.19: Example: Interrupt Initialization
• Serial ports and protocols (SSP, MSSP, USART, I2 C, CAN)
• 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
36
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).
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.
7
in the 18F family the PORTx register is also called LATx
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.
8
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
Data bus
D
37
Q
VDD
WR PORT
Q
CK
P
Data Latch
I/O pin
WR TRIS
D
Q
CK
Q
N
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
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 automatically 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
CLRF STATUS
CLRF PORTA
BSF
STATUS, RP0
MOVLW 0xCF
MOVWF TRISA
;
;
;
;
;
;
;
38
Bank0
Initialize PORTA clearing output latches
Select Bank1
Value used to initialize data direction
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 keydepression. 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
39
VDD
RBPU(2)
Data bus
WR Port
weak
P pull-up
Data Latch
D
Q
I/O
pin(1)
CK
TRIS Latch
D
Q
WR TRIS
TTL
Input
Buffer
CK
RD TRIS
Q
RD Port
D
EN
To Peripheral Module
Schmitt Trigger
Buffer
RD Port
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 viceversa. 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
40
Data bus
FOSC/4
0
PSout
1
1
Programmable
Prescaler
T0CKI pin
0
8
Sync with
Internal
clocks
TMR0
PSout
(2 cycle delay)
T0SE
3
PS2, PS1, PS0
PSA
T0CS
Set interrupt
flag bit T0IF
on overflow
Figura 1.23: Timer0 simplified block diagram
CLRF
CLRF
BSF
MOVLW
MOVWF
TMR0
INTCON
STATUS, RP0
0xC3
OPTION_REG
BCF
STATUS, RP0
;
;
;
;
;
;
;
;
Clear Timer0 register
Disable interrupts and clear T0IF
Bank1
PortB pull-ups are disabled,
Interrupt on rising edge of RB0
Timer0 increment from internal clock
with a prescaler of 1:16.
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, TIMER2, 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
41
• As a synchronous counter
• As an asynchronous counter
In timer mode, Timer1 increments every instruction cycle. In counter mode, it increments 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 capture/compare operations. The Timer3 module also has a software programmable prescaler.
For detailed timing diagrams and related problematics see the Family Reference Manual 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
CCPx Mode
CCPy Mode
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 special 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
42
Interaction
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 corresponding 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:
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
43
• 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 resolution 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
44
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
Max PWM Resolution = log
fosc
fpwm
log(2)
bits
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
1.4.4
45
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 implementation 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 methods 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 configured 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
46
• 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 generated depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL
bits.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
47
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 generated 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
48
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 generated 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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
49
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 information is contained in the messages that are transmitted. This is done via an identifier (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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
50
PIC18CXX8
with CAN
CAN
Transceiver
CAN
BUS
CAN
Transceiver
CAN
Transceiver
CAN
Transceiver
Microchip
MCP2510
Microchip
MCP2510
SPI
INTERFACE
PICmicro
Controller
CAN
Transceiver
PIC18CXX8
with integrated
CAN
PIC18CXX8
with integrated
CAN
PICmicro
Controller
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
required 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 Fundamentals Using PIC16C92x Microcontrollers”, AN649 “Yet Another Clock Using the
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
51
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 +
+
VIN –
–
Output
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
CM2:CM0 = 000
Comparators Reset (POR Default Value)
ANx0
ANx3
ANx1
ANx2
A
VIN -
A
VIN +
A
VIN -
A
VIN +
Off (Read as '0')
C2
Off (Read as '0')
ANx3
ANx1
ANx2
CM2:CM0 = 010
Two Independent Comparators
ANx0
ANx3
A
A
D
VIN -
D
VIN +
D
VIN -
D
VIN +
C1
Off (Read as '0')
C2
Off (Read as '0')
CM2:CM0 = 011
Three Inputs Multiplexed to Two Comparators
ANx0
VIN VIN +
CM2:CM0 = 111
Comparators Off
ANx0
C1
52
C1OUT
C1
ANx3
A
VIN -
A
VIN +
C1
C1OUT
C2
C2OUT
C1OUT
ANx1
ANx2
A
A
VIN VIN +
C2OUT
C2
ANx1
A
VIN -
ANx2
A
VIN +
C2OUT
CM2:CM0 = 101
Two Common Reference Comparators with Outputs
CM2:CM0 = 100
Two Common Reference Comparators
ANx0
ANx3
A
A
VIN VIN +
C1
C1OUT
ANx0
A
VIN -
ANx3
A
VIN +
C1
C1OUT
C2
C2OUT
C1OUT
ANx1
A
VIN -
ANx2
D
VIN +
C2
C2OUT
ANx1
A
VIN -
ANx2
D
VIN +
C2OUT
CM2:CM0 = 110
Four Inputs Multiplexed to Two Comparators
CM2:CM0 = 001
One Independent Comparator
ANx1
A
VIN -
ANx2
A
VIN +
C1
C1OUT
ANx0
A
ANx3
A
CIS = 0
CIS = 1
VINVIN+
C1
C1OUT
C2
C2OUT
C1OUT
ANx1
ANx0
ANx3
D
D
VIN VIN +
C1
Off (Read as '0')
ANx2
A
A
CIS = 0
CIS = 1
VINVIN+
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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
53
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
8R (1)
R
(1)
R (1)
R (1)
R
(1)
8R (1)
VRR
VR3
VREF
(From VRCON<3:0>)
16-1 Analog MUX
VR0
Figura 1.30: Vref diagram
The equations used to calculate the output of the Voltage Reference are as follows:
if VRR = 1 : VREF =
if VRR = 0 : VREF =
1.4.8
VR3 : VR0
∗ VDD
24
VDD VR3 : VR0
+
∗ VDD
4
32
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
54
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
011
(Input voltage)
AN3/VREF
010
AN2
8-bit A/D
Converter
001
AN1
VDD (1)
000
AN0
000 or
010 or
100
VREF
(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,
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
55
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
56
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
BSF IPR1, ADIP
BSF PIE1, ADIE
MOVLW 0xC1
MOVWF ADCON0
MOVLW 0x4E
MOVWF ADCON1
BCF PIR1, ADIF
BSF INTCON, PEIE
BSF INTCON, GIE
;
;
;
;
;
;
;
;
;
;
;
Configure A/D inputs,
result is left justified
High Priority.
Enable A/D interrupts
RC Clock, A/D is on,
Channel 0 is selected
Left Justified, AN0 is analog
Vref comes from AVDD and AVSS
Clear A/D interrupt flag bit
Enable peripheral interrupts
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
57
The port uses 11 I/O pins: the 8 data bit, CS as Chip Select, RD as ReaD operation 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 commands. 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
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
APPLICATION
Host
Controller/HUB
PIC16C745/765
VUSB
58
200 nF
1.5K
DD+
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.
CAPITOLO 1. ARCHITECTURE AND HARDWARE DESIGN
59
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
PIC18CXXX
VDD /VPP V DD
R1
MCLR/V PP
C1
R2
ICSP Connector
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.
60
CAPITOLO 2. INTERFACING PICS
61
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
CAPITOLO 2. INTERFACING PICS
62
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 electromagnetic, 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
CAPITOLO 2. INTERFACING PICS
63
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
r MCU and other electronic devices in the application circuit.
the PICmicro
Rather than designing discrete circuits to carry out this function, is best to use integrated 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.
CAPITOLO 2. INTERFACING PICS
64
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
CAPITOLO 2. INTERFACING PICS
65
Figura 2.8: Functional block diagram of LMD18200
2.5
RS232
Collegare un PICmicro ad una porta seriale RS232, del tipo che troviamo comunemente installata sui PC) è molto semplice. Una famiglia di circuiti integrati molto diffusa
(MAX220-249) si occupa della conversione dei livelli di tensione da TTL a RS232, e comprende anche i circuiti pompa per generare le tensioni necessarie garantendo una buona
protezione dalle scariche elettrostatiche.
L’integrato più diffuso è certamente il MAX232, prodotto dalla Maxim3 . che offre la
traduzione di livello per due canali in ingresso (RS232 ⇒ TTL) e due canali in uscita
(TTL ⇒ RS232).
L’utilizzo di questo integrato è immediato: è sufficiente collegarlo come descritto in
figura 2.9 e ci garantirà un funzionamento immediato e stabile.
Per informazioni sul software per gestire una comunicazione seriale, fare riferimento
alla sezione 1.4.4 Addressable USART.
3
www.maximic.com
CAPITOLO 2. INTERFACING PICS
66
+5V INPUT
C3
TOP VIEW
C5
C1+ 1
16 VCC
V+ 2
15 GND
C1- 3
C2+ 4
C2- 5
1
C1
14 T1OUT
MAX220
MAX232
MAX232A
V- 6
C2
13 R1IN
10 T2IN
9
R2IN 8
TTL/CMOS
INPUTS
R2OUT
DIP/SO
DEVICE
MAX220
MAX232
MAX232A
CAPACITANCE (µF)
C1 C2 C3 C4
4.7 4.7 10 10
1.0 1.0 1.0 1.0
0.1 0.1 0.1 0.1
V-
6
-10V
C4
T1OUT 14
+5V
RS-232
OUTPUTS
400kΩ
10 T2IN
T2OUT 7
12 R1OUT
C5
4.7
1.0
0.1
V+ 2 +10V
3 C14
C2+
+10V TO -10V
5 C2- VOLTAGE INVERTER
+5V
400kΩ
T1
11
IN
12 R1OUT
11 T1IN
T2OUT 7
16
VCC
+5V TO +10V
VOLTAGE DOUBLER
C1+
R1IN 13
TTL/CMOS
OUTPUTS
5kΩ
R2IN 8
9 R2OUT
5kΩ
GND
15
Figura 2.9: Piedinatura e descrizione del MAX232
RS-232
INPUTS
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, possono 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
67
CAPITOLO 3. PROGRAMMAZIONE
MOVF
ADDWF
RegistroA, w
RegistroB, f
68
: w indica di muovere verso l’accumulatore
: f indica di salvare il risultato nel registro
La memorizzazione del risultato nella sorgente elimina la necessità di istruzioni aggiuntive 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
SUBWF
BTFSZ
GOTO
GOTO
RegistroA, w
RegistroB, w
STATUS, Z
SonoUguali
SonoDiversi
: non modifichiamo il registro
: testiamo il flag Z
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 compilazione 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, similarmente 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
CAPITOLO 3. PROGRAMMAZIONE
69
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.
CAPITOLO 3. PROGRAMMAZIONE
3.4
70
FilterLab
FilterLab è un’applicazione rilasciata come download gratuito dalla microchip che permette 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’applicazione 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).
CAPITOLO 3. PROGRAMMAZIONE
3.5
71
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
PIC
.err
.hex
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.
CAPITOLO 3. PROGRAMMAZIONE
72
Utilizzando un singolo file, una volta steso il programma è sufficiente scegliere Quickbuild 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 configurazione. 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.
CAPITOLO 3. PROGRAMMAZIONE
73
• 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 preziose 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 funzionalità di debug. In caso di risposta affermativa inserirà nel codice sorgente alcune funzioni
CAPITOLO 3. PROGRAMMAZIONE
74
che permetteranno di controllare l’esecuzione del software. Al termine della fase di sviluppo è 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 impostare 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 microcontrollori. 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’indirizzo 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.
75
CAPITOLO 4. ESEMPI
76
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
movlw B’11111110’
movwf TRISB
;bcf
STATUS,RP0
; Accedi al banco 1 (Mid-range)
; Imposta PORTB <7:1> come Input
;
e PORTB<0> come Output
; Accedi al banco 0 (Mid-range)
MainLoop
btfsc
goto
bsf
call
goto
SpegniLED
bcf
call
goto
PORTB,0
SpegniLED
PORTB,0
Delay
MainLoop
; Se il LED e’ acceso
; Vai a SpegniLED
; Accendi il led
PORTB,0
Delay
MainLoop
; Spegni il LED
;Subroutines
Delay
clrf
clrf
Count
Count+1
DelayLoop
decfsz
goto
decfsz
goto
return
Count,1
DelayLoop
Count+1,1
DelayLoop
; Decrementa Count, salta se zero
; Decrementa Count+1, salta se zero
; Ritorna al punto di chiamata
END
Figura 4.1: Lampeggio di un LED senza interrupt
CAPITOLO 4. ESEMPI
77
Reset vector
DelayLoop
Impostazione
porte I/O
Decrementa
Count
Led acceso?
Count = 0
Vai a
SpegniLed
Decrementa
Count+1
No
Accendi
il LED
Spegni il
LED
Aspetta
ritardo
Aspetta
ritardo
goto DelayLoop
skip if clear
goto MainLoop
No
No
Count+1 = 0
Return
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
CAPITOLO 4. ESEMPI
78
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
goto Start
;Reset Vector
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
CAPITOLO 4. ESEMPI
79
list p=18f452, n=48, t=ON, st=OFF
#include "p18f452.inc"
ORG 0x00000
goto Start
;Reset Vector
org
goto
; Interrupt Vector Address
; goto Interrupt Service Routine
0x00008
ISR
Start
movlw
movwf
movlw
B’11111110’
TRISB
B’10000011’
movwf
movlw
T0CON
B’11100000’
movwf
INTCON
MainLoop
nop
goto
ISR
;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
;Set-up interrupts
;Bit 7 1 Global enable
;Bit 6 1 Peripheral enable
;Bit 5 1 Timer0 interrupt enable
; Your software here
MainLoop
; Interrupt Service Routine
btfsc INTCON,2
; Se interrupt sollevato dal timer
goto
Timer0Interrupt
retfie
Timer0Interrupt
btfsc PORTB,0
goto
SpegniLED
bsf
PORTB,0
bcf
INTCON,2
retfie
SpegniLED
bcf
PORTB,0
bcf
INTCON,2
retfie
; Se il LED e’ acceso
; Accendi il led
; Elimina il flag di Interrupt
; Spegni il LED
; Elimina il flag di Interrupt
END
Figura 4.4: Lampeggio di un LED con interrupt
CAPITOLO 4. ESEMPI
0x0000
80
goto Start
Reset vector
0x0001
0x0008
goto ISR
Interrupt vector
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-
CAPITOLO 4. ESEMPI
81
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 programma 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ù significativi 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 routine 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 applicazione sarà presentata nel documento relativo alla programmazione dei PIC in linguaggio
C.
CAPITOLO 4. ESEMPI
82
;************************************************************
; 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
goto
Start
; Reset Vector Address
org 0x00008
goto
ISR
; Interrupt Vector Address
; goto Interrupt Service Routine
;************************************************************
; program
org
Start
clrf
clrf
bcf
0x00020
PORTB
TRISB
TRISC,6
; clear all bits of PORTB
; Set PORTB as outputs
; Make RC6 an output
;Set up USART module
movlw
movwf
19h
SPBRG
; 9600 baud @4MHz
bsf
bsf
TXSTA,TXEN
TXSTA,BRGH
; Enable transmit
; Select high baud rate
bsf
bsf
RCSTA,SPEN
RCSTA,CREN
; Enable Serial Port
; Enable continuous reception
bcf
bsf
bsf
bsf
PIR1,RCIF
PIE1,RCIE
INTCON,PEIE
INTCON,GIE
;
;
;
;
Clear RCIF Interrupt Flag
Set RCIE Interrupt Enable
Enable peripheral interrupts
Enable global interrupts
Figura 4.6: Generazione PWM (1/4)
CAPITOLO 4. ESEMPI
83
;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
bsf
bsf
movlw
movwf
bcf
movlw
movwf
CCP2CON
CCP2CON, CCP2M3
CCP2CON, CCP2M2
0x3F
PR2
TRISC, 1
0x00
CCPR2L
;
;
;
;
;
;
CCP module is off
select PWM mode
select PWM mode
Set PWM frequency to 78.12kHz
make channel 1 an output
;Set the TMR2 prescale value and enable Timer2 by writing to T2CON
;Configure the CCP2 module for PWM operation
clrf
T2CON
; clear T2CON
clrf
TMR2
; clear Timer2
bsf
T2CON,TMR2ON ; turn on Timer2
;Start at 50% duty cycle
movlw 0x20
;
movwf CCPR2L
; Set PWM duty cycle
MLOOP
btfsc
goto
PORTA,4
MLOOP
; Has S2 been pressed? (low when pressed.)
; No, check again
SwitchMode
btfss
goto
bcf
goto
PORTB,RB0
SetPot
PORTB,RB0
Debounce
; if was POT
SetPot
bsf
PORTB,RB0
; if was SER
; set to pot
Debounce
btfss
goto
goto
PORTA,4
Debounce
MLOOP
; Has key been released?
; No, wait some more
; yes, wait for next key press
; set to SER
Figura 4.7: Generazione PWM (2/4)
CAPITOLO 4. ESEMPI
84
;************************************************************
; Service A/D interrupt
ISR
; Save context (WREG and STATUS) if required.
;A/D Interrupt
ADInt
btfss
goto
PIR1,ADIF
USARTInt
; Did A/D cause interrupt?
; No, check other sources
movf
btfsc
movwf
movwf
bcf
call
bsf
goto
ADRESH,W
PORTB,RB0
CCPR2L
TXREG
PIR1,ADIF
SetupDelay
ADCON0,GO
EndISR
;
;
;
;
;
;
;
;
;USART Interrupt
USARTInt
btfss PIR1,RCIF
goto
OtherInt
Get A/D value (hi bits)
Skip if Serial mode
Set PWM duty cycle
Send carachter on Serial port
Reset A/D int flag
Delay for 15 cycles
Start A/D conversion
return from ISR
; Did USART cause interrupt?
; No, some other interrupt
movlw
andwf
btfss
goto
06h
RCSTA,W
STATUS,Z
RcvError
;
;
;
;
Mask out unwanted bits
Check for errors
Was either error status bit set?
Found error, flag it
movf
btfss
movwf
movwf
goto
RCREG,W
PORTB,RB0
CCPR2L
TXREG
EndISR
;
;
;
;
;
Get input data
Skip if Pot mode
Set PWM duty cycle
Echo character back
go to end of ISR, restore context, return
RcvError
bcf
bsf
;
Signal
goto
RCSTA,CREN
; Clear receiver status
RCSTA,CREN
error to user
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)
CAPITOLO 4. ESEMPI
85
;************************************************************
; 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’
movwf ADCON1
; Make RA0,RA1,RA4 analog inputs
movlw
movwf
B’11000001’
ADCON0
; Select RC osc, AN0 selected,
; A/D enabled
bcf
bsf
PIR1,ADIF
PIE1,ADIE
; Clear A/D interrupt flag
; 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
movwf
SD
decfsz
goto
return
.3
TEMP
; Load Temp with decimal 3
TEMP, F
SD
; Delay loop
END
Figura 4.9: Generazione PWM (4/4)
Capitolo 5
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 5.1 particolare 2).
1
2
Per una descrizione più completa fare riferiento al documento Microchip 51275a
Per il datasheet del sensore cercare il documento Microchip DS21462
86
CAPITOLO 5. DESCRIZIONE DELLA PICDEM2 PLUS
7
2
9
87
8
15
13
11
10
3
5
14
12
4
17
18
1
16
2
6
Figura 5.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 5.1 sono riportati i collegamenti presenti sulla scheda.
Device
LEDs
RS-232
N/A
S1
S2
S3
Pot
R16
LCD
EEPROM Buzzer
ICD
Temp
Sensor
Y1/Y2
18-pin
RB3:RB0
MCLR
RA4
RB0
RA0
N/A
RB6/RB7
N/A
Yes
28-pin
RB3:RB0 RC6/RC7
MCLR
RA4
RB0
RA0
RA3:RA1 RC3/RC4
RD3:RD0
RC2
RB6/RB7
RC3/RC4
Yes
40-pin
RB3:RB0 RC6/RC7
MCLR
RA4
RB0
RA0
RA3:RS1 RC3/RC4
RD3:RD0
RC2
RB6/RB7
RC3/RC4
Yes
N/A
N/A
Tabella 5.1: PICDEM2 plus connections
Appendice A
Realizzazione di una demo-board
A.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 raccoglie questi componenti, oltre ad un sempre utile regolatore di tensione e la predisposizione
alla comunicazione seriale con standard RS-232.
A.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 A.2.
Seguitando troviamo il PICmicro (IC1) con collegato sui piedini 14-15 il quarzo (X1) ed i
relativi condensatori1 C7 e C8.
A.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
88
APPENDICE A. REALIZZAZIONE DI UNA DEMO-BOARD
89
C4 C7 C8
IC2
J1
C2
IC1
X1
C1
C5 C3
C6
Figura A.1: Posizionamento dei componenti demo board A
+5V INPUT
C3
TOP VIEW
C5
C1+ 1
16 VCC
V+ 2
15 GND
C1- 3
14 T1OUT
C2+ 4
C2- 5
MAX220
MAX232
MAX232A
V- 6
1
C1
C2
13 R1IN
12 R1OUT
10 T2IN
9
R2IN 8
TTL/CMOS
INPUTS
R2OUT
DIP/SO
CAPACITANCE (µF)
DEVICE
C1 C2 C3 C4
MAX220
4.7 4.7 10 10
MAX232
1.0 1.0 1.0 1.0
MAX232A 0.1 0.1 0.1 0.1
V-
6
-10V
C4
T1OUT 14
+5V
RS-232
OUTPUTS
400kΩ
10 T2IN
T2OUT 7
12 R1OUT
C5
4.7
1.0
0.1
V+ 2 +10V
3 C14
C2+
+10V TO -10V
5 C2- VOLTAGE INVERTER
+5V
400kΩ
11 T1IN
11 T1IN
T2OUT 7
16
VCC
+5V TO +10V
VOLTAGE DOUBLER
C1+
R1IN 13
TTL/CMOS
OUTPUTS
5kΩ
R2IN 8
9 R2OUT
5kΩ
GND
15
Figura A.2: Piedinatura e descrizione del MAX232
RS-232
INPUTS
APPENDICE A. REALIZZAZIONE DI UNA DEMO-BOARD
Figura A.3: Circuito stampato demo board A
Figura A.4: Circuito stampato demo board B
90
Appendice B
Instruction sets
B.1
PIC16F84A e PIC16F87x
Il set di istruzioni dei PIC16F84a e PIC16F87x sono caratterizzati da un numero di istruzioni 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 B.4.
B.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
91
APPENDICE B. INSTRUCTION SETS
92
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)
APPENDICE B. INSTRUCTION SETS
Mnemonic,
Operands
93
14-Bit Opcode
Description
Cycles
MSb
LSb
Status
Affected
Notes
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ANDWF
CLRF
CLRW
COMF
DECF
DECFSZ
INCF
INCFSZ
IORWF
MOVF
MOVWF
NOP
RLF
RRF
SUBWF
SWAPF
XORWF
f, d
f, d
f
f, d
f, d
f, d
f, d
f, d
f, d
f, d
f
f, d
f, d
f, d
f, d
f, d
Add W and f
AND W with f
Clear f
Clear W
Complement f
Decrement f
Decrement f, Skip if 0
Increment f
Increment f, Skip if 0
Inclusive OR W with f
Move f
Move W to f
No Operation
Rotate Left f through Carry
Rotate Right f through Carry
Subtract W from f
Swap nibbles in f
Exclusive OR W with f
BCF
BSF
BTFSC
BTFSS
f, b
f, b
f, b
f, b
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
1
1
1
1
1
1
1 (2)
1
1 (2)
1
1
1
1
1
1
1
1
1
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
00
0111
0101
0001
0001
1001
0011
1011
1010
1111
0100
1000
0000
0000
1101
1100
0010
1110
0110
dfff
dfff
lfff
0xxx
dfff
dfff
dfff
dfff
dfff
dfff
dfff
lfff
0xx0
dfff
dfff
dfff
dfff
dfff
ffff
ffff
ffff
xxxx
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
0000
ffff
ffff
ffff
ffff
ffff
00bb
01bb
10bb
11bb
bfff
bfff
bfff
bfff
ffff
ffff
ffff
ffff
111x
1001
0kkk
0000
1kkk
1000
00xx
0000
01xx
0000
0000
110x
1010
kkkk
kkkk
kkkk
0110
kkkk
kkkk
kkkk
0000
kkkk
0000
0110
kkkk
kkkk
kkkk
kkkk
kkkk
0100
kkkk
kkkk
kkkk
1001
kkkk
1000
0011
kkkk
kkkk
C,DC,Z
Z
Z
Z
Z
Z
Z
Z
Z
C
C
C,DC,Z
Z
1,2
1,2
2
1,2
1,2
1,2,3
1,2
1,2,3
1,2
1,2
1,2
1,2
1,2
1,2
1,2
BIT-ORIENTED FILE REGISTER OPERATIONS
1
1
1 (2)
1 (2)
01
01
01
01
1,2
1,2
3
3
LITERAL AND CONTROL OPERATIONS
ADDLW
ANDLW
CALL
CLRWDT
GOTO
IORLW
MOVLW
RETFIE
RETLW
RETURN
SLEEP
SUBLW
XORLW
k
k
k
k
k
k
k
k
k
Add literal and W
AND literal with W
Call subroutine
Clear Watchdog Timer
Go to address
Inclusive OR literal with W
Move literal to W
Return from interrupt
Return with literal in W
Return from Subroutine
Go into standby mode
Subtract W from literal
Exclusive OR literal with W
1
1
2
1
2
1
1
2
2
2
1
1
1
11
11
10
00
10
11
11
00
11
00
00
11
11
C,DC,Z
Z
TO,PD
Z
TO,PD
C,DC,Z
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 B.1: PIC16F84A instruction set
APPENDICE B. INSTRUCTION SETS
Mnemonic,
Operands
94
16-Bit Instruction Word
Description
Cycles
MSb
LSb
Status
Affected
Notes
BYTE-ORIENTED FILE REGISTER OPERATIONS
ADDWF
ADDWFC
ANDWF
CLRF
COMF
CPFSEQ
CPFSGT
CPFSLT
DECF
DECFSZ
DCFSNZ
INCF
INCFSZ
INFSNZ
IORWF
MOVF
MOVFF
f, d, a
f, d, a
f, d, a
f, a
f, d, a
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
f, d, a
fs, fd
MOVWF
MULWF
NEGF
RLCF
RLNCF
RRCF
RRNCF
SETF
SUBFWB
f, a
f, a
f, a
f, d, a
f, d, a
f, d, a
f, d, a
f, a
f, d, a
SUBWF
SUBWFB
f, d, a
f, d, a
SWAPF
TSTFSZ
XORWF
f, d, a
f, a
f, d, a
Add WREG and f
Add WREG and Carry bit to f
AND WREG with f
Clear f
Complement f
Compare f with WREG, skip =
Compare f with WREG, skip >
Compare f with WREG, skip <
Decrement f
Decrement f, Skip if 0
Decrement f, Skip if Not 0
Increment f
Increment f, Skip if 0
Increment f, Skip if Not 0
Inclusive OR WREG with f
Move f
Move fs (source) to 1st word
fd (destination) 2nd word
Move WREG to f
Multiply WREG with f
Negate f
Rotate Left f through Carry
Rotate Left f (No Carry)
Rotate Right f through Carry
Rotate Right f (No Carry)
Set f
Subtract f from WREG with
borrow
Subtract WREG from f
Subtract WREG from f with
borrow
Swap nibbles in f
Test f, skip if 0
Exclusive OR WREG with f
1
1
1
1
1
1 (2 or 3)
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1 (2 or 3)
1 (2 or 3)
1
1
2
C, DC, Z, OV, N
C, DC, Z, OV, N
Z, N
Z
Z, N
None
None
None
C, DC, Z, OV, N
None
None
C, DC, Z, OV, N
None
None
Z, N
Z, N
None
1, 2
1, 2
1,2
2
1, 2
4
4
1, 2
1, 2, 3, 4
1, 2, 3, 4
1, 2
1, 2, 3, 4
4
1, 2
1, 2
1
1
1
1
1
1
1
1
1
1
0010 01da0
0010
0da
0001 01da
0110 101a
0001 11da
0110 001a
0110 010a
0110 000a
0000 01da
0010 11da
0100 11da
0010 10da
0011 11da
0100 10da
0001 00da
0101 00da
1100 ffff
1111 ffff
0110 111a
0000 001a
0110 110a
0011 01da
0100 01da
0011 00da
0100 00da
0110 100a
0101 01da
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
1
1
0101
0101
11da
10da
ffff
ffff
ffff C, DC, Z, OV, N
ffff C, DC, Z, OV, N
1
1 (2 or 3)
1
0011
0110
0001
10da
011a
10da
ffff
ffff
ffff
ffff None
ffff None
ffff Z, N
4
1, 2
1
1
1 (2 or 3)
1 (2 or 3)
1
1001
1000
1011
1010
0111
bbba
bbba
bbba
bbba
bbba
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
ffff
None
None
None
None
None
1, 2
1, 2
3, 4
3, 4
1, 2
None
None
C, DC, Z, OV, N
C, Z, N
Z, N
C, Z, N
Z, N
None
C, DC, Z, OV, N
1, 2
1, 2
1, 2
1, 2
BIT-ORIENTED FILE REGISTER OPERATIONS
BCF
BSF
BTFSC
BTFSS
BTG
f, b, a
f, b, a
f, b, a
f, b, a
f, d, a
Bit Clear f
Bit Set f
Bit Test f, Skip if Clear
Bit Test f, Skip if Set
Bit Toggle f
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 B.2: PIC18F45x instruction set
APPENDICE B. INSTRUCTION SETS
95
16-Bit Instruction Word
Mnemonic,
Operands
Description
Cycles
MSb
LSb
Status
Affected
Notes
CONTROL OPERATIONS
BC
BN
BNC
BNN
BNOV
BNZ
BOV
BRA
BZ
CALL
n
n
n
n
n
n
n
n
n
n, s
CLRWDT
DAW
GOTO
—
—
n
NOP
NOP
POP
PUSH
RCALL
RESET
RETFIE
—
—
—
—
n
RETLW
RETURN
SLEEP
1 (2)
1 (2)
1 (2)
1 (2)
1 (2)
2
1 (2)
1 (2)
1 (2)
2
s
Branch if Carry
Branch if Negative
Branch if Not Carry
Branch if Not Negative
Branch if Not Overflow
Branch if Not Zero
Branch if Overflow
Branch Unconditionally
Branch if Zero
Call subroutine1st word
2nd word
Clear Watchdog Timer
Decimal Adjust WREG
Go to address1st word
2nd word
No Operation
No Operation
Pop top of return stack (TOS)
Push top of return stack (TOS)
Relative Call
Software device RESET
Return from interrupt enable
k
s
—
Return with literal in WREG
Return from Subroutine
Go into Standby mode
1
1
1
1
2
1
2
1110
1110
1110
1110
1110
1110
1110
1101
1110
1110
1111
0000
0000
1110
1111
0000
1111
0000
0000
1101
0000
0000
0010
0110
0011
0111
0101
0001
0100
0nnn
0000
110s
kkkk
0000
0000
1111
kkkk
0000
xxxx
0000
0000
1nnn
0000
0000
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0000
0000
kkkk
kkkk
0000
xxxx
0000
0000
nnnn
1111
0001
2
2
1
0000
0000
0000
1100
0000
0000
kkkk
0001
0000
1
1
2
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
nnnn
kkkk
kkkk
0100
0111
kkkk
kkkk
0000
xxxx
0110
0101
nnnn
1111
000s
Description
Cycles
MSb
TO, PD
C
None
None
None
None
None
None
All
GIE/GIEH,
PEIE/GIEL
kkkk None
001s None
0011 TO, PD
16-Bit Instruction Word
Mnemonic,
Operands
None
None
None
None
None
None
None
None
None
None
LSb
Status
Affected
LITERAL OPERATIONS
ADDLW
ANDLW
IORLW
LFSR
k
k
k
f, k
MOVLB
MOVLW
MULLW
RETLW
SUBLW
XORLW
k
k
k
k
k
k
Add literal and WREG
AND literal with WREG
Inclusive OR literal with WREG
Move literal (12-bit) 2nd word
to FSRx 1st word
Move literal to BSR<3:0>
Move literal to WREG
Multiply literal with WREG
Return with literal in WREG
Subtract WREG from literal
Exclusive OR literal with WREG
1
1
1
2
1
1
1
2
1
1
0000
0000
0000
1110
1111
0000
0000
0000
0000
0000
0000
1111
1011
1001
1110
0000
0001
1110
1101
1100
1000
1010
kkkk
kkkk
kkkk
00ff
kkkk
0000
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
kkkk
C, DC, Z, OV, N
Z, N
Z, N
None
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
0000
1000
1001
1010
1011
1100
1101
1110
1111
None
None
None
None
None
None
None
None
None
None
None
None
C, DC, Z, OV, N
Z, N
DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
TBLRD*
TBLRD*+
TBLRD*TBLRD+*
TBLWT*
TBLWT*+
TBLWT*TBLWT+*
Table Read
Table Read with post-increment
Table Read with post-decrement
Table Read with pre-increment
Table Write
Table Write with post-increment
Table Write with post-decrement
Table Write with pre-increment
2
2 (5)
Tabella B.3: PIC18F45x instruction set (continued)
4
Notes
APPENDICE B. INSTRUCTION SETS
Field
96
Description
Register file address (0x00 to 0x7F)
Working register (accumulator)
Bit address within an 8-bit file register (0 to 7)
Literal field, constant data or label (may be either an 8-bit or an 11-bit value)
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)
f
W
b
k
x
Tabella B.4: Istruction set conventions
Appendice C
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 input 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 mathematical(add, subtract, ...), logical (and, or, ...), and shifting operation.
Analog Refers to electronic transmission accomplished by adding signals of varying frequency 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
97
APPENDICE C. GLOSSARY
98
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. Machine 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. Equivalent 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.
APPENDICE C. GLOSSARY
99
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 industrial applications.
Capture A function of the CCP module in which the value of a timer/counter is “captured” 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 location 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 16bit 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.
APPENDICE C. GLOSSARY
100
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 characteristics 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 nonvolatile 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 MPASM 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.
APPENDICE C. GLOSSARY
101
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 module, 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 capability 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 symbols 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 / Write 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 incircuit. Program Memory technology that is almost functionally equivalent to Program EEPROM Memory.
APPENDICE C. GLOSSARY
102
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 Program 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 abstraction 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.
APPENDICE C. GLOSSARY
103
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 Instruction, 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 executed, 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 products 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.
APPENDICE C. GLOSSARY
104
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.
APPENDICE C. GLOSSARY
105
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 instructions.
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 MPASM is a DOS or Windows-based PC application that provides a platform for developing 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 assembler, 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.
APPENDICE C. GLOSSARY
106
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 communications 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 MPASM 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 addressing 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 implemented. 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 Windows 95/98, Windows NT, or Windows 2000. MPLAB IDE runs on 486 or higher
machines.
APPENDICE C. GLOSSARY
107
PICmicro MCUs PICmicro microcontrollers (MCUs) refers to all Microchip microcontroller 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. Programs 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 contains 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. Programs 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.
APPENDICE C. GLOSSARY
108
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 contained 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.
APPENDICE C. GLOSSARY
SFR Special Function Register.
information for the device.
109
These registers contain the control bits and status
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 microprocessor.
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 MPASMAssembler 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, return 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 command 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.
APPENDICE C. GLOSSARY
110
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 application.
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 programmer, 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 Memory 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 processor after a selectable length of time. The WDT is enabled or disabled and set up
using configuration bits.
Appendice D
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
111
APPENDICE D. APPLICATION NOTES
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
112
Fly UP