Vous êtes sur la page 1sur 26

PICMicrocontroller(MCU)

Widely used device from Microchip Technology


Sold > 10 billion PIC controllers
Several device families
Many devices per family
Common development environment

PIC
Microcontroller

Widely available
Large user base
Extensive application notes

Low cost
Free / low cost development tools
Basic architectural features
Pipelined RISC microprocessor core
Accumulator execution model
Data width 8 / 16 / 32 bits
Instruction width 12 / 14 / 16 / 32 bits

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

PICFamilies

PIC Microcontroller

Dr. Martin Land

Dr. Martin Land

TypicalApplications
Data
Width

Family

Architecture

8bitMCU

Embedded Systems Hadassah College Spring 2012

PIC10/PIC12/PIC16

Baseline
MidRange

Baseline
Replace discrete logic functions

Instruction
Width

Gates, simple state machines, encoders/decoders, etc.

12bits
8bits

PIC18

Disposable electronics

14bits

Drug / pregnancy testers, dialysis monitor, etc

Mid-Range
Digital sensors, displays, controllers, telecom equipment
Glucose / blood pressure set
PIC18
Integration with peripherals + networks

16bits

PIC24
16bitMCU

dsPIC30

Integrated
DSP

32bitMCU

16bits

16bits

32bits

32bits

USB, Ethernet, MCU-to-MCU, etc

Higher level analog peripherals, industrial control, major appliances


PIC24 / dsPIC30
16-bit ALU with integrated DSP

Data width
8 / 16/ 32 bits
Wider integer higher precision arithmetic

Portable EGK

Instruction width
12 / 14 / 16 / 32 bits
Wider instruction more complex instructions + higher precision arithmetic
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

PIC32
General purpose RISC microprocessor + controller
MRI
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

LearningPICArchitecture

8BitPICMCUs

Somegeneralobservations
Variety
Hundreds of PIC devices in 3 families and several sub-families
Updates

Datamemory

Organizedas8bitregisters
SomedevicesalsostoredataonEEPROM
16Bto4KB

Programmemory

Addressableunit=instructionword=12/14/16bits
Smallest:2Kword (3KBof12bitinstructions)
Largest:64Kword (128KBof16bitinstructions)

Architecture

PipelinedRISC
33to77instructions

Stack

Stores0(nostack)to31instructionaddresses
Usedforfunctioncalls

I/Odevices

8bitparallelports
Synchronous/asynchronousserialports
Timers+watchdogtimer
A/D+D/Aconverters
Pulsewidthmodulators

Microchip Technology upgrades devices frequently


Familiar devices replaced with new model
Instruction Set Architecture
8 and 16 bit devices share approximately uniform instruction set
PIC32 implements MIPS ISA
Caveats
Course takes general pedagogical approach to PIC as typical MCU
Focus on 8-bit devices Mid-Range + PIC18

Many books + websites on PIC with general-sounding titles


Each device is unique
Few statements are precisely true about each device
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

8BitPICOperationModel

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

Dr. Martin Land

PipelineOperation

ALU sources
Special WORKING register W
Data register or immediate
ALU destination
Data register or W

Instructioncycles(CY)

DataBus

Instruction
Fetch

Data
Memory

Execute
Decode

Address

Transfer operations
Data register W

Status

Status register
Flags produced by ALU operations

Instruction

Address

Instruction
Memory

Arithmetic
Logic
Unit
(ALU)

Data
Data
Memory

InstructionCycles

I1
I2
I3
I4

1
fetch

2
execute
fetch

execute
fetch

execute
fetch

execute

Branchinstructionsrequire2instructioncycles
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

PipelineOperation

ClockTypes

Clockcycles(OSC)
Instruction Cycle
4 cycles of external clock (oscillator)
CY = Q1 Q2 Q3 Q4
Instruction fetch
Q1

RC oscillator
Least expensive
Can be used for non-critical frequency accuracy and stability
Some devices have internal RC oscillator at 4 MHz

IR instructionregister
PC programcounter

UpdateProgramPointer

PC PC + 1

Fetch

IR [PC]

DecodeandExecute

Operationdependent

Crystal oscillator
Most stable

Q2 Q3
Q4

External clock
Provided by external digital system

Execution
Q1 Q4

Specific modes
LP mode frequencies between 32 kHz and 200 kHz
XT mode frequencies between 100 kHz and 4 MHz
HS mode frequencies between 8 MHz and 20 MHz

InstructionCycles

1
2
3
4
5
Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4
I1
fetch
execute

I2

fetch
execute

I3

fetch
execute

I4

fetch
execute
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

SleepMode

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

10

Dr. Martin Land

12

WakeUpEvents

Low-power mode
Main oscillator stopped
Most MCU functions stopped
Watchdog time continues
Power consumed < 1 mA for some models

Reset
Fetch instruction from address 0
Watchdog timer overflow
Normal execution of instruction following sleep

Instruction SLEEP

Interrupt
Interrupt not enabled ignore interrupt
Enabled
Normal execution of instruction following sleep
PC jumps to address 4 in program memory
Finds interrupt routine

MCU sleep mode


Data register values stable
Pipeline locked
Sleep instruction executes next instruction already fetched
On wake up
Next instruction executes
Recommendation instruction after sleep = NOP
Watchdog timer counter reset
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

11

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

WatchdogTimer

SomeTypical8bitPICDeviceFamilies

WDT oscillator (clock)


Independent from main clock
Continues in low power mode
May be disabled
WDT timeout
Timeout = 18 ms
Non-sleep mode

PIC12F5xx

PIC16F5xx

PIC10F3xx
PIC12F6xx
PIC16F6xx

PIC18F5xx

Instruction
word

12bits

12bits

12bits

14bits

16bits

Instructions

33

33

33

35

83

256 8192
words

2 Kwords
64 Kwords

Program
memory

MCU resets

Sleep mode
MCU wakes up executes instruction following sleep

Reset WDT
CLRWDT resets timeout = 18 ms
Prescaler
Divide time-base by 2k, k = 0, ... , 7
Extend timeout up to 2300 ms
Embedded Systems Hadassah College Spring 2012

PIC10F2xx

PIC Microcontroller

Dr. Martin Land

13

TypicalBaselineMCUPIC16X5xxFamily

256 512 512 1024 1024 2048


words
words
words

ROM

Flash

Flash

Flash

Flash

Flash

Datamemory
(bytes)

16 24

25 41

25 134

56 368

256 4K

Interrupts

int/ext

int /ext

Pins

14 40

6 64

18 100

I/Opins

12 32

4 54

16 70

Stack

2levels

2levels

2levels

8levels

31levels

Timers

2 3

2 5

Bulkprice

$0.35

$0.50

Embedded Systems Hadassah College Spring 2012

$0.50 $0.85 $0.35 $2.50 $1.20 $8.50


PIC Microcontroller

Dr. Martin Land

14

TypicalMidRangeMCU PIC16F873
8bitdata

8bitdata

14bitinstruction
12bitinstruction

General
I/Oports

W+ALU
Timers
A/D
UART
CompareCapturePulsewidth (CCP)
SynchronousSerialPort(SSP)

