An introduction to PICMicro Microcontrollers

Nicholas Amadori 21 dicembre 2004

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 . . . . . . . . 5 5 9 9 10 12 12 15 15 15 17 21 23 27 27 28 29 29 30 32 35 38 42 47 48 50 50 53 54 55

. . . . . . . . . . . . . . . . . . . . needs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2 Interfacing PICs 57 2.1 LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 2.2 Switch de-bounce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 2.3 Relais and Solenoids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

INDICE

II

2.4 2.5

Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 64 64 65 65 66 67 68 68 69 69 70

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

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

4 Esempi 72 4.1 Lampeggio LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.2 Generazione PWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 4.3 Controllore per motori stepper . . . . . . . . . . . . . . . . . . . . . . . . . 78 A Descrizione della PICDEM2 plus B Realizzazione di una demo-board B.1 16F84 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.1.1 Schema elettrico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.1.2 Circuito stampato . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 85 85 85 85

C Instruction sets 88 C.1 PIC16F84A e PIC16F87x . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 C.2 PIC18F45x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 D Glossary E Application Notes 94 108

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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 7 8 13 14 16 17 17 18 19 20 21 23 24 25 26 28 31 32 34 35 36 37 37 40 46 47 48 49 50 51 53 55 56

ELENCO DELLE FIGURE

IV

2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.1 3.2 3.3 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.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 .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

58 58 58 59 60 61 61 62 63

La finestra principale di Application Maestro . . . . . . . . . . . . . . . . . 66 FilterLab in azione . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Files generati dal compilatore . . . . . . . . . . . . . . . . . . . . . . . . . . 68 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) . . . . . . . . . . . . . . . . . . . . . . . . LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . con interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 74 75 76 77 79 80 81 82

A.1 PICDEM2 plus hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 B.1 B.2 B.3 B.4 Posizionamento dei componenti demo board Piedinatura e descrizione del MAX232 . . . Circuito stampato demo board A . . . . . . Circuito stampato demo board B . . . . . . A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 86 87 87

Elenco delle tabelle
1.1 1.2 1.3 Example RC oscillator frequencies . . . . . . . . . . . . . . . . . . . . . . . 22 Interaction between two CCP modules . . . . . . . . . . . . . . . . . . . . . 39 Minimum Duty Cycle Bit Time . . . . . . . . . . . . . . . . . . . . . . . . . 41

A.1 PICDEM2 plus connections . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 C.1 C.2 C.3 C.4 PIC16F84A instruction set . . . . . . PIC18F45x instruction set . . . . . . . PIC18F45x instruction set (continued) Istruction set conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 91 92 93

Introduzione
Questo articolo vuole essere una introduzione al mondo dei microcontrollori PICmicro, prodotti dalla Microchip a partire dagli anni ’80. Oggi i microcontrollori sono presenti praticamente in ogni oggetto elettronico, dalle radiosveglie ai forni a microonde. Negli ultimi anni si ` assistito ad una sempre maggior e 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 e domestiche in cui sono impiegati, per la mole di documentazione e codice sorgente che si pu` trovare su Internet, e per il basso costo per unit` o a che ne favorisce l’utilizzo per aplicazioni di larga scala. Oggi sono disponibili sul mercato un gran numero di microcontrollori anche pi` potenti dei PICmicro1 , ma essendo soluzioni u pi` nuove sono spesso sistemi pi` “chiusi”, utilizzabili solamente con i sistemi di sviluppo u u proprietari della casa, meno conosciuti e pi` costosi. u I microcontrollori, ed in particolar modo i PICmicro, si rivelano alleati formidabili per gli studenti di informatica ed elettronica interessati a realizzare piccole applicazioni. La loro versatilit` permette di sostituire chip dedicati non sempre facilmente reperibili o a 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 u consumi, si rivelano preziosi nelle applicazioni di robotica mobile. I capitoli di questa relazione che descrivono l’architettura e l’interfacciamento dei PICmicro sono stati scritti in inglese. Poich` tali parti si rifanno alla documentazione originale e della Microchip, si ` scelto di evitare una traduzione che, per quanto corretta, avrebbe e reso meno immediata la descrizione rompendo la corrispondenza tra i nomi delle funzioni ed i loro acronimi. Il capitolo 1 (in inglese) dopo un introduzione sull’architettura dei PICmicro e le famiglie di prodotti, descrive le funzioni del nucleo e delle periferiche. Nel capitolo 2 sono presentati alcuni esempi di interfacciamento. Il capitolo 3 descrive il processo di programmazione delle unit`, a partire dalla stesura a del programma in linguaggio Assembly o C, alla simulazione, la programmazione fisica e
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 e
1

ELENCO DELLE TABELLE

3

il debug. Nel capitolo 4 due esempi mettono in pratica quanto illustrato. Nelle appendici si trovano la descrizione della scheda scheda di test PICDEM2 plus, gli schemi per realizzare una scheda “custom” basata sul PIC16F84A dotata di interfaccia seriale, i set di istruzioni dei PIC16F84A e PIC18F45x utilizzati negli esempi. Chiudono la relazione un esaustivo glossario dei termini tecnici e la bibliografia delle Application Notes pi` utili. u

Ringraziamenti
Questa relazione non sarebbe mai stata scritta senza l’aiuto di alcuni amici. Grazie a Valerio, la cui passione e la voglia di fare (e il garage ;-) ) ci hanno fatto muovere insieme i primi passi nel mondo dei microcontrollori. Grazie a Riccardo e Giuseppe, che hanno reso piacevoli le ore trascorse insieme in laboratorio, e hanno creduto in me fino ad utilizzare i PICmicro per le loro tesi di laurea. Grazie al prof. Luca Zaccarian che mi ha permesso di impiegare questa mia passione in ambito universitario, aprendo una nuova strada nel laboratorio di robotica.

Nicholas

Capitolo 1

Architecture Description and Hardware Design
1.1 Generalities

You don’t need to fully understand this section to use PICs, but having an overview of it’s architecture can help in writing better software. Architecture of PICMicro devices can be thought as a processor, storage memory, data memory and peripherals all embedded in a single chip. The high performance of the PICmicro devices can be attributed to a number of architectural features commonly found in RISC microprocessors. These include: • Harvard architecture • Long Word Instructions • Single Word Instructions • Single Cycle Instructions • Instruction Pipelining • Reduced Instruction Set • Register File Architecture • Orthogonal (Symmetric) Instructions

Harvard Architecture Harvard architecture has the program memory and data memory as separate memories which are accessed from separate buses. This improves bandwidth over traditional von Neumann architecture in which program and data are fetched from the same memory

1.1. GENERALITIES

6

13 EPROM Program Memory up to 8K x 14 Program Bus 14 Instruction reg Direct Addr 7 Program Counter

Data Bus

8

PORTA RA0 RA1 RA2 RA3 RA4 RA5 PORTB

8 Level Stack (13-bit)

RAM File Registers up to 368 x 8 RAM Addr (1) 9

Addr MUX 8 Indirect Addr

FSR reg STATUS reg 8 3 PORTC

RB0/INT RB1 RB2 RB3 RB4 RB5 RB6 RB7 RC0 RC1 RC2 RC3 RC4 RC5 RC6 RC7

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

MUX

ALU PORTD W reg

MCLR

VDD, VSS

PORTE

RD0 RD1 RD2 RD3 RD4 RD5 RD6 RD7 RE0 RE1 RE2 RE3 RE4 RE5 RE6 RE7

Timer0

Timer1

Timer2

A/D PORTF

CCPs

Comparators

Synchronous Serial Port

USARTs

RF0 RF1 RF2 RF3 RF4 RF5 RF6 RF7

Other Modules

Parallel Slave Port

LCD Drivers

PORTG RG0 RG1 RG2 RG3 RG4 RG5 RG6 RG7

Voltage Reference

Data EEPROM up to 256 x 8

Peripheral Modules (Note 3)

General Purpose I/O (Note 3)

Note 1: The high order bits of the Direct Address for the RAM are from the STATUS register. 2: Not all devices have this feature, please refer to device data sheet. 3: Many of the general purpose I/O pins are multiplexed with one or more peripheral module functions. The multiplexing combinations are device dependent.

Figura 1.1: MID-Range PICMicro architecture

1.1. GENERALITIES

7

Harvard (PICmicro)

Data memory

8

CPU

12-16

Program memory

Von Neumann
8

CPU

Program and data memory

Figura 1.2: Architectures: Harvard vs. von Neumann

using the same bus. To execute an instruction, a von Neumann machine must make one or more (generally more) accesses across the 8-bit bus to fetch the instruction. Then data may need to be fetched, operated on and possibly written. As can be seen from this description, the bus can become extremely congested. With a Harvard architecture, the instruction is fetched in a single instruction cycle (all 12/16 bits). While the program memory is being accessed, the data memory is on an independent bus and can be read and written. These separated busses allow one instruction to execute, while the next instruction is fetched. Long Word Instructions Long word instructions have a wider (more bits) instruction bus than the 8-bit data memory bus. This is possible because the two buses are separate. This allows instructions to be sized differently than the 8-bit wide data word and allows a more efficient use of the program memory, since the program memory width is optimized to the architectural requirements. Single Word Instructions Typically in the von Neumann architecture, most instructions are multi-byte. In general, a device with 4 KBytes of program memory would allow approximately 2K of instructions.

1.1. GENERALITIES

8

This 2:1 ratio is generalized and dependent on the application code. Since each instruction may take multiple bytes, there is no assurance that each location is a valid instruction. Single word instruction opcodes are 12/14/16-bits wide1 making it possible to have all but a few instructions be single word instructions. A 16-bit wide program memory access bus fetches a 16-bit instruction in a single cycle.With single word instructions, the number of words of program memory locations equals the number of instructions for the device. This means that all locations are valid instructions. Double Word Instructions Some operations require more information then can be stored in the 16 bits of a program memory location. These operations require a double word instruction, and are therefore 32-bits wide. The first word indicates to the CPU that the next program memory location is the additional information for this instruction and not an instruction. If the CPU tries to execute the second word of an instruction (due to a software modified PC pointing to that location as an instruction), the fetched data is executed as a NOP. Double word instruction execution is not split between the two TCY cycles by an interrupt request. That is, when an interrupt request occurs during the execution of a double word instruction, the execution of the instruction is completed before the processor vectors to the interrupt address. The interrupt latency is preserved. Instruction Pipeline The instruction pipeline is a two-stage pipeline that overlaps the fetch and execution of instructions. The fetch of the instruction takes one TCY, while the execution takes another TCY. However, due to the overlap of the fetch of current instruction and execution of previous instruction, an instruction is fetched and another instruction is executed every TCY.

TCY0
1. MOVLW 55h 2. MOVWF PORTB 3. BRA 4. BSF SUB_1 PORTA, BIT3 (Forced NOP)

TCY1 Execute 1 Fetch 2

TCY2 Execute 2 Fetch 3

TCY3

TCY4

TCY5

Fetch 1

Execute 3 Fetch 4 Flush (NOP) Fetch SUB_1 Execute SUB_1

5. Instruction @ address SUB_1

All instructions are single cycle, except for any program branches. These take two cycles since the fetch instruction is “flushed” from the pipeline while the new instruction is being fetched and then executed.

Figura 1.3: Two-stage Pipeline

1

see section 1.2.2

1.2. PIC FAMILIES

9

Single Cycle Instructions With the program memory bus being 12/14/16-bits wide, the entire instruction is fetched in a single machine cycle (TCY), except for double word instructions which require two cycles to execute. The instruction contains all the information required and is executed in a single cycle. There may be a one cycle delay in execution if the result of the instruction modified the contents of the program counter. This requires the pipeline to be flushed and a new instruction to be fetched. Reduced Instruction Set When an instruction set is well designed and highly orthogonal (symmetric), fewer 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.

1.2. PIC FAMILIES

10

FLASH devices, identified with the letter F, as in PIC16Fxxx. ROM Devices ROM devices have their program memory fixed at the time of the silicon manufacture. Since the program memory cannot be changed, the device is usually housed in the low cost plastic package. Microchip offers a masked Read Only Memory (ROM) version of several of the highest volume parts, thus giving customers a lower cost option for high volume, mature products. EPROM Devices EPROM devices can be erased and reprogrammed with an UV light source. These devices are easily recognizable because of their ceramic package with a small quartz window that exposes the internal silicon. The amount of time required to completely erase a UV erasable device with a suitable eraser is usually 10 to 20 minutes. Fluorescent lights and sunlight both emit ultraviolet light at the erasure wavelength. Leaving a UV erasable device’s window uncovered could cause, over time, the devices memory cells to become erased. The erasure time for a fluorescent light is about three years, while sunlight requires only about one week. To prevent the memory cells from losing data, an opaque label should be placed over the erasure window. Flash Memory Devices These devices are electrically erasable, and are offered in a low cost plastic package. Being electrically erasable, these devices can be both erased and reprogrammed without removal from the circuit. A device will have the same specifications whether it is used for prototype development, pilot programs, or production. These are the best for development, because can be erased and reprogrammed in few seconds, allowing extensive test and debug of the software. Such devices have a tipical life of 100.000 erase/write cycles.

1.2.2

Logical Families

PICmicro devices are grouped by the size of their Instruction Word. The three current PICmicro families are: 1. Base-Line: 12-bit Instruction Word length 2. Mid-Range: 14-bit Instruction Word length 3. High-End: 16-bit Instruction Word length

1.2. PIC FAMILIES

11

PIC12 Family: 8-pin 12-bit/14-bit program word The PIC12 family packs Microchip’s powerful RISC-based PICmicro architecture into 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).

1.2. PIC FAMILIES

12

1.2.3

Packages

PICmicro devices are available in diferent packages. See figure 1.4 and 1.5 PDIP (Plastic Dual In-Line) is the most common package used in hand-made circuits. Can be used on a breadbord, with a socket o soldered in place. Available from 8 to 64 pin. CERDIP JW (Ceramic Dual In-Line) is a ceramic package with a quartz window used for EPROM devices. It has the same pinout (size and spacing) of the PDIP package. PLCC (Plastic Leaded Chip Carrer) is a square plastic package with smaller and narrower pin than DIP. Can be soldered on a printed board or used with a suitable socket. Available from 32 to 84 pins. CERQUAD (Ceramic Chip Carrier), same as PLCC but in a ceramic windowed package. SOIC, SSOP, QFP, TQFP, TSSOP Are different kind of surface mount packages. These removes the necessity of drilling holes through the printed circuit board, but can be soldered only with special tools, and can’t be used with sockets.

1.2.4

How to choose the right MCU for your needs

Microchip’s RISC-based PICmicro MCUs are designed for applications requiring high performance and low cost. The PICmicro MCU portfolio is comprised of more than 140 products and features a variety of memory configurations, low voltage and power, small footprint and ease-of-use. There is a great deal of “smarts” packed into a tiny space in our minimal footprint MCUs. As your designs grow in complexity, the code you write can be easily transitioned to larger Microchip MCUs with more peripheral resources. A seamless product migration path between PICmicro MCU families provides for complete upward compatibility in embedded control designs. To choose your MCU write down an outline of your project and see what are your I/O needs. Then grab the latest Product Line Card from the microchip web site and find what’s the most suitable. Because for a single unit price is not a factor of choice, my suggestions are: • if you need a compact device for simple tasks, choose the best PIC12C (PIC12C672 as 2002); • if you need a generic middle-range device go for the universal PIC16F84A, or aim at the PIC16F876A / PIC16F877A for plenty of memory and all sort of peripherals; • if you have specific requirements you can look at PIC16C745 / 765 for USB, PIC16C92x for LCD module, PIC16C77x for 12-bit ADC etc.; • if you are looking for speed and features with no compromises, pick one from the PIC18Fxxx family;

1.2. PIC FAMILIES

CERAMIC DUAL IN-LINE CERDIP

PLASTIC DUAL IN-LINE PDIP

PLASTIC LEADED CHIP CARRIER PLCC

18-LEAD CERDIP “JW” 28-LEAD PDIP “P” OR “PI” 14-LEAD PDIP “P” OR “PD” 28-LEAD SKINNY PDIP “SP” OR “PJ” 18-LEAD PDIP “P”

8-LEAD PDIP “P” OR “PA”

32-LEAD PLCC “L”

20-LEAD CERDIP “JW”

44-LEAD PLCC “L” OR “W”

28-LEAD CERDIP “JW” 20-LEAD PDIP “P” 40-LEAD PDIP “P” OR “PL”

68-LEAD PLCC “L” OR “LS”

Figura 1.4: Packaging of PICmicro MCUs
24-LEAD PDIP “P” OR “PG”

40-LEAD CERDIP “JW”

PLASTIC QUAD FLATPACK “QFP”

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

68-LEAD CERQUAD “CL”

84-LEAD CERQUAD “CL”

13

1.2. PIC FAMILIES

PLASTIC SMALL OUTLINE “SOIC”

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

8-LEAD SOIC (.150”) “SN” OR “OA” 20-LEAD SSOP “SS” 44-LEAD TQFP “PT” 28-LEAD SSOP “SS”

16-LEAD SOIC (.150”) “SL”

8-LEAD SIDE BRAZED “JW”

16-LEAD QSOP 18-LEAD SOIC “SO” 8-LEAD MSOP “MS” 20-LEAD SOIC “SO” 8-LEAD MSOP “UA” 80-LEAD TQFP’ “PT” 28-LEAD SIDE BRAZED (.300”) “JW” 64-LEAD TQFP “PT” 20-LEAD SIDE BRAZED “JW” 14-LEAD SIDE BRAZED “JW”

8-LEAD SOIC (.208”) “SM”

14-LEAD SOIC (.150”) “SL” OR “OD”

28-LEAD SOIC “SO” OR “OI”

PLASTIC THIN SHRINK SMALL OUTLINE “TSOP” CHIP SCALE PACKAGES
8-LEAD DFN “MF”

SMALL OUTLINE TRANSISTOR

8-LEAD TSSOP (4.4MM) “ST”

6-LEAD SOT-23 “CH” or “OT”

3-LEAD TRANSISTOR “TO” OR “ZB”

5-LEAD SOT-23 “OT” OR “CT”

3-LEAD SC-89 28-LEAD QFN “ML”

Figura 1.5: Packaging of PICmicro MCUs (continued)
3-LEAD SOT-23 “TT” OR “CB” SOT-143 “RC” 44-LEAD QFN “ML”

14-LEAD TSSOP (4.4MM) “ST” (PICmicro MCU) (4.4MM) “ST14” (MEMORY)

5-LEAD SC-70

3-LEAD SC-70

20-LEAD TSSOP (4.4MM) “ST”

14

1.3. CORE FEATURES

15

1.3

Core Features

The core pertains to the basic features that are required to make the device operate. These include: • Oscillator • Reset Logic • CPU (Central Processing Unit) and ALU (Arithmetic Logical Unit) • Memory • Configuration bits • Watchdog timer • Interrupts

1.3.1

CPU (Central Processing Unit)

The Central Processing Unit (CPU) is responsible for using the information in the program memory (instructions) to control the operation of the device. It is responsible for fetching the correct instruction for execution, decoding that instruction and then executing that instruction. Many of these instructions operate on data memory. The CPU controls the program memory address bus, the data memory address bus and accesses to the stack.

1.3.2

ALU (Arithmetic Logical Unit)

To operate on data memory, the Arithmetic Logical Unit (ALU) is required. In addition to performing arithmetical and logical operations, the ALU controls the state of the status bits, which are found in the STATUS register. The result of some instructions force status bits to a value depending on the state of the result. PICmicro devices contain an 8-bit ALU and an 8-bit working register (WREG). The ALU is a general purpose arithmetic and logical unit. It performs arithmetic and boolean functions between the data in the working register and any register file. The WREG register is directly addressable and in the SFR memory map. The ALU is 8-bits wide and is capable of addition, subtraction, multiplication, shift and logical operations. Unless otherwise mentioned, arithmetic operations are two’s 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.

1.3. CORE FEATURES

16

8-bit literal (from instruction word)

Register File

8 W Register 8

8-bit register value 8 (from direct or indirect address of instruction)

8

ALU
8 d bit, or from instruction d = '0' or Literal Instructions d = '1'

Special Function Registers (SFR’s) and General Purpose RAM (GPR)

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

1.3. CORE FEATURES

17

increase allows the device to be used in applications previously reserved for Digital Signal Processors. Example 1.7 shows the sequence to do an 8 x 8 unsigned multiply. Only one instruction is required when one argument of the multiply is already loaded in the WREG register. Example 1.8 shows the sequence to do an 8 x 8 signed multiply. To account for the sign bits of the arguments, each argument’s most significant bit (MSb) is tested and the appropriate subtractions are done.
MOVFF 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

1.3. CORE FEATURES

18

Q1 Tosc

Q2

Q3

Q4

Q1

Q2

Q3

Q4

Q1

Q2

Q3

Q4

TCY1

TCY2

TCY3

Figura 1.9: Internal instruction clock (TCY)

Using a crystal ensures the maximum stability and precision in clock frequency, therefore in istruction timing. You must use a crystal to have reliable serial comunications. The external RC is a cost-effective solution when you don’t need such precision and can tolerate some shift in timings. The internal RC is available on some low pin-count devices as the PIC12 series, to save pins for I/O functions and board space. Such devices need no external components to work. Some devices can also use Timer1 Oscillator as a low frequency low power clock source during sleep status, or multiply the clock by 4 with a Phase Lock Loop (PLL), making the internal instruction clock (TCY) equal to the external clock. Crystal Oscillator The PICmicros internal oscillator circuit is a parallel oscillator circuit, which requires that a parallel resonant crystal be selected. The load capacitance is usually specified in the 20 pF to 32 pF range. The crystal will oscillate closest to the desired frequency with capacitance in this range. Clock mode is primarily chosen by using the FOSC parameter specification (parameter 1A) in the device’s data sheet, based on frequency. Clock modes are simply gain selections, lower gain for lower frequencies, higher gain for higher frequencies. It is possible to select a higher or lower gain, if desired, based on the specific needs of the oscillator circuit. The OSC2 signal should be a nice clean sine wave that easily spans the input minimum and maximum of the clock input pin (4V to 5V peak to peak for a 5V VDD is usually good). An easy way to set this is to again test the circuit at the minimum temperature and maximum VDD that the design will be expected to perform in, then look at the output. This should be the maximum amplitude of the clock output. If there is clipping or the sine wave is squashing near VDD and VSS at the top and bottom, and increasing load capacitors will risk too much current through the crystal or push the value too far from the manufacturer’s load specification, then add a trimpot between the output pin and C2, and adjust it until the sine wave is clean. Try to get a

1.3. CORE FEATURES

19

combination where Rs is around 10k or less, and load capacitance is not too far from the 20 pF or 32 pF manufacturer specification. Remember that a scope probe adds its own capacitance to the circuit, so this may have to be accounted for in your design, i.e. if the circuit worked best with a C2 of 20 pF and scope probe was 10 pF, a 30 pF capacitor may actually be called for. The output signal should not be clipping or squashed. Overdriving the crystal can also lead to the circuit jumping to a higher harmonic level or even crystal damage. Application Note AN588 is an excellent reference if you would like to know more about crystal operation and their ordering information.You may also check Fact Sheet 00838a. A typical oscillator circuit is made by a 4MHz crystal and two 22 pF capacitors.

OSC1

C1
XTAL OSC2

To internal logic

(3)

RF (2)

SLEEP

Rs (1) C2
To internal logic (3) PIC16CXXX

Note 1: A series resistor, RS, may be required for AT strip cut crystals. 2: The feedback resistor, RF, is typically in the range of 2 to 10 MΩ. 3: Depending on the device, the buffer to the internal logic may be either before or after the oscillator inverter.

Figura 1.10: Typical crystal oscillator configuration

External RC Oscillator For timing insensitive applications, the RC and RCIO device options offer additional cost savings. The RC oscillator frequency is a function of the: • Supply voltage • External resistor (REXT) values • External capacitor (CEXT) values • Operating temperature In addition to this, the oscillator frequency will vary from unit to unit due to normal process parameter variation. The user also needs to take into account variation due to tolerance of external REXT and CEXT components used. Figure 1.11 shows how the

1.3. CORE FEATURES

20

RC combination is connected. For REXT values below 2.2 kΩ, oscillator operation may become unstable, or stop completely. For very high REXT values (e.g. 1 MΩ), the oscillator becomes sensitive to noise, humidity and leakage. Thus, we recommend keeping REXT between 3 kΩ and 100 kΩ.

V DD REXT OSC1 CEXT VSS Fosc/4 (1) Fosc Internal clock PIC16CXXX

Note 1: This output may also be able to be configured as a general purpose I/O pin.

Figura 1.11: Typical RC oscillator configuration