timer

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

GeneralI/Oports
ExternalInterrupt

Dr. Martin Land

15

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

16

TypicalPIC18MCU
8bitdata

MidRange
PICMCUs

16bitinstruction

Timers
A/D
UART
USB
CompareCapturePulsewidth (CCP)
ControllerAreaNetwork(CAN)
Embedded Systems Hadassah College Spring 2012

GeneralI/Oports
ExternalInterrupts
PIC Microcontroller

Dr. Martin Land

17

DataMemory/Registers

PIC Microcontroller

Dr. Martin Land

18

Special/GeneralRegisters

Register
Addressable location in data memory
8-bit word (byte)

GPR
General Purpose Registers
User program data

Data address space


9 bit address memory 29 = 512 bytes = 0.5 KB
Memory partitioned into banks
Bank = 27 = 128 = 80h registers (1/8 KB)
7 bit file address
Displacement in bank = 00h 7Fh

Read as 0
Write as NOP
PIC Microcontroller

SFR
Special Function Registers
Reserved for

7Fh

00h

Banks in address space


29-7 = 4 banks
2 to 4 banks implemented in device
Unimplemented banks

Embedded Systems Hadassah College Spring 2012

Embedded Systems Hadassah College Spring 2012

00

01

10

11

Control / configuration
Peripheral access
Indirect addressing
Program counter

bank

Core SFRs
Appear in every bank at
same file address

dataaddress
2bits

7bits

bank

fileaddress
Dr. Martin Land

19

Embedded Systems Hadassah College Spring 2012

Typical SFRs
STATUS

Statusword+flags

OPTION

Timeroptions

PCLATH
PCL

Componentsofprogram
counter(PC)

FSR

FileSelectforindirectdata
addressing

INTCON,PIR1,PIE1, Componentsofinterrupt
PIR2,PIE2
handling
PORTA,TRISA,

Accesstoparallelports

TMR0,OPTION,
INTCON,

Timer0

TXREG,TXSTA,
RCREG,RCSTA,

Accesstoserialport

ADRESH,ADRESL,
ADCON0,

AccesstoA/Dconverter

EEADRH,EEDATA,

AccesstoEEPROMand
Flashmemory

PIC Microcontroller

Dr. Martin Land

20

DataMemoryMap

StatusRegister
CoreSFRaccessibleatfileaddress03h ineverybank

Notes
(2,3)Notalllocations
implementedonall
devices
(4)CommonRAM
accessibleinallbanks
(onapplicabledevices)
(5)Notimplementedon
smallerdevices

Name

IRP

RP1

RP0

T0#

PD#

DC

Writable

R/W

R/W

R/W

RO

RO

R/W

R/W

R/W

Resetvalue

IRP
RP1, RP0
TO#

StateofWDT

PD#

Lowpower

Zeroflag

Carryout

C
PIC Microcontroller

Dr. Martin Land

21

AddressingDataMemory

DirectRegisterPointer
TO# 0 onWDToverflow
TO# 1 onpoweronreset,CLRWDT,SLEEP
PD# 0 onSLEEP
PD# 1 onCLRWDTandpoweronreset
Z 1 onALUzero
Z 0 onnonzero

C 1 oncarry(Addition)
C 0 onborrow(Subtraction)

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

22

AddressingDataMemory
Indirect addressing
Program writes to Special Function Registers (SFRs)

Notation
REG<b>

Bitb inregisterREG

REG<a:b>

Bitsa tob inregisterREG

A.B

ConcatenationofA andB
(A bitsfollowedbyB bits)

Address formed from SFRs

Instructions can increment/decrement SFR values


Similar to pointer arithmetic

Direct addressing
Program specifies data address
Bank selection
STATUS bits RP1 and RP0

File Select Register (FSR)


Core SFR accessible at file address 08h in all banks
RP1 RP0

7bitsfrominstruction

bank

fileaddress

File Address

IRP

FSR<6:0>
1

8bitsofFSR

bank

Bank

fileaddress
7

IRP.FSR<7>
STATUS bit IRP (Indirect Register Pointer)

On reset
RP1 = RP0 = 0 bank 0 selected

On small devices
1 or 2 banks = 128 or 256 bytes of data memory
8 bit FSR address covers 2 banks
IRP not implemented (read 0 / write = NOP)

Bank switching
Write to STATUS<6:5>

File Address
Literal field in instruction
Embedded Systems Hadassah College Spring 2012

IndirectRegisterPointer

Halfbytecarry DC 1 oncarry(Addition)
DC 0 onborrow(Subtraction)
(bits3,4)

DC

Embedded Systems Hadassah College Spring 2012

BankSelect

PIC Microcontroller

Dr. Martin Land

23

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

24

INDFRegister

InstructionMemorySpace
All8bitMCUs

INDF
Core SFR accessible at file address 00h in all banks

Instruction address
n bit location address

Virtual pointer not physical register


Tracks contents of FSR

Location = instruction
2n instructions

Simplifies pointer arithmetic


Example
In register file,
[05] = 10h
[06] = 0Ah
Load FSR 05
[INDF] = 10h
FSR++
[INDF] = 0Ah

Page

Page
1

Page
0

Instruction width
12 / 14 / 16 bits

;
;
;
;

Page
Partition of instruction
memory space
k
2 instructions / page
k bit offset

FSR points to file address 05


INDF points to file address 05
increment FSR FSR = 06
INDF points to file address 06

n bitaddress
n k bits

k bits

page

offset

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

25

InstructionMemorySpace

2 bits

= 8192 instruction words

k = 11
Page =

PIC Microcontroller

Dr. Martin Land

26

Accessible by instruction reads/writes

PC high (PCH) = PC<12:8>

offset
11

10

Not directly accessible to instructions

= 2048 = 800h words

PC latch high (PCLATH)


Core SFR accessible at file address 0Ah in all banks
PCH = PC<12:8> = PCLATH<4:0>
PCLATH<7:5> not implemented

Program counter (PC)


PC<12:11> = page number 4 pages
PC<10:0> = offset
Reserved addresses

page

Address 0h
PC

Address 4h
Interrupt vector pointer to interrupt service routine
PIC Microcontroller

offset

PCL

PCH

Reset vector pointer to reset routine

Embedded Systems Hadassah College Spring 2012

Memory
Location

PC register details
PC low (PCL) = PC<7:0>

13 bitPC
11 bits

page
12

211

11111

11000

01111

01011
01010
01001
01000
00111

00011
00010
00001
00000
page offset

Address

PCAccess

Mid-Range instruction memory


14-bit instruction word
n = 13
213

Embedded Systems Hadassah College Spring 2012

instruction

instruction

instruction

instruction
instruction
instruction
instruction
instruction

instruction
instruction
instruction
instruction

Dr. Martin Land

27

Embedded Systems Hadassah College Spring 2012

12

11

10

PCLATH

PIC Microcontroller

Dr. Martin Land

28

PCUpdates

Call/Return

Reset
PC 0

offset

page
PCH
PC

Non-branch instruction
PC PC + 1

PCL