Although the oscillator will operate with no external capacitor (CEXT = 0 pF), we recommend using values above 20 pF for noise and stability reasons. With no or a small external capacitance, the oscillation frequency can vary dramatically. See characterization data for the variation of oscillator frequency due to VDD for given REXT/CEXT values, as well as frequency variation due to operating temperature for given REXT, CEXT and VDD values. The oscillator frequency, divided by 4, is available on the OSC2/CLKO pin, and can be used for test purposes or to synchronize other logic. On some devices the OSC2/CLKO pin can be configured as generic I/O pin. Internal 4 MHz RC Oscillator The internal RC oscillator (not on all devices) provides a fixed 4 MHz (nominal) system clock at VDD = 5V and 25◦ C. The value in the OSCCAL register is used to tune the frequency of the internal RC oscillator. The calibration value that Microchip programs into the device will “trim” the internal oscillator to remove process variation from the oscillator frequency. Upon a device reset, the OSCCAL register is forced to the midpoint value. A calibration instruction is programmed into the last address of the implemented program memory. This instruction contains the calibration value for the internal RC oscillator. This value is programmed as a RETLW XX instruction where XX is the calibration value. In order to retrieve the calibration value, issue a CALL YY instruction where YY is the last location in the device’s user accessible program memory. The calibration value

1.3. CORE FEATURES

21

C EXT = 300 pF, T = 25°C 1000 900 800 700 Fosc (kHz) 600 500 400 300 200 100 0 2.5 3.0 3.5 4.0 VDD (Volts) 4.5 5.0 5.5

R = 3.3k

R = 5k

R = 10k

R = 100k

Figura 1.12: Example RC Oscillator Frequency vs. VDD

is now loaded in the W register. The program should then perform a MOVWF OSCCAL instruction to load the value into the internal RC oscillator calibration register. The internal RC oscillator can be configured to provide a clock out signal on the CLKOUT pin. When the calibration value of the internal RC oscillator is accidently erased, the clock out feature allows the user to determine what the calibration value should be. This is achieved by writing a program which modifies (increments/decrements) the value of the OSCCAL register. When the CLKOUT pin is at 4 MHz (± 1.5%) at 5V and 25◦ C, the OSCCAL register has the correct calibration value. This value then needs to be written to a port or shifted out serially, so that the value can be written down and programmed into the calibration location.

1.3.4

Reset logic

The reset logic is used to place the device into a known state. Devices differentiate between various kinds of reset: • Power-on Reset (POR) • MCLR Reset • WDT Reset (normal operation) • Programmable Brown-out Reset (BOR) • RESET Instruction

1.3. CORE FEATURES

22

Average CEXT
22 pF

R EXT
5k 10k 100k

Fosc @ 5V, 25°C
4.12 MHz 2.35 MHz 268 kHz 1.80 MHz 1.27 MHz 688 kHz 77.2 kHz 707 kHz 501 kHz 269 kHz 28.3 kHz ± 1.4% ± 1.4% ± 1.1% ± 1.0% ± 1.0% ± 1.2% ± 1.0% ± 1.4% ± 1.2% ± 1.6% ± 1.1%

100 pF

3.3k 5k 10k 100k

300 pF

3.3k 5k 10k 100k

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

1.3. CORE FEATURES

23

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

1.3. CORE FEATURES

24

The Program Counter (PC) specifies the address of the instruction to fetch for execution. Mid-Range MCU devices have a 13-bit program counter capable of addressing an 8K x 14 program memory space. The width of the program memory bus (instruction word) is 14-bits. Since all instructions are a single word, a device with an 8K x 14 program memory has space for 8K of instructions. This makes it much easier to determine if a device has sufficient program memory for a desired application.

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

CALL, RETURN RETFIE, RETLW

Stack Level 1

Stack Level 8 Reset Vector

0000h

2K 4K 6K 8K

Interrupt Vector On-chip Program Memory (Page 0) On-chip Program Memory (Page 1) On-chip Program Memory (Page 2) On-chip Program Memory (Page 3)

0004h 0005h 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

1.3. CORE FEATURES

25

map as well as the 8 level deep hardware stack. Depending on the device, only a portion of this memory may be implemented. To jump between the program memory pages, the high bits of the Program Counter (PC) must be modified. This is done by writing the desired value into a SFR called PCLATH (Program Counter Latch High). If sequential instructions are executed, the program counter will cross the page boundaries without any user intervention. For devices that have less than 8K words, accessing a location above the physically implemented address will cause a wraparound (that is, in a 4K-word device accessing 17FFh actually addresses 7FFh). 2K-word devices (or less) do not require paging.
ORG 0x500 BSF PCLATH, 3 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),

1.3. CORE FEATURES

26

PCLATU

PCLATH

PC 23 21

PCU 20 16 15

PCH 8 7

PCL 0

Reserved. Maintain these bits cleared.

Figura 1.16: PIC18x PC structure

the 32nd PUSH over-writes the value from the last push (the 31st) and sets the STKFUL bit while the STKPTR remains at 11111b. The 33rd PUSH overwrites the 32nd PUSH (and so on) while STKPTR remains 11111b. When the stack overflow enable bit is enabled a device reset will occur. Data memory Data memory is made up of the Special Function Registers (SFR) area and the General Purpose Registers (GPR) area. The SFRs are used for control and status of the 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

1.3. CORE FEATURES

27

locations in the Access Bank for your own variables, but using that can compromise portability to future devices. General Purpose Registers (GPR) are not initialized by a Power-on Reset and are unchanged on all other resets. The register file can be accessed either directly, or indirectly, using the File Select Register (FSR). Some devices have areas that are shared across the data memory banks, so a read/write to that area will appear as the same location (value), regardless of the current bank. We refer to this area as the Common RAM.

1.3.6

Device configuration bits

The device configuration bits allow each user to customize certain aspects of the device to the needs of the application. When the device powers up, the state of these bits determines the modes that the device uses. To know what features are supported by your specific device, please see it’s datasheet. Microchip’s assembler, MPASM, has a nice feature (directives) that allows you to 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 CLRWDT and SLEEP instructions clear the WDT counter and the WDT postscaler which prevents it from timing out and generating a device reset. The CLRWDT instruction will force the count value of the WDT counter to ’0’.

1.3. CORE FEATURES

28

LIST p = p18C452 #INCLUDE <P18C452.INC> #INCLUDE <MY_STD.MAC> #INCLUDE <APP.MAC>

; List Directive, ; Microchip Device Header File ; File which includes my standard macros ; File which includes macros specific ; to this application

; Specify Device Configuration Bits for ; Program Configuration Registers 0 through 6 __CONFIG __CONFIG __CONFIG __CONFIG __CONFIG __CONFIG _CONFIG0, _CONFIG1, _CONFIG2, _CONFIG3, _CONFIG5, _CONFIG6, 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

org 0x00 RESET_ADDR : end

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

1.3.8

Low power mode (Sleep)

The SLEEP function halts controller activity and reduces current consumption to a 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. The first event will reset the device upon wake-up. However, the latter two events will wake the device and then resume program execution.

1.3. CORE FEATURES

29

For the device to wake-up through an interrupt event, the corresponding interrupt enable bit must be set (enabled). Wake-up is regardless of the state of the GIE bit. If the GIE bit is clear (disabled), the device continues execution at the instruction after the SLEEP instruction. If the GIE bit is set (enabled), the device executes the instruction after the SLEEP instruction and then branches to the interrupt address. This way, interrupt sources can wake the controller from sleep without actually causing an interrupt. During sleep, some of the peripherals works, some works partially, some not. See the reference manual for your particolar application.

1.3.9

Table Read/Write

Enhanced devices have two memory spaces. The program memory space and the data memory space. The program memory space is 16 bits wide, while the data memory space is 8 bits wide. Table Reads and Table Writes have been provided to move data between these two memory spaces through an 8-bit register (TABLAT). For more details see the 18F family datasheet, or AN556 (Implementing a Table Read).

1.3.10

Interrupts

Interrupts can come from many sources. These sources currently include: • External interrupt from the INT, INT1, and INT2 pins • Change on RB7:RB4 pins • Timer overflow • Interfaces (USART, SSP, PSP, CAN) • Peripherals (A/D, CCP ecc...) When a valid interrupt occurs, program execution vectors to one of these interrupt vector addresses and the corresponding Global Interrupt Enable bit (GIE, GIEH, or GIEL) is automatically cleared. In the interrupt service routine, the source(s) of the interrupt can be determined by testing the interrupt flag bits. The interrupt flag bit(s) must be cleared before re-enabling interrupts to avoid infinite interrupt requests. Most flag bits are required to be cleared by the application software. There are some flag bits that are automatically cleared by the hardware. When an interrupt condition is met, that individual interrupt flag bit will be set regardless of the status of its corresponding mask bit. The “return from interrupt“ instruction, RETFIE, can be used to mark the end of the interrupt service routine. When this instruction is executed, the stack is “POPed” and the GIE bit is set (to re-enable interrupts). Generally devices have a minimum of four registers associated with interrupts. The
INTCON register contains the Global Interrupt Enable bit, GIE, as well as the Peripheral

1.4. PERIPHERALS

30

Interrupt Enable bit, PEIE, the PIE / PIR register pair that enables the peripheral 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 • Serial ports and protocols (SSP, MSSP, USART, I2 C, CAN)

1.4. PERIPHERALS

31

ORG 0x08

; high priority ISR

; Save status for High Priority Interrupts PUSH_REG_H MOVWF WREG_TEMP_HIGH MOVFF BSR, BSR_TEMP_HIGH MOVFF STATUS, STATUS_TEMP_HIGH ; ; High Priority Interrupt Service Routine (ISR) Code goes here ; ; Restore status after servicing interrupt POP_REG_H MOVFF BSR_TEMP_HIGH, BSR MOVF WREG_TEMP_HIGH, W MOVFF STATUS_TEMP_HIGH, STATUS RETFIE 0x00 ORG 0x18 ; Low Priority ISR

; Save status for High Priority Interrupts PUSH_REG_L MOVWF WREG_TEMP_LOW MOVFF BSR, BSR_TEMP_LOW MOVFF STATUS, STATUS_TEMP_LOW ; ; Low Priority Interrupt Service Routine (ISR) code goes here ; ; Restore status after servicing interrupt POP_REG_L MOVFF BSR_TEMP_LOW, BSR MOVF WREG_TEMP_LOW MOVFF STATUS_TEMP_LOW, STATUS

RETFIE 0x00

Figura 1.18: Example: Interrupt Service Routine Template

1.4. PERIPHERALS

32

RIVEDERE MOVLW RCON_VALUE MOVWF RCON MOVLW IPR1_VALUE ; RCON_VALUE = 1???????b

; ; ; ;

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 MOVLW PIE1_VALUE MOVWF PIE1 CLRF INTCON3 CLRF INTCON2 MOVLW OxC0 MOVWF INTCON ; Clear all flag bits ; Enable desired peripheral interrupts ; by setting their bit position.

; Enable high and low global interrupts.

Figura 1.19: Example: Interrupt Initialization

• Voltage References • Comparators • A/D converters • Parallel Slave Port • USB

1.4.1

Generic I/O

General purpose I/O pins can be considered the simplest of peripherals. They allow the PICmicro to monitor and control other devices. To add flexibility and functionality to a device, some pins are multiplexed with alternate functions. These functions depend on which peripheral features are on the device. In general, when a peripheral is functioning, that pin may not be used as a general purpose I/O pin. For most ports, the I/O pin’s direction (input or output) is controlled by the data direction register, called the TRIS register. TRISx<y> controls the direction of PORTx<y>. A ‘1’ in the TRIS bit corresponds to that pin being an input, while a ‘0’ corresponds to that pin being an output. An easy way to remember is that a ‘1’ looks like an I (input) and a ‘0’ looks like an O (output).

1.4. PERIPHERALS

33

When enabling peripheral functions, care should be taken in defining TRIS bits for each port pin. Some peripherals override the TRIS bit to make a pin an output, while other peripherals override the TRIS bit to make a pin an input, and other peripherals may not override the TRIS bits (requires that TRIS bits are configured for proper peripheral operation). The user should refer to the corresponding peripheral section in the device datasheet for the correct TRIS bit settings. A read from the TRIS register bits will always yield the value contained in the TRIS latch whether or not a peripheral is overriding the setting. The PORT register7 is the latch for the data to be output. When the PORT is read, the device reads the levels present on the I/O pins (not the latch). This means that care should be taken with read-modify-write commands on the ports8 and changing the direction of a pin from an input to an output. Figure 1.20 shows a typical I/O port. This does not take into account peripheral functions that may be multiplexed onto the I/O pin. Reading the PORT register reads the status of the pins whereas writing to it will write to the port latch. All write operations (such as BSF and BCF instructions) are read-modify-write operations. Therefore a write to a port implies that the port pins are read, this value is modified, and then written to the port data latch. PORTA
PORTA is a 5-7 bit latch. The corresponding data direction register is TRISA, the data output latch is PORTA (LATA), and the pins are PORTA. Except for RA4, all PORTA pins have TTL input buffers and full CMOS output drivers. All pins are configured as inputs on a reset.

The RA4 pin is a Schmitt Trigger input and an open drain output. All other RA port pins have TTL input levels and full CMOS output drivers. All pins have data direction bits (TRIS registers) which can configure these pins as output or input. Setting a TRISA register bit puts the corresponding output driver in a hi-impedance mode. Clearing a bit in the TRISA register puts the contents of the output latch on the selected pin(s). On some devices PORTA pins can be multiplexed with the A/D converters. PORTB PORTB is an 8-bit wide bi-directional port. The corresponding data direction register is TRISB, the data output latch is PORTB (LATB), and the pins are PORTB. All pins have TTL inputs. Setting a bit in the TRISB register puts the corresponding output driver in a high-impedance input mode. Clearing a bit in the TRISB register puts the contents of the output latch on the selected pin(s). All pins are configured as inputs on a reset. Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-ups. This is performed by clearing bit RBPU. The weak pull-up is automatiin 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 7

1.4. PERIPHERALS

34

Data bus WR PORT

D

Q

VDD
CK Q

P

Data Latch I/O pin
D Q Q

N VSS

WR TRIS

CK

TRIS Latch TTL or Schmitt Trigger
Q D EN

RD TRIS

RD PORT

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

Figura 1.20: Generic I/O port

cally turned off when the port pin is configured as an output. The pull-ups are disabled on a Power-on Reset. Four of PORTB’s pins, RB7:RB4, have an interrupt on change feature. Only pins configured as inputs can cause this interrupt to occur (i.e. any RB7:RB4 pin configured as an output is excluded from the interrupt on change comparison). The input pins (of RB7:RB4) are compared with the old value latched on the last read of PORTB. The present inputs of RB7:RB4 and their previous values are XOR’ed together to detect a “mismatch” condition and set the RB Port change interrupt flag bit RBIF. When enabled, this flag will generate an interrupt that can wake the device from sleep. The user, in the interrupt service routine, can clear the interrupt in the following manner: • Any read or write of PORTB. This will end the mismatch condition.9 • Clear flag bit RBIF.
9 The MOVFF instruction will not end the mismatch condition if PORTB is used only as the destination register.

1.4. PERIPHERALS

35

CLRF STATUS CLRF PORTA BSF STATUS, RP0 MOVLW 0xCF MOVWF TRISA

; ; ; ; ; ; ;

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

1.4. PERIPHERALS

36

VDD RBPU(2) Data Latch D CK TRIS Latch D Q WR TRIS CK Q I/O pin(1) weak P pull-up

Data bus WR Port

TTL Input Buffer

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

1.4. PERIPHERALS

37

Data bus FOSC/4 0 1 1 T0CKI pin T0SE 3 PS2, PS1, PS0 T0CS PSA Set interrupt flag bit T0IF on overflow Programmable Prescaler 0 PSout Sync with Internal clocks (2 cycle delay) TMR0 PSout 8

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

1.4. PERIPHERALS

38

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

1.4. PERIPHERALS

39

CCPx Mode Capture Capture

CCPy Mode Capture Compare

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

Compare

Compare

PWM PWM PWM

PWM Capture Compare

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:

1.4. PERIPHERALS

40

• Driven High • Driven Low • Toggle output (Low to High or High to Low)11 • Not affected (remains unchanged) At the same time, interrupt flag bit CCPxIF is set. The user must configure the CCPx pin as an output by clearing the appropriate TRIS bit. Selecting the compare output mode, forces the state of the CCP pin to the state that is opposite of the match state. So if the Compare mode is selected to force the output pin low on match, then the output will be forced high until the match occurs (or the mode is changed). In the compare toggle mode, the CCPx pin output is initially forced to the low state. The special event trigger output of CCPx resets the TMR1 register pair without setting the Timer1 interrupt flag bit, TMR1IF. This allows the CCPRx register to effectively be a 16-bit programmable period register for Timer1. For some devices, the special trigger output of the CCP module resets the TMR1 register pair, and starts an A/D conversion (if the A/D module is enabled). PWM mode In Pulse Width Modulation (PWM) mode, the CCPx pin produces up to a 10-bit 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 1 2 3

2

3

Timer2 is cleared and new duty cycle value is loaded from the Duty Cycle latch into the Duty Cycle Slave register Timer2 value equals to value in Duty Cycle Latch register, CCP Pin is driven low Timer2 overflow, value from Duty Cycle Latch is loaded into Slave Register, CCP Pin driven high

Figura 1.25: PWM Output The PWM period is specified by writing to the PR2 register. The PWM period can be calculated using the following formula:
11

only in PIC18F family

1.4. PERIPHERALS

41

PWMperiod = [(PR2) + 1] ∗ 4 ∗ Tosc ∗ (TMR2 prescale value) The PWM duty cycle is specified by writing to the CCPRxL register and to the DCxB<1:0> bits. Up to 10-bit resolution is available: the CCPRxL contains the eight MSbs and CCPxCON<5:4> contains the two LSbs. This 10-bit value is represented by DCxB9:0. The following equation is used to calculate the PWM duty cycle: PWMdutycycle = (DCxB < 9 : 0 > bits value) ∗ Tosc ∗ (TMR2 prescale value) The DCxB9:0 bits can be written to at any time, but the duty cycle value is not latched into CCPRxH until after a match between PR2 and TMR2 occurs (which is the end of the current period). In PWM mode, CCPRxH is a read-only register. The maximum PWM resolution in bits for a given PWM frequency is 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 1 4 16 Minimum Resolution (Time) TSCLK TCY 4 * TCY

Tabella 1.3: Minimum Duty Cycle Bit Time The following steps configure the CCP module for PWM operation: 1. Establish the PWM period by writing to the PR2 register. 2. Establish the PWM duty cycle by writing to the DCxB9:DCxB0 bits. 3. Make the CCPx pin an output by clearing the appropriate TRIS bit. 4. Establish the TMR2 prescale value and enable Timer2 by writing to T2CON. 5. Configure the CCP module for PWM operation. For a thorough explanation see “Using the CCP modules”, AN594 from Microchip web site.

1.4. PERIPHERALS

42

1.4.4

Serial ports and protocols

SSP and MSSP The Synchronous Serial Port (SSP) module is a serial interface useful for communicating with other peripherals or microcontroller devices. These peripheral devices may be serial EEPROMs, shift registers, display drivers, A/D converters, etc. The SSP module can operate in one of two modes: • Serial Peripheral Interface (SPI) • Inter-Integrated Circuit (I2C) – Slave mode – I/O slope control, and Start and Stop bit detection to ease software 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)
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.
12

1.4. PERIPHERALS

43

• Synchronous - Master (half duplex) • Synchronous - Slave (half duplex) To set the Baud Rate Generator please see the tables on the Mid-range and 18F Family Datasheet. You must set the SPBRG register and the BRGH bit for your clock speed and desidered baud rate. In Asynchronous Mode, the USART uses standard nonreturn-to-zero (NRZ) format (one start bit, eight or nine data bits and one stop bit). The most common data format is 8 bits. The USART transmits and receives the LSb first. Parity is not supported by the hardware, but can be implemented in software. Asynchronous mode is selected by clearing the SYNC bit (TXSTA register). Steps to follow when setting up an Asynchronous Transmission: 1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is desired, set the BRGH bit. 2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit. 3. If interrupts are desired, then set the TXIE, GIE/GIEH and PEIE/GIEL bits. Specify the interrupt priority if required. 4. If 9-bit transmission is desired, then set the TX9 bit (can be used as address/data bit). 5. Enable the transmission by setting the TXEN bit, which will also set the TXIF bit. 6. If 9-bit transmission is selected, the ninth bit should be loaded in the TX9D bit. 7. Load data to the TXREG register (starts transmission). Steps to follow when setting up an Asynchronous Reception: 1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is desired, set bit BRGH. 2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit. 3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and PEIE/GIEL bits, appropriately. 4. If 9-bit reception is desired, then set the RX9 bit. 5. Enable the reception by setting the CREN bit. 6. The RCIF flag bit will be set when reception is complete. An interrupt will be generated depending on the configuration of the RCIE, RCIP, GIE/GIEH and PEIE/GIEL bits.

1.4. PERIPHERALS

44

7. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error occurred during reception. 8. Read the 8-bit received data by reading the RCREG register. 9. If any error occurred, clear the error by clearing the CREN bit. Steps to follow when setting up an Asynchronous Reception: 1. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is desired, set bit BRGH. 2. Enable the asynchronous serial port by clearing the SYNC bit and setting the SPEN bit. 3. If interrupts are desired, then set the RCIE bit and configure the RCIP, GIE/GIEH and PEIE/GIEL bits, appropriately. 4. If 9-bit reception is desired, then set the RX9 bit. 5. Enable the reception by setting the CREN bit. 6. The RCIF flag bit will be set when reception is complete. An interrupt will be 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.

1.4. PERIPHERALS

45

4. Set bit RX9 to enable 9-bit reception. 5. Set ADDEN to enable address detect. 6. Enable the reception by setting the CREN bit. 7. The RCIF flag bit will be set when reception is complete. An interrupt will be 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.

1.4. PERIPHERALS

46

Figura 1.26: I2C connections and data format

A CAN bus consists of two or more nodes. The number of nodes on the bus may be changed dynamically without disturbing the communication of other nodes. This allows easy connection and disconnection of bus nodes (e.g. for addition of system function, error recovery or bus monitoring). One of the most common and cheapest medium is a twisted wire pair. The bus lines are then called “CANH” and “CANL”, and may be connected directly to the nodes or via a connector. There’s no standard defined by CAN regarding the connector to be used. The twisted wire pair is terminated by terminating resistors at each end of the bus line. The maximum bus speed is 1 Mbit, which can be achieved with a bus length of up to 40 meters. At least 20 nodes may be connected without additional equipment. Due to the differential nature of transmission, CAN is insensitive to EMI because both bus lines are affected in the same way which leaves the differential signal unaffected. In the CAN protocol it is not bus nodes that are addressed, but the address 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.

1.4. PERIPHERALS

47

PIC18CXX8 with CAN

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

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

1.4. PERIPHERALS

48

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

1.4.6

Comparators

The comparator module contains two analog comparators. The inputs to the comparators are multiplexed with the I/O pins. The on-chip Voltage Reference (see the “Voltage Reference” section) can also be an input to the comparators. A single comparator is shown in Figure 1.28 along with the relationship between the analog input levels and the digital output. When the analog input at VIN+ is less than the analog input VIN-, the output of the comparator is a digital low level. When the analog input at VIN+ is greater than the analog input VIN-, the output of the comparator is a digital high level. The shaded areas of the output of the comparator (figure 1.28) represent the uncertainty due to input offsets and response time.

VIN + 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

1.4. PERIPHERALS

49

CM2:CM0 = 000 Comparators Reset (POR Default Value)
ANx0

CM2:CM0 = 111 Comparators Off
ANx0

A A

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

D D

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

ANx3

ANx3

ANx1 ANx2

A A

VIN VIN + C2 Off (Read as '0')

ANx1 ANx2

D D

VIN VIN + C2 Off (Read as '0')

CM2:CM0 = 010 Two Independent Comparators
ANx0

CM2:CM0 = 011 Three Inputs Multiplexed to Two Comparators
ANx0

A A

VIN VIN + C1 C1OUT

A A

VIN VIN + C1 C1OUT

ANx3

ANx3 C1OUT

ANx1 ANx2

A A

VIN VIN + C2 C2OUT

ANx1 ANx2 C2OUT

A A

VIN VIN + C2 C2OUT

CM2:CM0 = 100 Two Common Reference Comparators
ANx0

CM2:CM0 = 101 Two Common Reference Comparators with Outputs
ANx0

A A

VIN VIN + C1 C1OUT

A A

VIN VIN + C1 C1OUT

ANx3

ANx3 C1OUT

ANx1 ANx2

A D

VIN VIN + C2 C2OUT

ANx1 ANx2 C2OUT

A D

VIN VIN + C2 C2OUT

CM2:CM0 = 001 One Independent Comparator ANx1 ANx2 C1OUT A A VIN VIN + C1 C1OUT