12

11

10

PCLATH

Stack
8 level FILO buffer
Holds 13 bit instruction addresses on CALL/RETURN

Branch types
Direct branch

literal
PC

10

12

11

10

4
GOTO instruction
PCH<12:11> PCLATH<4:3>

PCLATH

5
5

4
4

1
1

STACK

0
0

Indirect branch

PCH
PC

Computed GOTO
Write to PCL as register
Copies PCL ALU result
Forces PCH PCLATH<4:0>

Embedded Systems Hadassah College Spring 2012

11

10

PCLATH

opcode

13

opcode

13

6
f

7 6

8 7

0
k

11 10

opcode

Embedded Systems Hadassah College Spring 2012

12

11

10

PCLATH

PCL literal<10:0> from instruction


PCH<12:11> PCLATH<4:3>
2

Dr. Martin Land

opcode

13

Function exit
RETURN instruction

29

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

30

InstructionSet

10 9

PC<12:0> STACK
PCLATH not updated
May be different from PCH after RETURN

PIC Microcontroller

STACK PC<12:0>

InstructionFormat
8

10

Function entry
CALL instruction

PCL ALU<7:0>

12

PC

RETURN

Offset = PC<10:0> literal<10:0> from instruction

13

literal

CALL

0
k

PIC Microcontroller

Datatransfer

Byte oriented
d = 0 destination = W
d = 1 destination = f
f = 7 bit file address

Mnemonic
MOVF f, d

Bit oriented
b = bit position in register
f = 7 bit file address
General literal
k = 8 bit literal (immediate)

CALL / GOTO
k = 11 bit literal (immediate)

Dr. Martin Land

31

Operation
d f

Comment
Move f to d

Flags
Z

MOVF f, 0
MOVF f, W

W f

d = W

MOVF f, 1
MOVF f, f
MOVF f

f f

d = f

MOVWF f

f W

Move W to f

MOVLW k

W k

Move literal to W

CLRF f

f 0

Clear f

CLRW

W 0

Clear W

Operands
name / address of register

destination

literal

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

W , d = 0
destination =
f , d = 1

Dr. Martin Land

32

InstructionSet

InstructionSet

ArithmeticandLogic 1
Mnemonic
ADDWF f, d
ADDLW k

ArithmeticandLogic 2

Operation
d f + W

Comment
Add w to f

Flags
C, DC, Z

Mnemonic
IORWF f, d

W k + W

Add k to W

C, DC, Z

IORLW k

SUBWF f, d

d f W

Sub W from f

C, DC, Z

SUBLW k

W k W

Sub W from k

INCF f, d

d f + 1

DECF f, d

d f 1

ANDWF f, d

d f and W

And w with f

ANDLW k

W k and W

And k with W

d f or W

Comment
OR w with f

Flags
Z

W k or W

OR k with W

XORWF f, d

d f xor W

XOR W with f

C, DC, Z

XORLW k

W k xor W

XOR W with k

Inc f to d

RLF f, d

d left rotate f,C

Dec f to d

RRF f, d

d right rotate f,C

COMF f, d

d #f (not f)

compliment f
to d

SWAPF f, d

d fL fH

nibble swap

Operands
name / address of register

destination

literal

Embedded Systems Hadassah College Spring 2012

W , d = 0
destination =
f , d = 1

PIC Microcontroller

Dr. Martin Land

33

InstructionSet

Operation

Operands
name / address of register

destination

literal

Embedded Systems Hadassah College Spring 2012

(nibble=halfbyte)

W , d = 0
destination =
f , d = 1

PIC Microcontroller

Dr. Martin Land

34

InstructionSet

Control

Other

Mnemonic

Operation

Mnemonic

Operation

Flags

branch to address

BCF f, b

f<b> 0

BTFSC f, b

skip one instruction if f<b> = 0

BSF f, b

f<b> 1

BTFSS f, b

skip one instruction if f<b> = 1

NOP

no operation

INCFSZ f, d

d f + 1, skip one if result = 0

CLRWDT

WDT 0

TO#, PD#

DECFSZ f, d

d f - 1, skip one if result = 0

SLEEP

go to low power consumption

TO#, PD#

GOTO a

CALL a

call subroutine in address a

RETURN

subroutine return

RETFIE

interrupt return

RETLW k

return from subroutine with k in W

Operands
name / address of register

11 bit address

Operands
name / address of register

destination

bit location

bit location

literal

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

35

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

36

SampleProgramFragments

SampleProgramFragments

RAMInitialization

Branchtoaddressinnewpage

CLRF STATUS
; STATUS 0
MOVLW 0x20
; W 1st address in GPR bank 0
MOVWF FSR
; Indirect address register W
Bank0_LP
CLRF INDF0
; address in GPR 0
INCF FSR
; FSR++ (next GPR address)
BTFSS FSR, 7
; skip if (FSR<7> == 1) FSR = 80h
GOTO Bank0_LP
; continue
; ** IF DEVICE HAS BANK1 **
MOVLW 0xA0
; W 1st address in GPR bank 1
MOVWF FSR
; Indirect address register W
Bank1_LP
CLRF INDF0
; address in GPR 0
INCF FSR
; FSR++ (next GPR address)
BTFSS STATUS, C ; skip if (STATUS<0> == 1) FSR = 00h
GOTO Bank1_LP
; continue

Prog:
movlw HIGH Prog10
; W Prog10<15:8>
; operator HIGH reads bits <15:8> of pointer
movwf PCLATH
; PCLATH W
goto Prog10
; PC<10:0> Prog10<7:0>
; PC<12:11> PCLATH<4:3>

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

Prog10:
;
; Prog10 labels some address in program memory
;

37

SampleProgramFragments
HIGH Prog20
PCLATH
LOW Prog20
PCL

Dr. Martin Land

38

ifelsebranch
;
;
;
;
;

W Prog10<15:8>
PCLATH W
W Prog10<7:0>
PCL Prog10<7:0>
PCH PCLATH<4:0>

btfss f,b

PIC Microcontroller

; skip one instruction if


; bit b in register f = 1

goto Action2
Action1:
; instructions for Action1
goto Action3
Action2:
; instructions for Action2
Action3:
; instructions for Action3

Prog20:
;
; Prog10 labels some address in program memory
;

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

SampleProgramsFragments

Computedgoto
movlw
movwf
movlw
movwf

Embedded Systems Hadassah College Spring 2012

Dr. Martin Land

39

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

40

SampleProgramsFragments

SampleProgramsFragments

Staticloop

Datatableininstructionmemory

movlw times
; W times
movwf COUNTER
; COUNTER W (times)
Loop:
;
; loop instructions
;
decfsz COUNTER, f
; COUNTER-; COUNTER = 0 skip next
instruction
goto Loop
; next iteration
End:
;
;

; Function call returns


movlw HIGH Table
movwf PCLATH
movf INDEX, W
call Table
;
Table:
addwf PCL, f

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

retlw
retlw
retlw
retlw
retlw
41

PICMCUandtheOutsideWorld
Oscillator
Generates device clock
Four device clock periods per instruction cycle
Ports
Data I/O pins
Electrical connections to external circuits