CM2:CM0 = 110 Four Inputs Multiplexed to Two Comparators
ANx0

A A A A CIS = 0 CIS = 1 VINVIN+ C2 C2OUT CIS = 0 CIS = 1 VINVIN+ C1 C1OUT

ANx3 ANx1

ANx0

D D

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

ANx2

ANx3

From VREF Module A = Analog Input, port reads as zeros always. D = Digital Input. CIS (CMCON<3>) is the Comparator Input Switch.

Figura 1.29: Comparator Modes

1.4. PERIPHERALS

50

change that has occurred. The user, in the interrupt service routine, can clear the interrupt reading or writing to the CMCON register and clearing the CMIF flag bit.

1.4.7

Voltage References

This Voltage Reference module is typically used in conjunction with the Comparator module. The Voltage Reference is a 16-tap resistor ladder network that provides a selectable Voltage Reference. The resistor ladder is segmented to provide two ranges of VREF values and has a power-down function to conserve power when the reference is not being used. The VRCON register controls the operation of the reference.

16 Stages VREN 8R (1) R
(1)

R (1)

R (1)

R

(1)

8R (1)

VRR

VR3 VREF 16-1 Analog MUX VR0 (From VRCON<3:0>)

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 = VR3 : VR0 ∗ VDD 24

VDD VR3 : VR0 + ∗ VDD 4 32

1.4.8

A/D converters

The standard analog-to-digital (A/D) converter module has up to eight analog inputs, while the 10-bit Analog-to-Digital (A/D) Converter module can have up to sixteen analog inputs. The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level via successive approximation. This A/D conversion of the analog input signal results in a corresponding 8/10-bit digital number.

1.4. PERIPHERALS

51

The analog reference voltage is software selectable to either the device’s supply voltage (VDD) or the voltage level on the VREF pin. The A/D converter has a unique feature of being able to operate while the device is in SLEEP mode. The A/D module has three registers (five for the 10-bit module). These registers are: • A/D Result Register ADRES (ADRESH:ADRESL for the 10-bit) • A/D Control Register0 ADCON0 • A/D Control Register1 ADCON1 • A/D Control Register2 ADCON2 for the 10-bit module The ADCON0 register controls the operation of the A/D module. The ADCON1 register configures the functions of the port pins. The I/O pins can be configured as analog inputs (one I/O can also be a voltage reference) or as digital I/O. Note that pins multiplexed with Analog inputs are configured as analog inputs on a Power-on Reset. Reading port pins configured as analog inputs read a ‘0’. ADCON2 (if present) selects the A/D conversion clock source and the format of the A/D result. The block diagram of the 8-bit A/D module is shown in fig. 1.31.
CHS2:CHS0

111 AN7 110 AN6 101 AN5 100 VAIN (Input voltage) 011 010 8-bit A/D Converter 001 AN1 VDD (1) VREF (Reference voltage) 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. 000 or 010 or 100 001 or 011 or 101 000 AN0 AN2 AN4 AN3/VREF

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

When the A/D conversion is complete, the result is loaded into the ADRES register (ADRESH:ADRESL for the 10-bit), the GO/DONE bit (ADCON0<2>) is cleared, and A/D interrupt flag bit, ADIF, is set. After the A/D module has been configured as desired,

1.4. PERIPHERALS

52

the selected channel must be acquired before the conversion is started. The analog input channels must have their corresponding TRIS bits selected as an input. To determine acquisition time, see Subsection 21.4 “A/D Acquisition Requirements.” After this acquisition time has elapsed the A/D conversion can be started. The following steps should be followed for doing an A/D conversion: 1. Configure the A/D module • Configure analog pins, Voltage Reference, and digital I/O (ADCON1) • Select A/D input channel (ADCON0) • Select A/D conversion clock (ADCON0)13 • Turn on A/D module (ADCON0) 2. Configure A/D interrupt (if desired): • Clear the ADIF bit • Set the ADIE bit • Set/Clear the ADIP bit • Set the GIE/GIEH or PEIE/GIEL bit 3. Wait the required acquisition time. 4. Start conversion: • Set the GO/DONE bit (ADCON0) 5. Wait for the A/D conversion to complete, by either: • Polling for the GO/DONE bit to be cleared or the ADIF bit to be set, or • Waiting for the A/D interrupt 6. Read A/D Result register pair (ADRESH:ADRESL): clear the ADIF bit, if required. 7. For next conversion, go to step 1 or step 2 as required. The A/D conversion time per bit is defined as TAD. A minimum wait of 2TAD is required before next acquisition starts. Acquisition time is the time that the A/D module’s holding capacitor is connected to the external voltage level. When the GO bit is set, the conversion time of 12 TAD is started. The sum of these two times is the sampling time. There is a minimum acquisition time to ensure that the holding capacitor is charged to a level that will give the desired accuracy for the A/D conversion. To calculate the minimum acquisition time, see the device datasheet. Not all applications require a result with 10-bits of resolution, but may instead require a faster conversion time. The A/D module allows users to make the trade-off of conversion
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.
13

1.4. PERIPHERALS

53

speed to resolution. Regardless of the resolution required, the acquisition time is the same. To speed up the conversion, the clock source of the A/D module may be switched so that the TAD time violates the minimum specified time. Once the TAD time violates the minimum specified time, all the following A/D result bits are not valid.

CLRF ADCON1 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.

1.4. PERIPHERALS

54

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

1.5. IN-CIRCUIT SERIAL PROGRAMMING

55

APPLICATION PIC16C745/765

Host Controller/HUB

VUSB 1.5K DD+

200 nF

Note: The PIC16C745/765 requires an external resistor and capacitor to communicate with a host over USB.

Figura 1.33: USB external circuitry

www.usb.org. For a reference on the Microchip USB library see the PIC16C7xx Datasheet from Microchip web site. Related Microchip Application notes are: TB054 Gameport to USB Joystick Converter, TB055 PS/2 Mouse to USB, TB056 PS/2 Keyboard to USB, TB057 Gameport and PS/2 Mouse to USB Converter, TB058 Soft Detach and Change Configurations.

1.5

In-Circuit Serial Programming

18datasheet p221 If ICSP is implemented in the target application, some means of isolating RB7:RB6 from the rest of the circuit should be provided. The ISCP inputs have Schmitt Triggers while the RB7:RB6 inputs have TTL inputs. All Enhanced MCU devices can be In-Circuit Serial Programmed (ICSP) while in the end application circuit. This is simply done with two lines for clock and data, and three other lines for power, ground and the programming voltage. We will skip all the details on voltages, timing and procedures. If you need them you can read Application Note DS30277 In-Circuit Serial Programming Guide from the Microchip web site. The application circuit must be designed to allow all the programming signals to be directly connected to the PICmicro MCU. Figure 1.34 shows a typical circuit that is a starting point when designing with ICSP. The application must compensate for the following: Isolation of the MCLR/VPP pin: The resistor (R1) should be greater than 10kΩ to provide isolation between VDD and VPP. The application circuit must also be isolated from the +13V voltage provided by the programmer.

1.5. IN-CIRCUIT SERIAL PROGRAMMING

56

Loading of pins CLOCK and DATA: These pins must be isolated from the rest of the application circuit so as not to affect the signals during programming, accounting for CLOCK being an input on the MCU and for DATA being bi-directional. If the design permits, these pins should not be used by the application. Capacitance on each of the VDD, MCLR/VPP, CLOCK and DATA pins: The total capacitance on the programming pins affects the rise rates of these signals as they are driven out of the programmer. Keep it as low as possible, or use a driver board between the programmer and the application circuit. PICmicro oscillator When using RC or EC oscillator, the programmer must drive MCLR/VPP to the program mode entry voltage before the oscillator toggles four times. If the MCLR pin does not rise fast enough, while the device’s voltage is in the valid operating range, the internal Program Counter (PC) can increment, and the entire program will be shifted (offset) in the device program memory.

Application PCB PIC18CXXX MCLR/V PP

VDD /VPP V DD R1 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.
Depending on device. Devices in the 17C family have 2 special I/O ports capable do drive up to 60 mA.
1

2.2. SWITCH DE-BOUNCE

58

Figura 2.1: LED connection

Figura 2.2: Multiple 7-segments display wiring

2.2

Switch de-bounce

When a button is opened or closed, we perceive that it is a clean operation that really looks like a step function. In reality, the contacts of a switch bounce when they make contact, resulting in a jagged signal (see figure 2.3).

Figura 2.3: Swich bouncing signal

2.3. RELAIS AND SOLENOIDS

59

When this signal is passed to a PICmicro MCU, the microcontroller can recognize this as multiple button presses, which will cause the application software to act as if multiple, very fast button presses have occurred. Two common methods are used to debounce button inputs. The first is to poll the switch line at short intervals until the switch line stays at the same level for an extended period of time. A button is normally considered to be debounced if it does not change state for 20 ms or longer. The advantage of this method is that it can be done in an interrupt handler and the line can be scanned periodically with a flag set if the line is high and another flag in the line is low. This method of debouncing is good for debouncing keyboard inputs. If you don’t want to use the software approaches, you can use a capacitor to filter the bouncing signal and pass it into a Schmidt trigger input. This method is fairly reliable, but requires an available Schmidt trigger gate in your circuit. A Schmidt trigger input might be available in your PICmicro MCU, but check the data sheet to find out which states and peripheral hardware functions can take advantage of it.

Figura 2.4: Hardware debounce circuit

2.3

Relais and Solenoids

Some real-life devices that you might have to control by a microcontroller are 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

2.4. MOTORS

60

Figura 2.5: Relay control circuit

relay power supply and even the microcontroller. This diode must never be forgotten in a circuit that controls an electromagnetic device. The kick-back voltage is usually on the order of several hundred volts for a few nanoseconds. This voltage causes the diode to breakdown and allows current to flow, attenuating the induced voltage which can damage the PICmicro r MCU and other electronic devices in the application circuit. Rather than designing discrete circuits to carry out this function, is best to use 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.

2.4. MOTORS

61

Figura 2.6: H-bridge circuit

Figura 2.7: Using the 293D to control a motor

The 293D chip can control two motors (one on each side) connected to the buffer outputs (pins 3, 6, 11, and 14). Pins 2, 7, 10, and 15 are used to control the voltage level (the switches in the H-bridge diagram) of the buffer outputs. Pins 1 and 9 are used to control whether or not the buffers are enabled. The buffer controls can be PWM inputs, which make control of the motor speed very easy to implement. Vs is 5V used to power the logic in the chip and Vss is the power supplied to the motors (anywhere from 4.5 to 36 volts). A maximum of 500 mA can be supplied to the motors. Like the ULN2003A, the 293D contains integral shunt diodes. The 293D is limited to 1 amp total output and the 298 is limited to 3 amps. For these circuits to work best, a large heatsink is required. Another H-bridge circuit is the National2 LMD18200, rated 3A 55V, that features also 6A peak current, thermal warning flag and thermal shutdown, shorted load protection, brake input and current sense output.
2

http://www.national.com

2.5. RS232

62

Figura 2.8: Functional block diagram of LMD18200

2.5

RS232

It’s quite easy to connect a PICmicro to an RS232 serial port, the kind is usually found on PCs. A chip from the widespread family MAX220-249 takes care of translating the voltage levels from TTL to RS232 and vice-versa, including the pump-circuit to generate the various voltages from the 5v supply, and offering a good protection against electrostatic discharges. The most used chip is the MAX232, made by Maxim3 , offering level translation for 2 input channels (RS232 ⇒ TTL) and 2 output channels (TTL ⇒ RS232). Using the MAX232 is immediate: the only external components needed are five 1µF capacitors for the voltage doubler and the voltage inverter connected as in figure 2.9. To know about the software details for setting up a serial communication, see section 1.4.4 Addressable USART. An example circuit with the MAX232 is in Appendix B

3

www.maximic.com

2.5. RS232

63

+5V INPUT

C3

TOP VIEW
C5 C1+ 1 V+ 2 C1- 3 C2+ 4 C2- 5 V- 6 T2OUT 7 R2IN 8 16 VCC 15 GND 14 T1OUT C2 1 C1 C1+ 16 VCC +5V TO +10V VOLTAGE DOUBLER V+ 2 +10V 6 -10V C4

3 C14 C2+ +10V TO -10V 5 C2- VOLTAGE INVERTER +5V 400kΩ 11 T1IN

V-

MAX220 MAX232 MAX232A

13 R1IN 12 R1OUT 11 T1IN 10 T2IN 9 R2OUT TTL/CMOS INPUTS