Configured to function as
Digital I/O
Analog inputs to A/D converter

PIC Microcontroller

Dr. Martin Land

42

Quartz crystal time base


Crystal connected between PIC pins OSC1 and OSC2
Vibrates in electric field piezoelectric resonance in voltage
Modes

OSC
Ports
Controls

PIC

Controls
Devicedependent
Power+ground
Interrupt(INT)
Externalclock

Timer

Counts clock cycles interrupt on preset count

A/D

Samples analog level converts to digital representation

Comparator

Samples 2 analog levels outputs bit (A1 > A2)

USART

Bit-parallel bit-serial converter for communications

CCP

Capture/Compare/PWM (Pulse Width Modulation)


PIC Microcontroller

Embedded Systems Hadassah College Spring 2012

; PCL PCL + W = PCL + INDEX


; computed goto
; return with W 'A'

ConfigurableOscillatorModes

Peripheral Modules
Share data pins with general ports

Embedded Systems Hadassah College Spring 2012

'A'
'B'
'C'
'D'
'E'

data at Table.INDEX
; W Table<15:8>
; PCLATH W
; W INDEX
; Call to subroutine table

Dr. Martin Land

43

LP Low Frequency / Low Power Crystal 32 kHz to 200 kHz


XT Crystal/Resonator 100 kHz to 4 MHz
HS High Speed Crystal/Resonator 8 MHz to 20 MHz

Resistor/Capacitor time base


Capacitor discharges through resistor in time = 2RC
Oscillator frequency f = 1 / (2RC)
Modes
EXTRC External RC connected between PIC pin OSC1 and ground
INTRC Internal 4 MHz RC
CLKOUT
EXTRC or INTRC with instruction clock (= f/4) output on OSC2
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

44

Interrupts

InterruptControlRegister

Interrupt
Instruction at current PC executes
Instruction at current PC+1 fetched
Stack PC+2
PC interrupt pointer
On return from interrupt PC stack
Interrupt sources
External interrupt pin

Interrupt Control Register (INTCON)


PEIE

T0IE

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

45

PeripheralInterruptEnable(PIE)
TMR1Overflow

TMR2IE

TMR2toPR2Match

CCP1IE

CCP1

CCP2IE

CCP2

SSPIE

SynchronousSerialPort

RCIE

USARTReceive

TXIE

USARTTransmit

ADIE
ADCIE

T0IF

INTF

RBIF

PEIE

PeripheralInterruptEnable

1=Enablesallunmaskedperipheralinterrupts
0=Disablesallperipheralinterrupts

T0IE

OverflowInterruptEnable

1=EnablesTMR0overflowinterrupt
0=DisablesTMR0overflowinterrupt

INTE

ExternalInterruptEnable

1=EnablesINTexternalinterrupt
0=DisablesINTexternalinterrupt

RBIE

RBPortChangeInterruptEnable

1=EnablesRBportchangeinterrupt
0=DisablesRBportchangeinterrupt

T0IF

OverflowInterruptFlag

1=TMR0registerhasoverflowed
0=TMR0registerdidnotoverflow

INTF

ExternalInterruptFlag

1=INTexternalinterruptoccurred
0=INTexternalinterruptdidnotoccur

RBIF

RBPortChangeInterruptFlag

1=AtleastoneofRB7:RB4pinschangedstate
0=NoneofRB7:RB4pinshavechangedstate

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

1=enabledeviceinterrupt
0=disabledeviceinterrupt

TMR1IE

1=TMR1 registeroverflowed
0=TMR1 registerdidnotoverflow

TMR2IE

SameasTMR1IE

CCP1IE

CCP1InterruptFlagbit
CaptureMode
1=TMR1 registercaptureoccurred
0=NoTMR1 registercaptureoccurred
CompareMode
1=ATMR1 registercomparematchoccurred
0=NoTMR1 registercomparematchoccurred
PWMMode
Unusedinthismode

A/DConverter
SlopeA/DConverterComparatorTrip

OVFIE

SlopeA/DTMROverflow
ParallelSlavePortRead/Write

CCP2IE

SameasCCP1IE

EEWriteComplete

SSPIE

1=Transmission/receptioncomplete
0=Waitingtotransmit/receive

RCIE

1=USARTreceivebufferRCREG full
0=USARTreceivebufferisempty

LCDIE
CMIE

LCD
Comparator

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

46

Dr. Martin Land

48

Number of PIR registers device dependent

PSPIE
EEIE

Dr. Martin Land

PeripheralInterruptRegister(PIR) 1

Number of PIE registers device dependent


TMR1IE

RBIE

GlobalInterruptEnable

Peripheral modules
General internal interrupt
A/D
Timer
Comparator
USART
CCP

INTE

1=Enablesallunmaskedinterrupts
0=Disablesallinterrupts

GIE

Pin RB0 on some PIC devices (separate pin on other devices)

GIE

Dr. Martin Land

47

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

PeripheralInterruptRegister(PIR) 2

InterruptLatency

Number of PIR registers device dependent


TXIE

1=USARTtransmitbufferTXREGempty
0=USARTtransmitbufferisfull

ADIE

1=A/Dconversioncomplete
0=A/Dconversionnotcomplete

ADCIE

1=A/Dconversioncomplete
0=A/Dconversionnotcomplete

OVFIE

1=SlopeA/DTMRoverflow
0=SlopeA/DTMRdidnotoverflow

PSPIE

1=Readorwriteoperationoccurred
0=Readorwritedidnotoccur

EEIE
LCDIE
CMIE

On interrupt
1. Current instruction execution completes
2. Current instruction fetch completes
3. PC interrupt pointer
Latency ~ 3 to 4 instruction cycles

1=DataEEPROMwriteoperationcomplete
0=DataEEPROMwriteoperationnotcomplete

1=LCDinterruptoccurred
0=LCDinterruptdidnotoccur

1=Comparatorinputchanged
0=Comparatorinputnotchanged

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

49

InterruptInitialization+Enabling
PIE1_MASK1 EQU B01101010

;
;
CLRF STATUS
CLRF INTCON
CLRF PIR1
BSF STATUS, RP0
MOVLW PIE1_MASK1
MOVWF PIE1
BCF STATUS, RP0
BSF INTCON, GIE

Embedded Systems Hadassah College Spring 2012

;
;
;
;
;
;

PIC Microcontroller

Dr. Martin Land

50

MacrosforRegisterSave/Restore
; Interrupt Enable
; Register mask (device
; dependent)

Bank0
Disable interrupts during
configuration
Clear flags
Bank1
set PIE1 via W

; Bank0
; Enable Interrupts

PIC Microcontroller

Embedded Systems Hadassah College Spring 2012

PUSH_MACRO MACRO
MOVWF W_TEMP
SWAPF STATUS,W
MOVWF STATUS_TEMP
ENDM

;
;
;
;
;

Save register contents


Temporary register W
W swap STATUS nibbles
Temporary register STATUS
End this Macro

POP_MACRO MACRO
SWAPF STATUS_TEMP,W
MOVWF STATUS
SWAPF W_TEMP,F
SWAPF W_TEMP,W

;
;
;
;
;
;
;

Restore register contents


W swap STATUS
STATUS W
W_Temp swap W_Temp
W swap W_Temp s
no affect on STATUS
End this Macro

ENDM

Dr. Martin Land

51

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

52

TypicalInterruptServiceRoutine(ISR) 1

TypicalInterruptServiceRoutine(ISR) 2

org ISR_ADDR

; store at ISR address

PUSH_MACRO

; save context registers W, STATUS

CLRF STATUS

; Bank0

T1_INT
:
BCF PIR1, TMR1IF
GOTO END_ISR
AD_INT
:
BCF PIR1, ADIF
GOTO END_ISR
LCD_INT
:
BCF PIR1, LCDIF
GOTO END_ISR
PORTB_INT
:
END_ISR
POP_MACRO
RETFIE

; switch implementation in PIC assembly language


BTFSC PIR1, TMR1IF

; skip next if (PIR1<TMR1IF> == 1)

GOTO T1_INT

; go to Timer1 ISR

BTFSC PIR1, ADIF

; skip next if (PIR1<ADIF> == 1)

GOTO AD_INT

; go to A/D ISR

BTFSC PIR1, LCDIF

; skip next if (PIR1<LCDIF> == 1)

GOTO LCD_INT

; go to LCD ISR

BTFSC INTCON, RBIF

; skip next if (PIR1<RBIF> == 1)

GOTO PORTB_INT

; go to PortB ISR

GOTO INT_ERROR_LP1

; default ISR

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

53

Timers

; Timer1 overflow routine


; Clear Timer1 overflow interrupt flag
; Leave ISR
; Routine when A/D completes
; Clear A/D interrupt flag
; Leave ISR
; LCD Frame routine
; Clear LCD interrupt flag
; Leave ISR
; PortB change routine
; Leave ISR
; Restore registers
; Return and enable interrupts

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

54

PIC Microcontroller

Dr. Martin Land

56

WatchdogTimer(WDT)

Watchdog timer (WDT)


Normal program resets timer before timeout (18 ms)
Timeout

Time base
Internal RC oscillator
Timer0 clock source

Non-sleep mode MCU resets


Sleep mode MCU wakes up executes instruction following sleep

Configured in OPTION_REG SFR


Timer0
Generic programmable 8-bit timer/counter
Shares prescaler (divide by 2k, k = 0,...,8) with WDT
Configured in OPTION_REG SFR
Timer1
Generic programmable 16-bit timer/counter
Read / write two 8-bit registers
Timer2
Generic programmable 8-bit timer/counter
Time base for PWM mode
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

55

Embedded Systems Hadassah College Spring 2012

OPTION_REGSFR(FileAddress081h)

Timer0

RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

8-bit timer/counter
Readable / writable at TMR0 SFR (File Address 081h)

WeakPullupEnable

1=Weakpullupsaredisabled
0=Weakpullupsareenabledbyportlatchvalues
Underline active=0/inactive=1

8-bit software programmable prescaler

RBPU

INTEDG

InterruptEdgeSelect

1=InterruptonrisingedgeofINTpin
0=InterruptonfallingedgeofINTpin

Selectable clock source

T0CS

TMR0ClockSourceSelect

1=TransitiononT0CKIpin
0=Internalinstructioncycleclock(CLKOUT)

Interrupt on overflow FFh 00h

T0SE

TMR0SourceEdgeSelect

1=IncrementonhightolowtransitiononT0CKIpin
0=IncrementonlowtohightransitiononT0CKIpin

PSA

PrescalerAssignment

1=PrescalerisassignedtotheWDT (watchdog)
0=PrescalerisassignedtotheTimer0module

PS2:PS0

PrescalerRateSelect

Embedded Systems Hadassah College Spring 2012

Divide input pulse train (slows time scale)


Scale by 1:1 , 1:2, 1:4, ... , 1:128
External / internal

PS2:PS0

TMR0

WDT

PS2:PS0

TMR0

WDT

000
001
010
011

1:2
1:4
1:8
1:16

1:1
1:2
1:4
1:8

100
101
110
111

1:32
1:64
1:128
1:256

1:16
1:32
1:64
1:128

PIC Microcontroller

Dr. Martin Land

Edge select (phase synchronization with external clock)

57

Timer0Operation

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

58

InitializeTimer0withInternalClockSource

Timer mode
T0CS = 0
TMR0++ on every instruction cycle (without prescaler)
Write to TMR0 register no increment for two instruction cycles
Counter mode
T0CS = 1
TMR0++ on every rising or falling edge of T0CKI (external clock)

CLRF TMR0

; Clear Timer0 register

CLRF INTCON

; Disable interrupts and clear T0IF

BSF STATUS, RP0

; Bank1

MOVLW 0xC3

; Disable PortB pull-ups


; C3 = 11000011

MOVWF OPTION_REG

Edge determined by T0SE bit

; Interrupt on rising edge of RB0


; Timer0 increment from internal clock

Prescaler
Set by PSA control bits
TMR0 Interrupt
Generated on overflow FFh 00h
Sets bit T0IF (INTCON<2>)

; Prescale = 1:16.
BCF STATUS, RP0

; Bank0

T0_OVFL_WAIT

Timer0 interrupt service routine

BTFSS INTCON, T0IF

; poll overflow bit

GOTO T0_OVFL_WAIT

; on timer overflow

Clear T0IF
Re-enable interrupt
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

59

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

60

Timer1

T1CONSFR

16-bit timer/counter
TMR1 pair TMR1H:TMR1L

T1CKPS1 T1CKPS0 T1OSCEN


7

Readable and writable 8-bit registers

Counter 0000h to FFFFh with rollover to 0000h

Embedded Systems Hadassah College Spring 2012

1=Oscillatormodeenabled
0=Oscillatormodedisabled

Input

Timer1ExternalClock
InputSynchronization
Select

Dr. Martin Land

61

Timer1Operation

TMR1CS = 1 (CounterMode)
1=AsynchronousCounterMode
0=SynchronousCounterMode
TMR1CS = 0 (TimerMode)
Ignored

Timer1ClockSource
Select

1=CounterMode(countexternalclock)
0=TimerMode(countinternalclockFOSC /4)

TMR1ON

Timer1On

1=EnablesTimer1
0=StopsTimer1

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

62

ReadingTimer1
; All interrupts disabled
MOVF TMR1H, W
; W high byte
MOVWF TMPH
; TMPH W
MOVF TMR1L, W
; W low byte
MOVWF TMPL
; TMPL W
; TMR1L can roll-over between reads of high and low bytes
MOVF TMR1H, W
; W high byte again
SUBWF TMPH, W
; Verify high byte
BTFSC STATUS,Z ; bad read (Z = 0 not equal) re-do
GOTO CONTINUE
; New reading good value.
MOVF TMR1H, W
; W high byte
MOVWF TMPH
; TMPH W
MOVF TMR1L, W
; W low byte
MOVWF TMPL
; TMPL W
; Re-enable interrupts (if required)
CONTINUE
; Continue