T1OUT 14 RS-232 OUTPUTS T2OUT 7 R1IN 13 5kΩ RS-232 INPUTS

+5V 400kΩ 10 T2IN 12 R1OUT

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 TTL/CMOS OUTPUTS

C5 4.7 1.0 0.1

9 R2OUT

R2IN 8 5kΩ GND 15

Figura 2.9: Piedinatura e descrizione del MAX232

Capitolo 3

Programmazione
Nel capitolo 1 abbiamo mostrato l’architettura dei PICmicro e le periferiche che questi metono a disposizione. In questo capitolo mostreremo come scrivere un programma che ci permetta di sfruttare al meglio il chip per le nostre applicazioni. I PICmicro, date le piccole dimensioni del codice e il ridotto numero di istruzioni, 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 a u compilatore C.

3.1

Linguaggio Assembly

L’assembler ` il linguaggio pi` semplice da utilizzare per programmi di piccole dimensioni, e u 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 e 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 o aggiungere al registro RegistroA il registro RegistroB e memorizzare il risultato nel registro RegistroB dobbiamo eseguire:
Per semplicit` consideriamo impropriamente le istruzioni di Table Read e Table Write come operazioni a di controllo
1

3.2. LINGUAGGIO C

65

MOVF ADDWF

RegistroA, w RegistroB, f

: 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 aga giuntive per memorizzare il risultato dell’operazione. L’esecuzione di una operazione aritmetica influenza i bit di stato nel registro STATUS, in particolar modo i bit N, OV, Z, DC, C che indicano la presenza rispettivamente di un risultato Negativo (in complemento a due), un OVerflow, un risultato nullo (Zero), un riporto sul digit2 (Digit Carry), un riporto (Carry). Ad esempio se vogliamo verificare che il contenuto dei due registri RegistroA e RegistroB sia uguale possiamo effettuare una sottrazione e controllare il bit Z del registro di stato: MOVF 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 a vi permetter` di scrivere codice funzionante in brevissimo tempo. a A mio avviso il modo migliore per capire il linguaggio ` analizzare del codice gi` pronto, e a 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

3.3. APPLICATION MAESTRO

66

La programmazione in linguaggio C dei PICmicro verr` trattata in un documento a 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 e gestire autonomamente funzioni quali USART, CAN, I2C o polling degli ADC, tagliate su misura per la nostra applicazione.

Figura 3.1: La finestra principale di Application Maestro

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

3.4. FILTERLAB

67

3.4

FilterLab

FilterLab ` un’applicazione rilasciata come download gratuito dalla microchip che pere mette un facile design di filtri attivi. Le principali caratteristiche sono: • Design automatico di filtri attivi passa-basso Chebyshev, Bessel o Butterworth fino all’8vo ordine, da 0.1 Hz a 10 MHz, con ottimizzazione per conversioni A/D; • Implementazione del circuito con resistenze e condensatori standard; • Analisi del circuito risultante; • Generazione del modello Spice.

Figura 3.2: FilterLab in azione

Pur non essendo direttamente collegata alla programmazione dei PICmicro, l’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).

3.5. MPLAB IDE

68

3.5

MPLAB IDE

MPLAB IDE e’ un ambiente di sviluppo integrato fornito dalla Microchip. Esso consiste in un ambiente di lavoro con gestione di progetti che permette di invocare i vari tools quali assemblatore, linker, debugger, simulatore, compilatori di terze parti.

3.5.1

Programmare e compilare

Editor

.asm

.inc

Compilatore assembler

.cod

.lst

.err

.hex

PIC

Programmatore

Figura 3.3: Files generati dal compilatore

Nel creare il nostro programma possiamo scegliere se lavorare su un singolo file, nel qual caso ` sufficiente eseguire una quickbuild, o creare un progetto composto da pi` files e u su cui bisogna eseguire il linking. La scelta ovviamente dipender` dalla complessit` del a a progetto da affrontare.

3.6. PROGRAMMARE CON L’ICD 2

69

Utilizzando un singolo file, una volta steso il programma ` sufficiente scegliere Quice kbuild dal men` per assemblare il programma con MPASM Assembler. Se sono stati u installati tools di terze parti ` necessario accertarsi che sia selezionato il tool corretto nelle e impostazioni del progetto (Project → Set Language Tool Locations). Una volta corretti tutti gli eventuali errori, ` possibile passare alla fase successiva, il debugging. e Dovendo realizzare un programma di dimensioni maggiori sar` opportuno impostare a 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 confie gurazione. E’ consigliabile farlo all’interno del codice tramite le direttive di configurazione (vedi sezione 3.1.1) in modo da rendere le scelte immediatamente visibili e “trasportabili”, oppure tramite l’interfaccia grafica di MPLAB. Al termine della compilazione il codice generato ` immediatamente disponibile per la e successiva fase di debug, o per essere direttamente programmato sul PICmicro. Una guida all’utilizzo di MPLAB IDE ` fornita dalla microchip nel file “Application e Development With MPLAB IDE” (51410a).

3.5.2

Simulare

Una volta compilato il codice ` possibile verificarne il funzionamento senza utilizzare un e 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 a 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 → e MPLAB SIM. Nel men` compariranno i comandi per poterlo utilizzare. u

3.6

Programmare con l’ICD 2

L’ICD2 ` il nuovo programmatore-debugger a basso costo offerto dalla Microchip. Pur non e presentando le caratteristiche di verifica sulla programmazione necessarie in un ambiente di produzione3 offre all’utente tutte le funzionalit` necessarie per sviluppare applicazioni a su una vasta gamma di PICmicro. L’ICD2 pu` essere collegato al PC di controllo tramite porta seriale o USB. o 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 e cella di memoria venga letta diversamente se alimentata a livelli di tensione differenti.

3.7. DEBUG CON L’ICD2

70

• alimentare l’ICD2 tramite un alimentatore stabilizzato da 9V • collegare l’ICD2 al circuito target tramite un cavo con terminale RJ45 • selezionare nelle impostazioni all’interno di MPLAB l’opzione di alimentare il circuito target tramite l’ICD2 Se invece utilizziamo la porta USB dobbiamo: • collegare l’ICD2 al PC tramite un cavo USB A-B • collegare l’ICD2 al circuito target tramite un cavo con terminale RJ45 • alimentare il circuito target separatamente • selezionare nelle impostazioni all’interno di MPLAB l’opzione di NON alimentare il circuito target tramite l’ICD2 Per utilizzare l’ICD2 come programmatore ` sufficiente selezionarlo da Programmer → e Select Tool → MPLAB ICD2. Nel men` compariranno i comandi per poterlo utilizzare. u 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 prea ziose per individuare in breve tempo difetti nel software che altrimenti richiederebbero un impegno maggiore per essere scoperti. Utilizzando l’ICD2 come debugger abbiamo la possibilit` di: a • 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 funzioa nalit` di debug. In caso di risposta affermativa inserir` nel codice sorgente alcune funzioni a a

3.7. DEBUG CON L’ICD2

71

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 e non funzioner` scollegato dell’ICD2. a Per utilizzare il debugger ` altres` necessario disabilitare il timer di watchdog ed impoe ı stare correttamente l’indirizzo finale del programma. Se alcuni parametri di configurazione sono incompatibili con le esigenze del debugger MPLAB provveder` a mostrare un avviso. a

Capitolo 4

Esempi
Imparare tramite esempi ` sicuramente il modo pi` semplice per avvicinarsi ai microe u controllori. In questo capitolo presenteremo alcune applicazioni di difficolt` crescente a 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 o u primo basilare, il secondo un po pi` “furbo”. u Single-task Per iniziare vediamo il metodo pi` semplice: facciamo eseguire un numero fisso di istruzioni u 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’indie rizzo del vettore di reset, l’istruzione seguente sar` la prima ad essere eseguita dopo un a 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 e registro TRISB si trova nel Banco 0, quindi per accedervi ` necessario manipolare il valore e di STATUS, RP0 come spiegato nel capitolo 1.3.5. A questo punto abbiamo il nostro ciclo principale, illustrato nel diagramma di flusso in figura 4.2. A seconda dello stato attuale del LED decidiamo se accenderlo o spegnerlo, ed entriamo nella routine di ritardo.

4.1. LAMPEGGIO LED

73

list p=18f452, n=48, t=ON, st=OFF #include "p18f452.inc" ORG 0x80 Count RES 2 ORG 0x00000 ;bsf STATUS,RP0 movlw B’11111110’ movwf TRISB ;bcf STATUS,RP0 MainLoop btfsc goto bsf call goto SpegniLED bcf call goto ; Riserva due Bytes dall’indirizzo Count ; Reset vector ; Accedi al banco 1 (Mid-range) ; Imposta PORTB <7:1> come Input ; e PORTB<0> come Output ; Accedi al banco 0 (Mid-range)

PORTB,0 SpegniLED PORTB,0 Delay MainLoop PORTB,0 Delay MainLoop

; Se il LED e’ acceso ; Vai a SpegniLED ; Accendi il led

; Spegni il LED

;Subroutines Delay clrf clrf DelayLoop decfsz goto decfsz goto return END

Count Count+1

Count,1 DelayLoop Count+1,1 DelayLoop

; Decrementa Count, salta se zero ; Decrementa Count+1, salta se zero ; Ritorna al punto di chiamata

Figura 4.1: Lampeggio di un LED senza interrupt

4.1. LAMPEGGIO LED

74

Reset vector

DelayLoop

Impostazione porte I/O

Decrementa Count

No
Led acceso? Count = 0

No

Vai a SpegniLed

Decrementa Count+1

goto MainLoop

Accendi il LED

Spegni il LED

No
Count+1 = 0

Aspetta ritardo

Aspetta ritardo

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 e a 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 e secondi con un clock a 4 MHz. Se avessimo voluto una frequenza pi` vicina ad un secondo u avremmo potuto scegliere di caricare un valore iniziale diverso da zero ad ognuno dei due registri.
1

vedi la sezione 1.1

goto DelayLoop

skip if clear

4.1. LAMPEGGIO LED

75

A livello di curiosit` in figura 4.3 abbiamo riportato il codice esadecimale generato dal a nostro programma, ci` che verr` effettivamente programmato nel PIC. o a
: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 e sviluppato, ma ha un grosso difetto: tutta la potenza di calcolo della CPU ` impegnata a e 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 e di conteggio ad una periferica TIMER, che ci segnaler` la necessit` di aggiornare lo stato a a del LED tramite un interrupt. Vediamo come: Inizialmente, dopo le usuali direttive per il compilatore, troviamo subito una novit`: a ORG 0x00000 goto Start ;Reset Vector

Per capire il perch` di questa scelta dobbiano sapere come ` organizzata la memoria e e 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 e sia pi` lungo e quindi non entri nello spazio tra i due vettori. Per questo motivo inseriamo u solamente una chiamata al nostro codice. Le stesse considerazioni si applicano al vettore di interrupt ad alta priorit` che si trova a a dieci locazioni dal vettore a bassa priorit` 0x0018. a 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 a 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 e stata utilizzata per altri task. Mentre il processore ` libero il Timer0 decrementa con frequenza pari a 1/64 del clock e esterno e genera un interrupt ogni volta che raggiunge lo zero. A questo punto la routine di

4.1. LAMPEGGIO LED

76

list p=18f452, n=48, t=ON, st=OFF #include "p18f452.inc" ORG 0x00000 goto Start org goto Start movlw movwf movlw 0x00008 ISR ;Reset Vector

; Interrupt Vector Address ; goto Interrupt Service Routine

B’11111110’ TRISB B’10000011’

;Set-up timer ;Bit 7 1 Timer0 on ;Bit 6 0 16bit ;Bit 5 0 count Tcy ;Bit 3 0 Prescaler on ;Bit 2-0 011 1:16 prescaler ;Set-up interrupts ;Bit 7 1 Global enable ;Bit 6 1 Peripheral enable ;Bit 5 1 Timer0 interrupt enable

movwf movlw

T0CON B’11100000’

movwf MainLoop nop goto ISR

INTCON

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

; Se il LED e’ acceso ; Accendi il led ; Elimina il flag di Interrupt

; Spegni il LED ; Elimina il flag di Interrupt

Figura 4.4: Lampeggio di un LED con interrupt

4.2. GENERAZIONE PWM

77

0x0000 0x0001

goto Start

Reset vector

0x0008

goto ISR Start