Async
Input

CLKIn/OSCout
CounterMode

Sampling

TimerMode
OscillatorMode T1CKI T1OSI

Embedded Systems Hadassah College Spring 2012

01=1:2Prescalevalue
00=1:1Prescalevalue

TMR1CS

Sampled
Input

PIC Microcontroller

Timer1OscillatorEnable

TMR1++ on rising edge of input pin

Sample
Clock

T1OSCEN

Asynchronous counter

Synchronized to internal clock TOSC


Sample input pin on rising edge of TOSC
Input must be high / low for at least 2TOSC

11=1:8Prescalevalue
10=1:4Prescalevalue

T1SYNC

TMR1++ on rising edge of sampled input pin

TMR1ON

Timer1InputClock
PrescaleSelect

Modes
Synchronous timer

Synchronous counter

TMR1CS

T1CKPS1
T1CKPS0

Generate Timer1 interrupt on rollover (if enabled)

TMR1++ on every instruction cycle (FOSC / 4)

T1SYNC

PIC Microcontroller

Dr. Martin Land

63

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

64

WritingTimer1

Timer2
Readable / writable 8-bit timer
Prescaler
Period register PR2

; All interrupts are disabled


CLRF TMR1L

; Clear Low byte


; Prevents rollover to TMR1H

MOVLW HI_BYTE

; W HI_BYTE

MOVWF TMR1H, F

; TMR1H W

MOVLW LO_BYTE

; W LO_BYTE

MOVWF TMR1L, F

; TMR1L W

Readable / writable
TMR2 = PR2 reset (TMR2 0)

Postscaler
Counts TMR2 = PR2 resets
Triggers TMR2IF interrupt flag

; Re-enable interrupts (if required)


CONTINUE
; Continue

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

65

T2CONSFR

PIC Microcontroller

Dr. Martin Land

66

Ports

TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0


7

Embedded Systems Hadassah College Spring 2012

TMR2ON
2

T2CKPS1 T2CKPS0
1

I/O pins
Electrical connections to external circuits
Configurable in SFR ADCON1 as

TOUTPS3:0

Timer2Output
Postscale Select

0000=1:1Postscale
0001=1:2Postscale
0010=1:3Postscale
0011=1:4Postscale
:
1111=1:16Postscale

TMR2ON

Timer2On

1=Timer2ison
0=Timer2isoff

T2CKPS1:0

Timer2Clock
PrescaleSelect

00=Prescaleris1
01=Prescaleris4
1x=Prescaleris16

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

OSC
Ports
Controls

PIC

Digital I/O
Analog inputs to A/D converter
Mid-Range PIC configurations
Minimal Port A (6 pins) + Port B (8 pins)
Maximal Port A (6 pins), Port B (8 pins), ... , Port G (8 pins)
Special Function Registers
Data
PORTA , ... , PORTG
PORTi<x> = data bit on pin x of port i

Direction
TRISA, ... , TRISG
TRISi<x> = 1 pin x of port i is Input
TRISi<x> = 0 pin x of port i is Output
Dr. Martin Land

67

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

68

PortAccess

PORTA

Output
Set TRISi<x> = 0
Write data bit to PORTi<x>

5 general purpose I/O pins


RA5 and RA3:RA0
Standard electrical behavior
TTL input levels and CMOS output drivers

Input
Set TRISi<x> = 1
Read data bit from PORTi<x>

Special input
RA4
Schmitt trigger input
Threshold decision converts input to binary (RA4 > threshold)

Order of operations
Read

Open drain output


Permits specialize electrical functions on output
Wired-OR, analog weighting, ...

Reads levels on physical I/O pins (not data register file)

Write
Implemented as read modify
Causes update of all input data registers from physical I/O pins
Program must read all required inputs before any write

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

69

InitializingPORTA
CLRF STATUS
CLRF PORTA
BSF STATUS, RP0
MOVLW 0xCF

MOVWF TRISA

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

70

Dr. Martin Land

72

PORTB
;
;
;
;
;
;
;
;
;

8 general purpose I/O pins


RB7:RB0

Bank0
Initialize PORTA
Select Bank1
Initialize data directions
CFh = 11001111
= x x Out Out In In In In
PORTA<3:0> = inputs
PORTA<5:4> = outputs
TRISA<7:6> always read 0

Standard electrical behavior


TTL input levels and CMOS output drivers

Interrupt on change
Input pins RB7:RB4
Inputs compared with previous read of PORTB
OR(compare bits) = 1 RB Port Change Interrupt
Can wake device from SLEEP
Example wake-up on key press

Clear interrupt
Read or write PORTB
Clear flag bit RBIF
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

71

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

PortsCtoG

AnalogtoDigital(A/D)ConverterModule

Ports C to E
8 binary I/O pins

Converts analog input signals


Sample and hold
One of 8 analog inputs (channels)
Conversion to 8-bit binary number

Ri7:Ri0, i = C, D, E

Schmitt trigger on each input pin

Analog reference voltage


Software selectable
Device supply voltage
Voltage level on VREF pin

Ports F and G
Ri7:Ri0, i = F, G

Can operate in sleep mode

8 binary inputs

Three registers
A/D Result Register (ADRES)
A/D Control Register0 (ADCON0)
A/D Control Register1 (ADCON1)

Schmitt trigger on each input

8 LCD driver outputs


Direct connection to 7-segment display

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

73

ADCON0SFR
ADCS0

CHS2

CHS1

CHS0

GO/DONE

Resv

ADON

A/D Conversion Clock Select


10=fOSC/32
11=fRC (internalA/DRCosc)

00=fOSC/2
01=fOSC/8

Analog Channel Select


CHS2:CHS0

PIC Microcontroller

Dr. Martin Land

74

ADCON1SFR

ADCS1

ADCS1:ADCS0

Embedded Systems Hadassah College Spring 2012

000=channel0(AN0)
001=channel1(AN1)
010=channel2(AN2)

011=channel3(AN3)
:
111=channel7(AN7)

A/D Conversion Status

GO/DONE

0=notinprogress

1=inprogress
Reserved
ADON
1=activated
Embedded Systems Hadassah College Spring 2012

PCFG2

PCFG1

PCFG0

PCFG2:PCFG0

AN7

AN6

AN5

AN4

AN3

AN2

AN1

AN0

000

001

VREF

010

011

VREF

100

101

VREF

11x

Portpinconfiguredforanaloginput

PortpinconfiguredfordigitalI/O

AN3=VREF

ConversioncomparestoreferencevoltageVREF=voltageonAN3

A/D On

AN3=D

ConversioncomparestoreferencevoltageVREF=devicesupplyvoltage

0=deactivated
PIC Microcontroller

Dr. Martin Land

75

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

76

OperationofA/DConverter

A/DConversion

Configure A/D module


Analog pins + voltage reference + digital I/O in ADCON1
Select A/D input channel (ADCON0)
Select A/D conversion clock (ADCON0)
Activate A/D module (ADCON0)

BSF STATUS, RP0


; Bank1
CLRF ADCON1
; Configure inputs as analog
BSF PIE1, ADIE
; Enable A/D interrupts
BCF STATUS, RP0
; Bank0
MOVLW 0xC1
; C1h = 11000001
MOVWF ADCON0
; Internal RC, A/D active, Channel 0
BCF PIR1, ADIF
; Clear A/D interrupt flag
BSF INTCON, PEIE
; Enable peripheral interrupts
BSF INTCON, GIE
; Enable all interrupts
;
; Wait required sampling time for selected input
;
BSF ADCON0, GO
; ADCON0<2> 1 Start conversion
; On completion ADIF bit 1 and GO/DONE 0

Configure A/D interrupt (optional)


Clear ADIF
Set ADIE + GIE
Start conversion
Set GO/DONE bit (ADCON0)
Wait for A/D conversion to complete
Poll GO/DONE until cleared or wait for A/D interrupt
Read result
A/D Result register (ADRES)
Repeat
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

77

Comparator

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

78

PIC Microcontroller

Dr. Martin Land

80

ComparatorModes 1

Two analog comparators


Inputs shared with I/O pins
Access via CMCON SRF (device-dependent file address)
Operation
Analog input at VIN+ < VIN output = binary 0
Analog input at VIN+ > VIN output = binary 1
CMCON SFR
C2OUT

C1OUT

CIS

CM2

CM1

CM0

C2OUT
C1OUT

Comparator
Outputs

1 = VIN+ > VIN


0 = VIN+ > VIN

CIS
CM2:CM0

Comparator
InputSwitch

Seetableonfollowingslides

responsetime
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

79

Embedded Systems Hadassah College Spring 2012

ComparatorModes 2

InitializeComparator
FLAG_REG EQU 0x20
CLRF FLAG_REG
CLRF PORTA
ANDLW 0xC0
IORWF FLAG_REG,F
MOVLW 0x03
MOVWF CMCON
BSF STATUS,RP0
MOVLW 0x07
MOVWF TRISA

BCF STATUS,RP0
CALL DELAY 10
MOVF CMCON,F
BCF PIR1,CMIF
BSF STATUS,RP0
BSF PIE1,CMIE
BCF STATUS,RP0
BSF INTCON,PEIE
BSF INTCON,GIE
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

81

USART

Embedded Systems Hadassah College Spring 2012

;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;

FLAG_REG points to address 20h


flag register 0
PORTA 0
Mask comparator bits W<5:0> 0
FLAG_REG FLAG_REG OR W
Init comparator mode
CM<2:0> = 011 (2 common reference)
Bank1
Initialize data direction
Set RA<2:0> as inputs
RA<4:3> as outputs
TRISA<7:5> read 0
Bank0
10ms delay
Read CMCON (enter read mode)
Clear pending interrupts
Bank1
Enable comparator interrupts
Bank0
Enable peripheral interrupts
Global interrupt enable
PIC Microcontroller

Dr. Martin Land

82

USARTTransmitOperation

Universal Synchronous / Asynchronous Receiver / Transmitter


Serial Communications Interface (SCI)

Data
Byte TXREG framing TSR bit FIFO TX pin

PC serial port / modem

Framing add start bit / parity bit

Transmit
Parallel serial
Data byte as 8 serial bits

InterruptonemptyTXREG

Receive
Serial parallel
Assemble 8 bits as data byte

Modes
Asynchronous
Full duplex simultaneous transmit + receive

Synchronous

TSRfull/emptyPortEnable

Half duplex transmit or receive


Master synchronize data to internal clock
Slave synchronize data to external clock
Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

TransmitSpeed

Dr. Martin Land

83

Embedded Systems Hadassah College Spring 2012

Paritybit

PIC Microcontroller

Dr. Martin Land

84

USARTReceiveOperation

Capture/Compare/PWM(CCP)Module

Data
RX pin bit FIFO RSR RCREG byte

SFRs
CCP control register (CPCON)
CCPR High byte / Low byte (CCPRH / CCPRL)

Framing
Identify data between stop bits
Check for parity error

OverrunError

I/O pin
CPP pin (CPPx) device-dependent pin configured in TRIS SFR

FramingError

ContinuousReceiveEnable

Capture Mode
Captures 16-bit value of register TMR1 on CCPx event
Every falling edge / rising edge / 4th rising edge / 16th rising edge

Triggers interrupt
Compare mode
Compare 16-bit (CCPR == TMR1)

Sample+FIFO

Paritybit

Configurable response on match


CCPx 0 / 1
Interrupt with no change on CPPx

PortEnable

RCREGfull

Embedded Systems Hadassah College Spring 2012

Pulse Width Modulation (PWM) mode


Generates duty cycle waveform on CCPx

PIC Microcontroller

Dr. Martin Land

85

CCPxCONSFR
7

DCxB1:DCxB0

Embedded Systems Hadassah College Spring 2012

Period
Dutycycle

PIC Microcontroller

Dr. Martin Land

86

CaptureMode
DCxB1

DCxB0

CCPxM3

CCPxM2

CCPxM1

CCPxM0

Event
Input pin CCPx divided by prescaler sampled on rising / falling edge

PWMDutyCycle DCx1:DCx0of10bitPWMdutycycle
bit1andbit0
DCx9:DCx2inCCPRxL

Interruptflag,x=1,2

CCPxR =CCPRxH:CCPRxL,x=1,2

CCPxM3:CCPxM0

Embedded Systems Hadassah College Spring 2012

CCPx Mode
Selectbits

0000=Capture/Compare/PWMoff(resets CCPx module)


0100=Capturemode,everyfallingedge
0101=Capturemode,everyrisingedge
0110=Capturemode,every4thrisingedge
0111=Capturemode,every16thrisingedge
1000=Comparemode,CCPlowtohigh
1001=Comparemode,CCPhightolow
1010=Comparemode,softwareinterruptonmatch
1011=Comparemode,Triggerspecialevent
11xx=PWMmode

PIC Microcontroller

Dr. Martin Land

87

16bitvalueinTimer1
Configuration
CCPcontrolregister,x=1,2

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

88

CompareMode

PulseWidthModulation(PWM)mode
Generates duty cycle waveform

16-bit compare
(CCPRx == TMR1), x = 1, 2
ResetTimer1

Setdutycycle
Interrupt

Period=(PR2+1) 4 prescale TOSC


Dutycycle=DC prescale TOSC
16bitpresetvalueinCCPRx

Period
Dutycycle

0 PR2 255
0 DC 1023

16bitvalueofTimer1

Setperiod

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

89

DutyCycle

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

90

Dr. Martin Land

92

DutyCycleExample
Frequencyanddutycyclefromgivenparameters

TPWM = 4 P TOSC

fOSC = 20MHz TOSC = ( 20MHz ) = 50ns


-1

TPWM = 4 (PR2 + 1) P TOSC

P=1
PR2 = 63 TPWM = 4 64 50ns = 12.8s

TON = DC P TOSC
TON = P TOSC

fPWM = (12.8s ) = 78.125kHz


-1

DutyCycle
TON
DC P TOSC
DC
=
=
TPWM 4 (PR2 + 1) P TOSC 4 (PR2 + 1 )