Interrupt vector

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

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 u a a modalit` asincrona RS232 (capitolo 1.4.4) e il convertitore A/D (capitolo 1.4.8). a L’applicazione produce sul piedino RC1 un segnale PWM il cui Duty Cycle pu` essere o controllato tramite un byte in ingresso sulla porta seriale, oppure tramite il potenziome-

4.3. CONTROLLORE PER MOTORI STEPPER

78

tro presente sulla PICDEM2 collegato al piedino RA0. La modalit` di controllo viene a 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 a a a dall’assemblatore che sostituir` le occorrenze del nome simbolico con l’indirizzo di memoria a 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` a 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 a 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` signie a u ficativi derivanti dalla conversione determinano gli 8 bit pi` significativi del duty-cycle e u vengono trasmessi sulla porta seriale. Per semplicit` si ` deciso di non sfruttare l’intera a e risoluzione (10 bit) del modulo A/D e del modulo CCP. Similarmente quando viene generato un interrupt dall’unit` USART, se ` selezionata a e la modalit` “seriale”, il byte ricevuto determina gli 8 bit pi` significativi del duty-cycle. a u Per semplicit` e poich` non si presentava necessit` di farlo, sono state omesse le roua e a tine di salvataggio del contesto durante il servizio degli interrupt. In caso di programmi principali pi` complessi la gestione di un interrupt pu` modificare alcuni registri di stato u o ed influenzare il flusso principale del programma. In caso ci` sia possibile ` necessario o e 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 a C.

4.3. CONTROLLORE PER MOTORI STEPPER

79

;************************************************************ ; Produce un PWM il cui Duty Cycle puo’ essere controllato ; via il potenziometro su RA0 o tramite un byte trasmesso ; sulla porta seriale. ; Per scegliere la modalita’ premere S2 (RA4). ; Led acceso = controllo potenziometro ; Led spento = controllo seriale ; Il PWM sar` emesso su RC1. a ;************************************************************ list p=18f452, n=48, t=ON, st=OFF #include "p18f452.inc" ;************************************************************ ; variables TEMP equ 0x000

;************************************************************ ; reset and interrupt vectors org 0x00000 goto Start org 0x00008 goto ISR ; Reset Vector Address

; 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 bsf bsf bsf bsf bcf bsf bsf bsf 19h SPBRG TXSTA,TXEN TXSTA,BRGH RCSTA,SPEN RCSTA,CREN PIR1,RCIF PIE1,RCIE INTCON,PEIE INTCON,GIE ; 9600 baud @4MHz

; Enable transmit ; Select high baud rate ; Enable Serial Port ; Enable continuous reception ; ; ; ; Clear RCIF Interrupt Flag Set RCIE Interrupt Enable Enable peripheral interrupts Enable global interrupts

Figura 4.6: Generazione PWM (1/4)

4.3. CONTROLLORE PER MOTORI STEPPER

80

;Set up A/D module call call bsf InitializeAD SetupDelay ADCON0,GO ; configure A/D module ; delay for 15 instruction cycles ; 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 SwitchMode btfss goto bcf goto SetPot bsf Debounce btfss goto goto

PORTA,4 MLOOP

; Has S2 been pressed? (low when pressed.) ; No, check again

PORTB,RB0 SetPot PORTB,RB0 Debounce

; if was POT ; set to SER

PORTB,RB0

; if was SER ; set to pot

PORTA,4 Debounce MLOOP

; Has key been released? ; No, wait some more ; yes, wait for next key press

Figura 4.7: Generazione PWM (2/4)

4.3. CONTROLLORE PER MOTORI STEPPER

81

;************************************************************ ; Service A/D interrupt ISR ; Save context (WREG and STATUS) if required. ;A/D Interrupt ADInt btfss goto movf btfsc movwf movwf bcf call bsf goto PIR1,ADIF USARTInt ADRESH,W PORTB,RB0 CCPR2L TXREG PIR1,ADIF SetupDelay ADCON0,GO EndISR ; Did A/D cause interrupt? ; No, check other sources ; ; ; ; ; ; ; ; 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

;USART Interrupt USARTInt btfss PIR1,RCIF goto OtherInt movlw andwf btfss goto movf btfss movwf movwf goto RcvError bcf bsf ; Signal goto 06h RCSTA,W STATUS,Z RcvError RCREG,W PORTB,RB0 CCPR2L TXREG EndISR

; Did USART cause interrupt? ; No, some other interrupt ; ; ; ; ; ; ; ; ; Mask out unwanted bits Check for errors Was either error status bit set? Found error, flag it Get input data Skip if Pot mode Set PWM duty cycle Echo character back go to end of ISR, restore context, return

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)

4.3. CONTROLLORE PER MOTORI STEPPER

82

;************************************************************ ; InitializeAD - initializes and sets up the A/D hardware. ; Select AN0 to AN3 as analog inputs, RC clock, and read AN0. InitializeAD movlw B’00000100’ movwf ADCON1 movlw movwf bcf bsf 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 END B’11000001’ ADCON0 PIR1,ADIF PIE1,ADIE

; Make RA0,RA1,RA4 analog inputs

; Select RC osc, AN0 selected, ; A/D enabled ; Clear A/D interrupt flag ; Enable A/D interrupt

.3 TEMP TEMP, F SD

; Load Temp with decimal 3

; Delay loop

Figura 4.9: Generazione PWM (4/4)

Appendice A

Descrizione della PICDEM2 plus
La PICDEM2 plus ` una demo board realizzata dalla Microchip. Presenta a bordo vari e componenti per permettere la dimostrazione di gran parte delle periferiche presenti sui microcontrollori della serie 16 e 18. La scheda ha a bordo:1 • Display LCD 2 righe x 16 caratteri • Circuiteria per interfaccia seriale RS232 (MAX232A) • Sensore di temperatura TC742 con interfaccia I2 C • EEPROM seriale 24L256 da 256K x 8 • Cicalino piezoelettrico pilotato in PWM • 4 LED • 2 pulsanti + reset • Potenziometro La scheda permette la prototipazione rapida di gran parte dei PICmicro grazie agli zoccoli da 18, 28 e 40 PIN e al connettore per la programmazione in-circuit. Tutti i piedini di I/O sono disponibili sulle piazzole, e sono predisposti un oscillatore al quarzo da 4 MHz, un oscillatore RC da 2MHz e un quarzo per applicazioni di timing da 32.768 KHz. Nel caso in cui stiamo utilizzando la scheda con l’ICD2 collegato al PC tramite porta USB, dobbiamo alimentare la scheda tramite un alimentatore non regolato da 9V, tramite una batteria da 9V oppure con un alimentatore stabilizzato da 5V collegato ai ganci posti vicino all’area di prototipazione (figura A.1 particolare 2).
1 2

Per una descrizione pi` completa fare riferiento al documento Microchip 51275a u Per il datasheet del sensore cercare il documento Microchip DS21462

84

7 2 13 11 3 14 4 16 12 18 10

9

8 15

5

17 1

2 6

Figura A.1: PICDEM2 plus hardware

Se invece utilizziamo l’ICD2 tramite porta seriale, e quindi lo alimentiamo, possiamo fare in modo che fornisca anche l’alimentazione alla scheda modificando le impostazioni in MPLAB. Sulla scheda sono presenti tre jumpers. Il primo, siglato J6, permette di disabilitare i led posti sulla parte superiore della scheda e di utilizzare le porte relative come canali di I/O generali; il secondo, J7, abilita l’oscillatore RC presente sulla scheda; il terzo, J9, permette di scollegare il cicalino piezoelettrico. Nella tabella A.1 sono riportati i collegamenti presenti sulla scheda.
Pot R16 RA0 RA0 RA0 Temp Sensor N/A RC3/RC4 RC3/RC4

Device 18-pin 28-pin 40-pin

LEDs RB3:RB0

RS-232 N/A

S1 MCLR MCLR MCLR

S2 RA4 RA4 RA4

S3 RB0 RB0 RB0

LCD N/A

EEPROM Buzzer N/A N/A RC2 RC2

ICD RB6/RB7 RB6/RB7 RB6/RB7

Y1/Y2 Yes Yes Yes

RB3:RB0 RC6/RC7 RB3:RB0 RC6/RC7

RA3:RA1 RC3/RC4 RD3:RD0 RA3:RS1 RC3/RC4 RD3:RD0

Tabella A.1: PICDEM2 plus connections

Appendice B

Realizzazione di una demo-board
B.1 16F84

Per il funzionamento di un PICmicro sono sufficienti pochissimi componenti esterni. Per poter realizzare prototipi in poco tempo, abbiamo sviluppato una piccola scheda che raccoglie questi componenti, oltre ad un sempre utile regolatore di tensione e la predisposizione alla comunicazione seriale con standard RS-232.

B.1.1

Schema elettrico

Lo schema elettrico ` molto semplice. Connesso al connettore a vaschetta DB-9 (J1) e troviamo il MAX232 (IC2) con i suoi condensatori (C1-C5) come riportato in figura B.2. Seguitando troviamo il PICmicro (IC1) con collegato sui piedini 14-15 il quarzo (X1) ed i relativi condensatori1 C7 e C8.

B.1.2

Circuito stampato

Lo sbroglio del circuito stampato ` stato effettuato a mano in due versioni diverse: i e ringraziamenti per la versione B vanno all’ Ing. Valerio Senni. Poich` non ` possibile garantire l’accuratezza della scala di riproduzione, e’ necessario e e assicurarsi che la distanza tra i piedini del PIC sia pari a 2.54 mm, per una distanza totale tra il piedino 1 e il piedino 9 di 22.86 mm.

1

Il prototipo realizzato monta un quarzo da 4 MHz e due condensatori da

B.1. 16F84

86

C4 C7 C8 J1 IC2 C2 C1 C5 C3 C6
Figura B.1: Posizionamento dei componenti demo board A

X1

IC1

+5V INPUT

C3

TOP VIEW
C5 C1+ 1 V+ 2 C1- 3 C2+ 4 C2- 5 V- 6 T2OUT 7 R2IN 8 16 VCC 15 GND 14 T1OUT C2 1 C1 C1+ 16 VCC +5V TO +10V VOLTAGE DOUBLER V+ 2 +10V 6 -10V C4

3 C14 C2+ +10V TO -10V 5 C2- VOLTAGE INVERTER +5V 400kΩ 11 T1IN

V-

MAX220 MAX232 MAX232A

13 R1IN 12 R1OUT 11 T1IN 10 T2IN 9 R2OUT TTL/CMOS INPUTS

T1OUT 14 RS-232 OUTPUTS T2OUT 7 R1IN 13 5kΩ RS-232 INPUTS

+5V 400kΩ 10 T2IN 12 R1OUT

DIP/SO
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 TTL/CMOS OUTPUTS

DEVICE MAX220 MAX232 MAX232A

C5 4.7 1.0 0.1

9 R2OUT

R2IN 8 5kΩ GND 15

Figura B.2: Piedinatura e descrizione del MAX232

B.1. 16F84

87

Figura B.3: Circuito stampato demo board A

Figura B.4: Circuito stampato demo board B

Appendice C

Instruction sets
C.1 PIC16F84A e PIC16F87x

Il set di istruzioni dei PIC16F84a e PIC16F87x sono caratterizzati da un numero di istruzioni estremamente ridotto. Ci` avvantaggia il programmatore che pu` imparare il set o o 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 e il tipo dell’istruzione, ed uno o pi` operandi. Il set di istruzioni ` altamente ortogonale, e u 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 u calcolabile rispetto a processori pi` complessi. u Il significato dei simboli utilizzati nella descrizione del set di istruzioni ` riportato in e tabella C.4.

C.2

PIC18F45x

Il set di istruzioni del PIC18F45x aggiunge diversi miglioramenti a quello della famiglia PIC16F, pur mantenendo la stessa semplicit` ed ortogonalit`. a a Tutte le istruzioni tranne tre occupano una singola word (16 bit). Tentare di eseguire la seconda word di un istruzione non provoca danni, in quanto viene riconosciuta come

C.2. PIC18F45X

89

tale ed eseguita come NOP. Tutte le istruzioni single-word sono eseguite in un ciclo di clock, ad eccezione dei salti. Le operazioni sono suddivise in cinque categorie principali: • Operazioni orientate al byte • Operazioni orientate al bit • Operazioni letterali • Operazioni di controllo • Operazioni di trasferimento tra memoria programma e memoria dati (table read/write)

C.2. PIC18F45X

90

Mnemonic, Operands

14-Bit Opcode Description Cycles MSb BYTE-ORIENTED FILE REGISTER OPERATIONS LSb

Status Affected

Notes

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

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

C,DC,Z Z Z Z Z Z Z Z Z

1,2 1,2 2 1,2 1,2 1,2,3 1,2 1,2,3 1,2 1,2

C C C,DC,Z Z

1,2 1,2 1,2 1,2 1,2

BIT-ORIENTED FILE REGISTER OPERATIONS BCF BSF BTFSC BTFSS ADDLW ANDLW CALL CLRWDT GOTO IORLW MOVLW RETFIE RETLW RETURN SLEEP SUBLW XORLW f, b f, b f, b f, b k k k k k k k k k Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set 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 1 (2) 1 (2) 1 1 2 1 2 1 1 2 2 2 1 1 1 01 01 01 01 00bb 01bb 10bb 11bb bfff bfff bfff bfff ffff ffff ffff ffff C,DC,Z Z TO,PD Z 1,2 1,2 3 3

LITERAL AND CONTROL OPERATIONS 11 11 10 00 10 11 11 00 11 00 00 11 11 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

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 C.1: PIC16F84A instruction set

C.2. PIC18F45X

91

Mnemonic, Operands

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 MOVWF MULWF NEGF RLCF RLNCF RRCF RRNCF SETF SUBFWB SUBWF SUBWFB SWAPF TSTFSZ XORWF BCF BSF BTFSC BTFSS BTG 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 f, a f, a f, a f, d, a f, d, a f, d, a f, d, a f, a f, d, a f, d, a f, d, a f, d, a f, a f, d, a f, b, a f, b, a f, b, a f, b, 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 Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set Bit Toggle 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 1 1 1 1 1 1 1 1 1 1 1 1 1 (2 or 3) 1 1 1 1 (2 or 3) 1 (2 or 3) 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 0101 0101 0011 0110 0001 11da 10da 10da 011a 10da bbba bbba bbba bbba bbba 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 ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff

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 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 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, 2 1, 2

1, 2

ffff C, DC, Z, OV, N ffff C, DC, Z, OV, N ffff None ffff None ffff Z, N ffff ffff ffff ffff ffff

1, 2 4 1, 2

BIT-ORIENTED FILE REGISTER OPERATIONS
1001 1000 1011 1010 0111

None None None None None

1, 2 1, 2 3, 4 3, 4 1, 2

Note 1: When a PORT register is modified as a function of itself (e.g., MOVF PORTB, 1, 0), the value used will be that value present on the pins themselves. For example, if the data latch is ’1’ for a pin configured as input and is driven low by an external device, the data will be written back with a ’0’. 2: If this instruction is executed on the TMR0 register (and, where applicable, d = 1), the prescaler will be cleared if assigned. 3: If Program Counter (PC) is modified or a conditional test is true, the instruction requires two cycles. The second cycle is executed as a NOP. 4: Some instructions are 2-word instructions. The second word of these instructions will be executed as a NOP, unless the first word of the instruction retrieves the information embedded in these 16-bits. This ensures that all program memory locations have a valid instruction. 5: If the Table Write starts the write cycle to internal memory, the write will continue until terminated.

Tabella C.2: PIC18F45x instruction set

C.2. PIC18F45X

92

Mnemonic, Operands CONTROL OPERATIONS BC BN BNC BNN BNOV BNZ BOV BRA BZ CALL CLRWDT DAW GOTO NOP NOP POP PUSH RCALL RESET RETFIE RETLW RETURN SLEEP n n n n n n n n n n, s — — n — — — — n s k s —

16-Bit Instruction Word Description Cycles MSb LSb

Status Affected

Notes

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 Return with literal in WREG Return from Subroutine Go into Standby mode

1 (2) 1 (2) 1 (2) 1 (2) 1 (2) 2 1 (2) 1 (2) 1 (2) 2 1 1 2 1 1 1 1 2 1 2 2 2 1

1110 1110 1110 1110 1110 1110 1110 1101 1110 1110 1111 0000 0000 1110 1111 0000 1111 0000 0000 1101 0000 0000 0000 0000 0000

0010 0110 0011 0111 0101 0001 0100 0nnn 0000 110s kkkk 0000 0000 1111 kkkk 0000 xxxx 0000 0000 1nnn 0000 0000 1100 0000 0000

nnnn nnnn nnnn nnnn nnnn nnnn nnnn nnnn nnnn kkkk kkkk 0000 0000 kkkk kkkk 0000 xxxx 0000 0000 nnnn 1111 0001 kkkk 0001 0000

nnnn nnnn nnnn nnnn nnnn nnnn nnnn nnnn nnnn kkkk kkkk 0100 0111 kkkk kkkk 0000 xxxx 0110 0101 nnnn 1111 000s

None None None None None None None None None None TO, PD C None

None None None None None All GIE/GIEH, PEIE/GIEL kkkk None 001s None 0011 TO, PD Status Affected

4

Mnemonic, Operands LITERAL OPERATIONS ADDLW ANDLW IORLW LFSR MOVLB MOVLW MULLW RETLW SUBLW XORLW TBLRD* TBLRD*+ TBLRD*TBLRD+* TBLWT* TBLWT*+ TBLWT*TBLWT+* k k k f, k k k k k k k

16-Bit Instruction Word Description Cycles MSb LSb

Notes

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

1 1 1 2 1 1 1 2 1 1 2

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 None None None None C, DC, Z, OV, N Z, N None None None None None None None None

DATA MEMORY ↔ PROGRAM MEMORY OPERATIONS
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

2 (5)

Tabella C.3: PIC18F45x instruction set (continued)

C.2. PIC18F45X

93

Field f W b k x

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)

Tabella C.4: Istruction set conventions

Appendice D

Glossary
Absolute Section A section with a fixed (absolute) address which can not be changed by the linker. Access RAM (PIC18CXXX Devices Only) This is a region of data memory RAM that can be accessed regardless of the currently selected bank. This allows special function registers to be accessed by the instruction without changing the currently selected bank. Access RAM also contains some General Purpose Registers (GPRs). This is useful for the saving of required variables during context switching (such as during an interrupt). When used in reference to PIC18CXXX devices, Access RAM refers to special general purpose registers that allow access regardless of the setting of the bank select bit(BSR). Acquisition Time (TACQ) This is related to Analog-to-Digital (A/D) converters. This is the time that the PIC18CXXX A/D’s holding capacitor acquires the analog 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

95

half duplex synchronous communications port. When operating in the asynchronous mode, the USART can be interfaced to a PC’s serial port. Alphanumeric Alphanumeric characters include alpha characters and numbers: (a...z, A...Z, 1...9). Application A set of software and hardware developed by the user, usually designed to be a product controlled by a PICmicro microcontroller. Assemble What an assembler does. See assembler. Assembler A language tool that translates a user’s assembly source code (.asm) into machine code. MPASM is Microchip’s assembler. Assembly A programming language that is once removed from machine language. 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.

96

Breakpoint - Hardware An event whose execution will cause a halt. Breakpoint - Software An address where execution of the firmware will halt. Usually achieved by a special break opcode. Build A function that recompiles all the source files for an application. C A high level programming language that may be used to generate code for PICmicro MCUs, especially high-end device families. Calibration Memory A special function register or registers used to hold values for calibration of a PICmicro microcontroller on-board RC oscillator. CAN Controller Area Network. A peripheral interface targeting automotive and 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.

97

Configuration Bits Unique bits programmed to set PICmicro microcontroller modes of operation. A configuration bit may or may not be preprogrammed. These bits are set in the Options → Development Mode dialog for simulators or emulators and in the CONFIG MPASM directive for programmers. Configuration Word This is a non-volatile memory location that specifies the 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.

98

EEPROM Electrically Erasable Programmable Read Only Memory. A special type of PROM that can be erased electrically. Data is written or erased one byte at a time. EEPROM retains its contents even when power is turned off. Embedded System Special-purpose computer built into and integral to a device. It is used to control, monitor or assist an operation. All embedded systems are or include computers, the simplest being a single microprocessor (“chip”). A microprocessor may be designed so that ROM software (“firmware”) for a particular purpose can be added (e.g., a PC’s ROM BIOS). Emulation The process of executing software loaded into emulation memory as if the firmware resided on the microcontroller device under development. Emulation Memory Program memory contained within the emulator. Emulator Hardware that performs emulation. Emulator System The MPLAB ICE emulator system includes the pod, processor 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.

99

FOSC Frequency of the device oscillator. File Registers On-chip general purpose and special function registers. GIO General Input/Output. GPIO General Purpose Input/Output. GPR General Purpose Register (RAM). A portion of the data memory that can be used to store the program’s dynamic variables. Harvard Architecture In this architecture, the Program Memory and Data Memory buses are separated. This allows concurrent accesses to Data Memory and 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.

100

Identifier A function or variable name. Import Bring data into the MPLAB IDE from an outside source, such as from a hex file. Indirect Addressing When the Data Memory Address is not contained in the 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.

101

LIN Protocol Specification A low cost, short-distance, low speed network designed to transmit changes in switch settings and respond to switch changes. Used in many automotive subsystems. Link What a linker does. See Linker. Linker A language tool that combines object files and libraries to create executable code. Linking is performed by Microchip’s linker, MPLINK LINKER. Linker Script Files Linker script files are the command files of the MPLINK LINKER (.LKR). They define linker options and describe available memory on the target platform. Literal This is a constant value that is embedded in an instruction word. Listing File A listing file is an ASCII text file that shows the machine code generated for each C source statement, assembly instruction, MPASM Assembler directive, or macro encountered in a source file. Logic Probes Up to 14 logic probes connected to the emulator. The logic probes provide external trace inputs, trigger output signal, +5V, and a common ground. Long Word Instruction An instruction word that embeds all the required information (opcode and data) into a single word. This ensures that every instruction is accessed and executed in a single instruction cycle. LP One of the device oscillator modes. Used for low frequency operation which allows the oscillator to be tuned for low power consumption. Operation is up to 200 kHz. LSb (or LSB) Least Significant Bit. Machine cycle This is a concept where the device clock is divided down to a unit time. For PICmicro devices, this unit time is 4 times the device oscillator(4TOSC), also known as TCY. Machine Code Either object or executable code. Macro A collection of assembler instructions that are included in the assembly code when the macro name is encountered in the source code. Macros must be defined before they are used; forward references to macros are not allowed. Master Synchronous Serial Port The MSSP has two operational functions. The first is a “Serial Peripheral Interface (SPI)” and the second is the Inter-Integrated Circuit (“I2C”). The I2C function supports both master and slave functions in hardware. MCU Microcontroller Unit. An abbreviation for microcontroller. Also mC. Memory Models Versions of libraries and/or precompiled object files based on a device’s memory (RAM/ROM) size and structure.

102

Microcontroller A highly integrated chip that contains all the components comprising a controller. Typically this includes a CPU, RAM, some form of ROM, I/O ports, and timers. Unlike a general-purpose computer, which also includes all of these components, a microcontroller is designed for a very specific task - to control a particular system. As a result, the parts can be simplified and reduced, which cuts down on production costs. MIPS The unit commonly used to give the rate at which a processor executes 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.

103

MPSIM; Simulator The DOS version of Microchip’s simulator. MPLAB SIM is the newest simulator from Microchip. MSb Most Significant Bit. MSB Most Significant Byte. MSSP See “Master Synchronous Serial Port”. Non-Return to Zero (NRZ) Two-level encoding used to transmit data over a 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.

104

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.

105

PWM Signals See description under “Pulse Width Modulation (PWM)”. PSP See description under “Parallel Slave Port (PSP)”. Pulse Width Modulation (PWM) A serial signal in which the information is 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.

106

SFR Special Function Register. information for the device.

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.

107

Stack - Software The compiler uses a software stack for storing local variables and for passing arguments to and returning values from functions. Static RAM or SRAM Static Random Access Memory. Program memory you can Read/Write on the target board that does not need refreshing frequently. TAD In the A/D Converter, the time for a single bit of the analog voltage to be converted to a digital value. Target Refers to user hardware. Target Application Firmware residing on the target board. Target Board The circuitry and programmable device that makes up the target 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 E

Application Notes
Microchip Documentation The following documents are available from Microchip. Many of these documents provide application specific information that give actual examples of using, programming and designing with PICmicro MCUs. Fundamentals DS39500 DS33023 PIC18C reference manual Mid-Range MCU Family Reference Manual

Architecture and hardware design DS30277 AN522 AN607 AN594 AN579 AN588 In-Circuit Serial Programming Guide Power-Up Considerations Power-Up Troubleshooting Using the CCP modules Using the 8-bit Parallel Slave Port PIC16/17 Oscillator Design Guide

109

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

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