DC = 32 TON = 32 50ns = 1.6ms

TON
1 DC 4 (PR2 + 1)
TPWM

TON
32
=
= 0.125 = 12.5%
TPWM 4 64

Controllability
TON
P TOSC
1
=
=
TPWM 4 (PR2 + 1 ) P TOSC 4 (PR2 + 1 )

TON
1
1
=
=
= 0.00390625
TPWM 4 64 256

Resolution
DC 4 (PR2 + 1) 2r =
Embedded Systems Hadassah College Spring 2012

log ( 4 (PR2 + 1 ) P )
TON
4 (PR2 + 1) P r =
TOSC
log ( 2 )
PIC Microcontroller

Dr. Martin Land

2r =
91

log ( 256 )
TON
4 64 r =
=8
TOSC
log ( 2 )

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

PWMExample

PWMExample

Choosingparameters

Code

Internal oscillator
fOSC =4MHz TOSC =0.25s

Oscillatorfrequency=4MHz
Produceoutputwith
1kHzfrequency(TPWM =1ms)
10%dutycycle

PWM frequency

Init_pwm:

TPWM =1ms=4 (PR2+1) P 0.25s=(PR2+1) P 1s


Require(PR2+1) P=1000
Preset and PR2

P=4 PR2+1=250 PR2=249=0xF9


TON =P TOSC =1s
Duty cycle = 10%

TON =0.10 1ms=100s


DC=0.10 4 (PR2+1) =100 =0x064 DCH =0x19=25DCL=0

TON_pwm:

List p = 16F873
include "P16F873.INC"
movlw 0x01
;
movwf T2CON
;
clrf CCP1CON
;
clrf TMR2
;
movlw .25
;
movwf CCPR1L
;
bsf STATUS, RP0
;
movlw .249
;
movwf PR2
bcf PIE1, TMR2IE
;
bcf PIE1, CCP1IE
;
bcf TRISC, 2
;
bcf STATUS, RP0
;
clrf PIR1
;
movlw 0x0C
;
movwf CCP1CON
;
bsf T2CON, TMR2ON
;
return
movwf CCPR1L
;
return
;
end

Stop Timer2
Prescaler 4
Reset module CCP1
Timer2 0
10% duty cycle
DC1B9:DC1B2
Bank 1
Timer2
Disable Timer2 interrupt
Disable CCP1 interrupt
Pin CCP1 = output
Bank 0
Clear interrupt flags
CCP1 in PWM mode
DC1B1:DC1B0 0
Start Timer2
Call to change
Duty cycle

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

93

DataEEPROM

PIC Microcontroller

Dr. Martin Land

94

EECON1SFR

Additional long term data memory


Internal EEPROM
Indirect addressing
Not directly mapped in register file space
Access through SFRs

EECON1
Control bits
EECON2
Initiates read / write operation
Virtual register not physically implemented
EEDATA
8-bit data for read / write
EEADR
Access address in EEPROM
8-bit address 256 EEPROM locations

Embedded Systems Hadassah College Spring 2012

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

95

EEIF

WRERR

WREN

WR

RD

EEIF

WriteOperation
InterruptFlag

1=Writeoperationcompleted
0=Writeoperationnotcomplete/notstarted

WRERR

ErrorFlag

1=Writeoperationprematurelyterminated
0=Writeoperationcompleted

WREN

WriteEnable

1=Allowswritecycles
0=InhibitswritetodataEEPROM

WR

WriteControl

1=Initiateswritecycle
0=WritecycletodataEEPROMiscomplete(clearedbyhardware)

RD

ReadControl

1=Initiatesread
0=DoesnotinitiateanEEPROMread(clearedbyhardware)

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

96

EECON2SFR

EEPROMRead/Write/Verify 1
Read
BCF STATUS, RP0
MOVLW CONFIG_ADDR
MOVWF EEADR
BSF STATUS, RP0
BSF EECON1, RD
BCF STATUS, RP0

Not physical register


Read EECON2 0
SFR access to EEPROM write hardware
Data EEPROM write sequence
EEDATA data
EEADR address_for_write
W 55h
EECON2 W
W AAh
; EECON2 55AAh
EECON2 W
; initiate(writecontrolbitset)
EECON1<WR> 1

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

MOVF EEDATA, W
Write
BSF STATUS, RP0
BCF INTCON, GIE
BSF EECON1, WREN
MOVLW 55h
MOVWF EECON2
MOVLW AAh
MOVWF EECON2
BSF EECON1,WR
BSF INTCON, GIE
Dr. Martin Land

97

EEPROMRead/Write/Verify 2

SUBWF EEDATA, W
BTFSS STATUS, Z
GOTO WRITE_ERR

Embedded Systems Hadassah College Spring 2012

; W EEDATA
;
;
;
;
;
;
;
;
;

Bank1
Disable INTs
Enable write

W 55h
EECON2 W
W AAh
EECON2 W
Set WR bit (initiates write)
Enable INTs

PIC Microcontroller

Dr. Martin Land

98

Determines certain device modes


Oscillator mode, WDT reset, copy protection
Sets device state on power-up
Configured during EEPROM programming

; Bank0
; copy write request data to W
; Bank1

Mapped to program memory location 2007h

; Initiate read
; Bank0

Not accessible at run time

; W write request read


; Skip next if (Z == 1)
; Handle write error

PIC Microcontroller

Bank0
Address in Data EEPROM
Set read address
Set Bank1
Initiate EEPROM Read
Set Bank0

PICConfigurationBits 1

Verify
BCF STATUS, RP0
MOVF EEDATA, W
BSF STATUS, RP0
READ
BSF EECON1, RD
BCF STATUS, RP0

Embedded Systems Hadassah College Spring 2012

;
;
;
;
;
;

Dr. Martin Land

99

CP1:CP0

CodeProtection

11=Codeprotectionoff
10=devicedependent
01=devicedependent
00=memorycodeprotected

DP

DataEEPROMCodeProtection

1=Codeprotectionoff
0=DataEEPROMMemorycodeprotected

BODEN

BrownoutResetEnable

1=BORenabled
0=BORdisabled

PWRTE

PowerupTimerEnable

1=PWRT disabled
0=PWRT enabled

MCLRE

MCLR (masterclear)PinFunction

1=Pinfunction=MCLR
0=Pinfunction=digitalI/O

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

100

PICConfigurationBits 2
WDTE

WatchdogTimerEnable

1=WDTenabled
0=WDTdisabled

FOSC1:FOSC0

OscillatorSelection
FordeviceswithnointernalRC

11=RCoscillator
10=HSoscillator
01=XToscillator
00=LPoscillator

OscillatorSelection
FordeviceswithinternalRC

111=EXTRCoscillator,withCLKOUT
110=EXTRCoscillator
101=INTRCoscillator,withCLKOUT
100=INTRCoscillator
011=Reserved
010=HSoscillator
001=XToscillator
000=LPoscillator

FOSC2:FOSC0

Embedded Systems Hadassah College Spring 2012

PIC Microcontroller

Dr. Martin Land

101